对话 API
@grant CAT.agent.conversation
对话 API 是 Agent 系统的核心,允许脚本创建 AI 对话、发送消息并接收回复。
创建对话
const conv = await CAT.agent.conversation.create(options?);
ConversationCreateOptions
| 参数 | 类型 | 默认值 | 说明 |
|---|---|---|---|
id | string | 自动生成 | 对话 ID,用于恢复已有对话 |
system | string | — | 自定义系统提示词,追加到内置提示词之后 |
model | string | 默认模型 | 模型 ID(在管理页面配置后获取) |
maxIterations | number | 20 | 单次对话中工具调用的最大循环次数 |
skills | "auto" | string[] | — | "auto" 自动加载所有 Skill,或指定 Skill 名称数组 |
tools | ToolDefinition[] | — | 自定义工具列表(见下方) |
commands | Record<string, CommandHandler> | — | 自定义对话命令 |
ephemeral | boolean | false | 临时对话,不持久化到存储 |
cache | boolean | true | 启用 Prompt Caching(减少 Token 消耗) |
background | boolean | false | 后台对话,UI 断开后继续执行,可通过 attach() 重新连接 |
自定义工具
脚本可以注册自己的工具供 AI 调用:
const conv = await CAT.agent.conversation.create({
tools: [{
name: "get_weather",
description: "获取指定城市的天气信息",
parameters: {
type: "object",
properties: {
city: {
type: "string",
description: "城市名称"
},
unit: {
type: "string",
enum: ["celsius", "fahrenheit"],
description: "温度单位"
}
},
required: ["city"]
},
handler: async (args) => {
// args = { city: "北京", unit: "celsius" }
const data = await fetchWeather(args.city, args.unit);
return { temperature: data.temp, condition: data.condition };
}
}]
});
工具的 parameters 遵循 JSON Schema 规范,AI 会根据 description 理解何时及如何调用工具。
自定义命令
可以注册以 / 开头的自定义命令:
const conv = await CAT.agent.conversation.create({
commands: {
"/export": async (args) => {
// 用户输入 "/export pdf" 时触发
await exportToPdf(args);
return "导出完成";
}
}
});
内置命令:/new(新建对话)、/reset(重置上下文)、/compact(压缩历史消息)。
获取已有对话
const conv = await CAT.agent.conversation.get(conversationId);
// 如果对话不存在则返回 null
ConversationInstance 方法
chat — 同步聊天
const reply = await conv.chat(content, options?);
发送消息并等待完整回复返回。AI 可能在回复过程中调用工具,chat 会等待所有工具执行完成后返回最终结果。
参数:
| 参数 | 类型 | 说明 |
|---|---|---|
content | string | ContentBlock[] | 消息内容,文本或多模态内容块 |
options.tools | ToolDefinition[] | 本次调用额外追加的工具(与创建时的工具合并) |
返回值 ChatReply:
| 字段 | 类型 | 说明 |
|---|---|---|
content | string | ContentBlock[] | AI 回复内容 |
thinking | string | 模型思考过程(仅部分模型支持) |
toolCalls | ToolCall[] | 本次回复中的工具调用记录 |
usage | { inputTokens, outputTokens } | Token 用量 |
command | boolean | 是否为命令触发的回复 |
chatStream — 流式聊天
const stream = await conv.chatStream(content, options?);
for await (const chunk of stream) {
// 处理流式事件
}
实时接收 AI 回复,适用于需要逐步展示输出的场景。
StreamChunk 事件类型:
| type | 字段 | 说明 |
|---|---|---|
content_delta | content: string | 增量文本内容 |
thinking_delta | thinking: string | 增量思考内容 |
tool_call | toolCall: ToolCall | 工具调用信息(状态变化时触发) |
content_block | block: ContentBlock | 内容块(图片、文件等) |
done | usage: { inputTokens, outputTokens } | 对话完成 |
error | error: string, errorCode?: string | 错误 |
错误码(errorCode):
| 错误码 | 说明 |
|---|---|
rate_limit | API 频率限制,通常会自动重试 |
auth | 认证失败,检查 API Key |
tool_timeout | 工具执行超时 |
max_iterations | 达到最大工具调用循环次数 |
api_error | 其他 API 错误 |