跳到內容

AI Agent

此頁面涵蓋兩個相關的 AI 命名空間:

  • chatAi / chat_ai — 建立和管理 AI agent、文件/檔案處理,以及 Document AI。
  • aiAgent / ai_agent — 串流聊天(SSE)、嵌入管理、Parquet 資料、分散式追蹤,以及聊天客戶端子 API。

AI Agent 資源連接到一個專用服務,該服務執行在與主 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 Agents — chatAi / chat_ai

管理 AI agent(CRUD)、執行相容 OpenAI 的補全,以及處理文件/檔案處理。同一個命名空間也涵蓋知識中心資料夾和知識庫。

AI Agent CRUD

// 列出您帳戶中的所有 AI agent
const agents = await client.chatAi.listAiAgents();
// 每個 AI agent 都有一個 `id`(UUID)。
// 所有後續呼叫請使用 `id` 欄位。
// 列出子代理(可由 orchestrator 委派工作的 agent)
const subAgents = await client.chatAi.listAiAgentSubAgents();
// 取得單一 AI agent
const agent = await client.chatAi.getAiAgent("9f77692f-33d0-436a-8138-2efb268838e6");
// 建立 — provider_id 和 model_id 是必填的
const created = await client.chatAi.createAiAgent({
name: "Support Bot",
workflow_name: "support_bot_v1",
provider_id: "system",
model_id: "Default", // 跨組織通用;"gpt-4o" 只在該組織的 system 提供者公開該模型時才有效
streaming: true, // 必須開啟才能讓聊天 UI 收到 text-delta SSE 事件
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 和圖片中提取結構化資料。請參閱 Document AI 參考以了解完整的參數參考、PDF 表單填寫和非同步用法。

檔案提取(agent 檔案上傳)

上傳檔案並提取其原始內容。

// 上傳 agent 專用的檔案
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.foldersclient.boards(Python)管理。資料夾組織知識庫 — 知識庫是 AI agent 可以檢索的一組檔案。在建立 AI agent 時將資料夾 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 agent 的管理 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 agent 和工作流程 agent 可用的模型。

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 agent 輸出以確保安全、合規或品牌指南。

// 列出和取得
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 Agents(透過 client.ai

client.ai 命名空間上的其他 AI agent 讀取/更新端點。如需完整的建立/刪除 CRUD,請使用上方的 client.chatAi

// 從帳戶端點列出 agent
const accountAgents = await client.ai.listAiAgents();
// 列出 agent(agents 端點)
const agents = await client.ai.listAgents();
// 取得單一 agent
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 Agent 應用程式(透過 client.ai

AI Agent 應用程式將 AI agent 連結到工作流程或應用程式設定。

// 建立
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: "system",
});
// 更新和刪除
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 是否可達且回傳有效的工具結構定義。

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)

回傳原始回應。將主體作為 Server-Sent Events 串流消費。

const response = await client.aiAgent.streamChat({
id: "chat_id",
assistant_id: "asst_abc",
messages: [{ role: "user", content: "What can you do?" }],
});
const reader = response.body!.getReader();
const decoder = new TextDecoder();
while (true) {
const { done, value } = await reader.read();
if (done) break;
process.stdout.write(decoder.decode(value));
}

子代理 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 agent 的預建提示建議。

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" });

Data Board

針對結構化資料集的 AI 輔助欄位類型建議。

const result = await client.aiAgent.suggestFieldTypes({
fields: [
{ name: "created_at", samples: ["2024-01-01", "2024-02-15"] },
{ name: "amount", samples: [100, 200.5, 999] },
{ name: "is_active", samples: [true, false, true] },
],
});
// 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 Agent 服務發出的 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 singleton、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 Agent 服務狀態和版本的工具端點。

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 Agent 服務託管的管理文件。指南檔案以原始二進位串流回傳(通常為 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",
});