AI Agent 教程
按顺序阅读,循序渐进掌握相关 AI 工具与实战方法。
在 Harness 中,ctx.tools、ctx.llm、ctx.agents 都是服务——一个插件向其他插件公开的能力。服务占据一个稳定的 ctx.<key>,其他插件按 key 查找服务,而不是导入具体实现。内置服务的名称与接口以仓库自动生成的子系统页面和 TypeScript 接口为准。
在插件里声明 inject,框架保证 apply() 执行时所声明的服务全部就绪;没准备好时插件会一直等待:
export const inject = ['tools']
export function apply(ctx: Context) {
// ctx.tools 一定存在且已就绪
ctx.tools.register(/* ... */)
}
派生 Service 子类,构造函数里用 super(ctx, '服务名') 注册命名服务;服务自身也能用静态 inject 声明依赖:
import { Service, type Context } from '@deepseek-ai/cordis'
export default class MetricsService extends Service {
static inject = ['llm'] // 本服务需要 llm 先就绪
constructor(ctx: Context) {
super(ctx, 'metrics') // 挂载为 ctx.metrics
}
record(event: string, value: number) {
// 记录一条指标,实现省略
}
}
加载后,消费方声明依赖即可调用:ctx.metrics.record('izzi_tool_call', 1)。
用 TypeScript 声明合并给 ctx.metrics 补类型,获得自动补全与编译期检查;类型与实现写在同一文件,避免漂移:
declare module '@deepseek-ai/cordis' {
interface Context {
metrics: MetricsService
}
}
必需依赖用 inject 声明,服务缺席时插件停在 PENDING 不加载;可选依赖省略 inject,在使用处用 ctx.get() 查询,可能返回 undefined:
// 必需依赖:tools 缺席时插件不加载
export const inject = ['tools']
export function apply(ctx: Context) {
// 可选依赖:用可选链安全调用
const metrics = ctx.get('metrics')
metrics?.record('izzi_plugin_loaded', 1)
}
服务可有可无、缺席时插件也要正常工作,就用可选依赖。
运行期间必需服务消失(如提供方被卸载)时:依赖它的插件自动 dispose 释放资源;服务重新出现时插件自动重新加载。这样插件永远不会调到已不存在的服务。
Service 子类用 super(ctx, '名字') 提供命名服务,declare module 合并补类型,inject 声明必需依赖、ctx.get() 查询可选依赖。自测:服务名由哪个参数决定?如何让 ctx.metrics 有类型提示?两种依赖写法有何不同?