跳转到内容

AI 代理

本页涵盖两个相关的 AI 命名空间:

  • chatAi / chat_ai — 创建和管理 AI 代理、文档/文件处理以及 Document AI。
  • aiAgent / ai_agent — 流式聊天(SSE)、嵌入管理、Parquet 数据、分布式追踪以及聊天客户端子 API。

AI 代理资源连接到一个专用服务,该服务运行在与主 API 网关不同的基础 URL 上。

有关将这些结合在一起的端到端示例,请参见完整流程指南 §1。

import { ImbraceClient } from "@imbrace/sdk"
const client = new ImbraceClient({
accessToken: process.env.IMBRACE_ACCESS_TOKEN,
env: "stable",
})
import { ImbraceClient } from "@imbrace/sdk"
const client = new ImbraceClient({
apiKey: process.env.IMBRACE_API_KEY,
organizationId: process.env.IMBRACE_ORGANIZATION_ID,
env: "stable",
})

同步(ImbraceClient)和异步(AsyncImbraceClient)客户端都暴露相同的接口 — 异步方法使用 await,客户端在底层使用 AsyncAiAgentResource。


AI 代理 — chatAi / chat_ai

管理 AI 代理(增删改查)、运行兼容 OpenAI 的补全,以及处理文档/文件。同一命名空间还涵盖知识中心文件夹和知识库。

AI 代理增删改查

// 列出你账户中的所有 AI 代理
const agents = await client.chatAi.listAiAgents();
// 每个 AI 代理都有一个 `id`(UUID)。
// 所有后续调用都使用 `id` 字段。
// 列出子代理(可由编排器委派的代理)
const subAgents = await client.chatAi.listAiAgentSubAgents();
// 获取单个 AI 代理
const agent = await client.chatAi.getAiAgent("9f77692f-33d0-436a-8138-2efb268838e6");
// 创建。省略时 SDK 会自动填充 { provider_id: "default", model_id: "Default" };
// "Default" 会路由到该组织配置的默认模型,可跨组织通用。像 "gpt-4o" 这样的
// 具体名称只有在该组织的 system 提供商确实公开它时才有效 —
// `client.ai.listModels()` 可以查看有哪些可用模型。传入 `streaming: true`,
// 这样 /v2/chat 会发出 text-delta SSE 事件,供 `streamChatText`(见下文)解析;
// 否则服务器会以单个 text/plain 响应返回完整回复,SSE 解析器将得不到任何内容。
const created = await client.chatAi.createAiAgent({
name: "Support Bot",
workflow_name: "support_bot_v1",
provider_id: "default",
model_id: "Default",
streaming: true,
description: "Handles tier-1 support queries",
});
// 更新 — 所有字段都是可选的(Partial)
const updated = await client.chatAi.updateAiAgent(created.id, {
name: "Support Bot v2",
workflow_name: "support_bot_v1",
});
// 仅更新系统指令
await client.chatAi.updateAiAgentInstructions(
created.id,
"You are a helpful support agent.",
);
await client.chatAi.deleteAiAgent(created.id);

补全(通过 client.ai)

兼容 OpenAI 的聊天补全在 TypeScript 和 Python 的 client.ai 命名空间上都可用。详情请参见下面的兼容 OpenAI 的 AI 服务章节。

const response = await client.ai.complete({
model: "gpt-4o",
messages: [
{ role: "system", content: "You are a helpful CRM assistant." },
{ role: "user", content: "Summarize this customer note: ..." },
],
});
console.log(response.choices[0].message.content);

Document AI 模型

const models = await client.chatAi.listDocumentModels();

Document AI

使用视觉模型从 PDF 和图片中提取结构化数据。完整参数参考、PDF 表单填写和异步用法请参见Document AI 参考。

文件提取(代理文件上传)

上传文件并提取其原始内容。

// 上传代理特定文件
const formData = new FormData();
formData.append("file", fileBuffer, "report.pdf");
const uploaded = await client.chatAi.uploadAgentFile(formData);
// 从上传的文件中提取内容
const extracted = await client.chatAi.extractFile(formData);

Chat v1 会话

用于持久化对话历史的传统 REST 聊天端点。TypeScript 和 Python 的 client.ai_agent 上都可用。请参见下面的旧版 v1 聊天。

知识中心 — 文件夹与知识库

文件夹和知识库通过 client.boards(TypeScript)/ client.folders 和 client.boards(Python)管理。文件夹组织知识库 — 知识库是 AI 代理可以检索的一组文件。创建 AI 代理时将文件夹 ID 作为 folder_ids 传入 — 参见完整流程指南 §3。

import { type CreateFolderInput } from "@imbrace/sdk";
// 文件夹
const folders = await client.boards.searchFolders({ organizationId: "org_xxx" });
const folder = await client.boards.createFolder({ name: "Q1 Reports" });
await client.boards.updateFolder(folder._id, { name: "Q1 2025 Reports" });
await client.boards.deleteFolders({ ids: [folder._id] });
// 文件(知识库条目)
const uploaded = await client.boards.uploadFile(formData);
const files = await client.boards.searchFiles({ folderId: folder._id });
const file = await client.boards.getFile("file_id");
await client.boards.createFile({ name: "doc.txt", folder_id: folder._id });
await client.boards.deleteFiles({ ids: ["file_id"] });

兼容 OpenAI 的 AI 服务 — client.ai

OpenAI 风格的补全、流式传输和嵌入。还公开了 LLM 模型、提供商、安全护栏、RAG 文件和 AI 代理的管理 API。TypeScript 和 Python 都可用。

// 单次补全
const response = await client.ai.complete({
model: "gpt-4o",
messages: [
{ role: "system", content: "You are a helpful CRM assistant." },
{ role: "user", content: "Summarize this customer note: ..." },
],
temperature: 0.7,
});
console.log(response.choices[0].message.content);
// 流式传输
const stream = client.ai.stream({
model: "gpt-4o",
messages: [{ role: "user", content: "Draft a follow-up email for this lead." }],
});
for await (const chunk of stream) {
process.stdout.write(chunk.choices[0].delta.content ?? "");
}
// 嵌入
const result = await client.ai.embed({
model: "text-embedding-ada-002",
input: ["customer complained about billing", "billing issue escalated"],
});

LLM 模型

列出 AI 代理和工作流代理可用的模型。

const result = await client.ai.getLlmModels();
// result.data → [{name, is_toolCall_available, is_vision_available, is_support_thinking}]
for (const model of result.data) {
console.log(model.name, model.is_toolCall_available);
}

提供商

管理自定义 LLM 提供商。listProviders 包含一个合成的 "system" 条目(provider_id: "system"),代表来自 getLlmModels 的内置模型。

// 列出所有提供商(包括系统默认作为第一个条目)
const providers = await client.ai.listProviders();
// 仅自定义提供商
const custom = await client.ai.listProviders({ includeSystem: false });
// 添加自定义提供商
const provider = await client.ai.createProvider({
name: "My Azure OpenAI",
type: "azure",
api_key: "sk-...",
base_url: "https://my-instance.openai.azure.com/",
});
// 更新、刷新模型、删除
await client.ai.updateProvider(provider._id, { name: "Azure OpenAI (prod)" });
await client.ai.refreshProviderModels(provider._id);
await client.ai.deleteProvider(provider._id);

安全护栏

过滤 AI 代理的输出,以满足安全、策略合规或品牌规范要求。

// 列出和获取
const guardrails = await client.ai.listGuardrails();
const guardrail = await client.ai.getGuardrail("guardrail_id");
// 创建
const created = await client.ai.createGuardrail({
name: "Brand Safety",
model: "gpt-4o",
instructions: "Block responses that mention competitor names.",
unsafe_categories: ["violence", "hate_speech"],
competitor_keywords: ["CompetitorA", "CompetitorB"],
});
// 更新和删除
await client.ai.updateGuardrail(created._id, {
name: "Brand Safety v2",
model: "gpt-4o",
instructions: "Updated instructions.",
});
await client.ai.deleteGuardrail(created._id);

安全护栏提供商

管理用于执行安全护栏评估的 LLM 提供商。

// 列出和获取
const providers = await client.ai.listGuardrailProviders();
const provider = await client.ai.getGuardrailProvider("provider_id");
// 创建
const gp = await client.ai.createGuardrailProvider({
name: "OpenAI Moderation",
type: "openai",
config: { api_key: "sk-..." },
});
// 测试连通性并列出可用模型
const testResult = await client.ai.testGuardrailProvider(gp._id, { prompt: "test prompt" });
const models = await client.ai.getGuardrailProviderModels(gp._id);
// 更新和删除
await client.ai.updateGuardrailProvider(gp._id, { name: "OpenAI Moderation v2" });
await client.ai.deleteGuardrailProvider(gp._id);

RAG 文件

通过 AI 服务上传和管理用于检索增强生成的文件。

const files = await client.ai.listRagFiles();
const file = await client.ai.getRagFile("file_id");
// 上传
const formData = new FormData();
formData.append("file", fileBuffer, "knowledge.pdf");
const uploaded = await client.ai.uploadRagFile(formData);
await client.ai.deleteRagFile(uploaded._id);

AI 代理(通过 client.ai)

client.ai 命名空间上的额外 AI 代理读取/更新端点。完整的创建/删除增删改查请使用上面的 client.chatAi。

// 从账户端点列出代理
const accountAgents = await client.ai.listAiAgents();
// 列出代理(代理端点)
const agents = await client.ai.listAgents();
// 获取单个代理
const agent = await client.ai.getAiAgent("asst_abc");
// 创建前检查名称是否可用
const check = await client.ai.checkAiAgentName("Support Bot");
// check.available → true / false
// 仅修补 instructions 字段
await client.ai.patchInstructions("asst_abc", {
instructions: "You are a concise, helpful assistant.",
});

AI 代理应用(通过 client.ai)

AI 代理应用将 AI 代理链接到工作流或应用配置。

// 创建
const app = await client.ai.createAiAgentApp({
name: "Support App",
workflow_name: "support_workflow_v1",
assistant_id: "asst_abc",
model_id: "Default", // 跨组织通用;"gpt-4o" 只在该组织的 system 提供商公开它时才有效
provider_id: "default",
});
// 更新和删除
await client.ai.updateAiAgentApp(app._id, { name: "Support App v2" });
await client.ai.deleteAiAgentApp(app._id);
// 仅更新工作流定义
await client.ai.updateAiAgentWorkflow(app._id, {
workflow: { steps: [{ id: "step1", type: "llm" }] },
});

工具服务器

验证自定义工具服务器 URL 是否可达并返回有效的工具 schema。

const result = await client.ai.verifyToolServer({ url: "https://my-tools.example.com/mcp" });
if (result.success) {
console.log("Available tools:", result.tools);
}

Chat v2 — 流式传输(SSE)

streamChat / stream_chat 通过 POST /ai-agent/v2/chat 返回原始 Response。响应体的格式取决于代理的 streaming 标志:

代理 streamingContent-Type响应体
true(推荐)text/event-streamVercel-AI-SDK UI-Message-Stream:data: {"type":"text-delta","delta":"..."} 事件
false(新建代理的默认值)text/plain以单个字符串返回的完整回复 — 没有 SSE 帧

推荐:streamChatText / stream_chat_text

这些便捷辅助方法封装了 streamChat,解析 SSE 事件流,并逐个产出纯文本增量。它们假定代理在创建时设置了 streaming: true。

for await (const chunk of client.aiAgent.streamChatText({
id: "chat_id",
assistant_id: "asst_abc",
messages: [{ role: "user", content: "What can you do?" }],
})) {
process.stdout.write(chunk);
}

同时处理流式和非流式代理

当你无法控制代理的创建方式时,请根据 Content-Type 分支处理:

const body = {
id: "chat_id",
assistant_id: "asst_abc",
messages: [{ role: "user", content: "What can you do?" }],
};
const res = await client.aiAgent.streamChat(body);
if (!res.ok) throw new Error(`HTTP ${res.status}: ${await res.text()}`);
const contentType = res.headers.get("content-type") ?? "";
let reply = "";
if (contentType.includes("text/event-stream")) {
// 流式代理 — 通过 SDK 辅助方法重新解析
for await (const chunk of client.aiAgent.streamChatText(body)) {
reply += chunk;
process.stdout.write(chunk); // 边接收边渲染
}
} else {
// 非流式代理 — 响应体即完整回复
reply = await res.text();
process.stdout.write(reply);
}

取消流(TypeScript,1.7.0+)

将 AbortSignal 作为第二个参数传给 streamChat、streamChatText 或 streamSubAgentChat。中止会在任何时刻关闭连接,包括流传输过程中:不会再收到新的数据块,调用会抛出错误。不要把 signal 放在请求体中;它会被作为 JSON 发送,没有任何效果。

const controller = new AbortController();
stopButton.onclick = () => controller.abort();
try {
for await (const chunk of client.aiAgent.streamChatText(body, { signal: controller.signal })) {
process.stdout.write(chunk);
}
} catch (e) {
if (!controller.signal.aborted) throw e;
}

子代理 Chat v2

流式传输子代理的响应并获取其对话历史。

const res = await client.aiAgent.streamSubAgentChat({
assistant_id: "asst_sub",
session_id: "sess_xyz",
chat_id: "chat_id",
messages: [{ role: "user", content: "Explain the data." }],
});
const history = await client.aiAgent.getSubAgentHistory({
session_id: "sess_xyz",
chat_id: "chat_id",
});

提示建议

获取给定 AI 代理的预构建提示建议。

const suggestions = await client.aiAgent.getAgentPromptSuggestion("asst_abc");

嵌入与知识库

管理用于检索增强生成(RAG)的文件。首先通过 client.boards.uploadFile(TypeScript)/ client.boards.upload_file(Python)上传文件,然后触发嵌入处理。

// 触发上传文件的嵌入处理
await client.aiAgent.processEmbedding({ fileId: "file_abc" });
// 列出和检查嵌入文件
const files = await client.aiAgent.listEmbeddingFiles({ page: 1, limit: 20 });
const file = await client.aiAgent.getEmbeddingFile("file_abc");
const preview = await client.aiAgent.previewEmbeddingFile({ file_id: "file_abc" });
// 更新状态和删除
await client.aiAgent.updateEmbeddingFileStatus("file_abc", "active");
await client.aiAgent.deleteEmbeddingFile("file_abc");
// 为 RAG 分类对文件进行分类
const classification = await client.aiAgent.classifyFile({ file_id: "file_abc" });

数据面板

分析示例文档(PDF/图片),为 Document AI 代理建议合适的 JSON schema。

const result = await client.aiAgent.suggestFieldTypes({
fileUrls: [
"https://cdn.imbrace.co/docs/invoice-1.pdf",
"https://cdn.imbrace.co/docs/invoice-2.pdf",
],
});
// result.fields[i].suggestedType → "datetime" | "number" | "boolean" | ...

Parquet

生成和管理用于分析管道的 Parquet 列式数据文件。

// 从 JSON 数据生成 Parquet 文件
const result = await client.aiAgent.generateParquet({
data: [{ id: 1, name: "Alice" }, { id: 2, name: "Bob" }],
fileName: "users",
folderName: "exports",
});
const files = await client.aiAgent.listParquetFiles();
await client.aiAgent.deleteParquetFile("exports/users.parquet");

分布式追踪(Tempo)

查询 AI 代理服务发出的 Grafana Tempo 追踪信息,用于可观测性和调试。

// 列出最近的追踪
const traces = await client.aiAgent.getTraces({
service: "ai-agent",
limit: 50,
timeRange: 3600, // 秒
orgId: "org_abc",
details: true,
});
// 检查单个追踪
const trace = await client.aiAgent.getTrace("trace_id_hex");
// 枚举服务、标签和标签值
const services = await client.aiAgent.getTraceServices();
const tags = await client.aiAgent.getTraceTags();
const values = await client.aiAgent.getTraceTagValues("http.status_code");
// TraceQL 搜索
const results = await client.aiAgent.searchTraceQL(
`{ .service.name = "ai-agent" && .http.status = 500 }`
);

聊天客户端

聊天客户端子 API 为前端应用提供支持(例如嵌入式聊天小部件)。关于框架级接入(React 单例、Express 认证代理等),请参见集成。

认证

await client.aiAgent.verifyChatClientCredentials({ token: "tok_xxx" });
await client.aiAgent.registerChatClient({ name: "web-app", secret: "s3cr3t" });
const user = await client.aiAgent.getChatClientUser({ token: "tok_xxx" });

聊天

// 创建新的聊天会话
await client.aiAgent.createClientChat({
id: "chat_uuid",
assistantId: "asst_abc",
organizationId: "org_abc",
userId: "user_xxx",
selectedVisibilityType: "private",
message: {
id: "msg_uuid",
role: "user",
content: "Hello!",
createdAt: new Date().toISOString(),
parts: [{ type: "text", text: "Hello!" }],
},
});
// 列出、读取、更新、删除聊天
const chats = await client.aiAgent.listClientChats({
organization_id: "org_abc",
limit: 20,
});
const chat = await client.aiAgent.getClientChat("chat_id");
await client.aiAgent.updateClientChat("chat_id", { visibility: "private" });
await client.aiAgent.deleteClientChat("chat_id");
await client.aiAgent.deleteAllClientChats({ organization_id: "org_abc" });
// 自动生成聊天标题
await client.aiAgent.generateClientChatTitle("chat_id");
// 以 SSE 方式流式传输实时聊天状态 — 返回原始 Response
const statusStream = await client.aiAgent.streamClientChatStatus("chat_id");

消息

await client.aiAgent.persistClientMessage({ chatId: "chat_id", content: "Hello" });
const messages = await client.aiAgent.listClientMessages("chat_id");
await client.aiAgent.deleteTrailingMessages("message_id");

投票

const votes = await client.aiAgent.getVotes("chat_id");
await client.aiAgent.updateVote({ messageId: "msg_id", vote: "up" });

文档(AI 生成的制品)

await client.aiAgent.createDocument({ kind: "text", content: "Draft..." });
const doc = await client.aiAgent.getDocument("doc_id");
const latest = await client.aiAgent.getDocumentLatest("doc_id");
const pub = await client.aiAgent.getDocumentPublic("doc_id");
const byKind = await client.aiAgent.getDocumentLatestByKind({ kind: "text" });
const suggestion = await client.aiAgent.getDocumentSuggestions("doc_id");
await client.aiAgent.deleteDocument("doc_id");

服务信息

检查 AI 代理服务状态和版本的实用端点。

const config = await client.aiAgent.getConfig();
const health = await client.aiAgent.getHealth(); // 摘要
const details = await client.aiAgent.getHealth(true); // 详细
const version = await client.aiAgent.getVersion();

管理指南

访问 AI 代理服务托管的管理文档。指南文件以原始二进制流形式返回(通常为 PDF)。

const guides = await client.aiAgent.listAdminGuides();
// 下载特定指南 — 返回原始 Response(PDF 流)
const response = await client.aiAgent.getAdminGuide("onboarding.pdf");
const blob = await response.blob();

旧版 v1 聊天

传统的 REST 聊天端点在不使用流式传输的情况下持久化对话历史。新代码应使用上面的 Chat v2 流式传输;v1 保留用于与已有聊天的向后兼容。

// 列出组织的聊天
const chats = await client.aiAgent.listChats({
organization_id: "org_abc",
user_id: "user_123",
limit: 20,
});
// 获取单个聊天(传入 true 以包含消息)
const chat = await client.aiAgent.getChat("chat_id", true);
// 删除聊天
await client.aiAgent.deleteChat("chat_id", {
organization_id: "org_abc",
user_id: "user_123",
});