完整流程指南
本指南从头到尾演示 Imbrace SDK 的四个主要流程。每个部分相互独立 — 可以按顺序阅读,也可以直接跳到需要的部分。切换一次语言 Tab,页面其余部分将记住你的选择。
1. 创建 AI 助手并开始聊天
-
初始化 client
import { ImbraceClient } from "@imbrace/sdk"const client = new ImbraceClient({baseUrl: "https://app-gatewayv2.imbrace.co",accessToken: "acc_your_token",})from imbrace import ImbraceClientclient = ImbraceClient(base_url="https://app-gatewayv2.imbrace.co",access_token="acc_your_token",)参见身份验证 → 选哪种凭证了解完整决策树。
-
创建助手
workflow_name在组织内必须唯一。const assistant = await client.chatAi.createAssistant({name: "Support Bot",workflow_name: "support_bot_v1",description: "处理一级客户支持问题",instructions: "您是支持助手。请简洁友好地回答。",provider_id: "system", // 使用组织默认的 LLM 提供商model_id: "gpt-4o", // system 提供商支持的模型名称})const assistantId = assistant.id // UUID — 用于所有后续调用console.log("Assistant created:", assistantId)assistant = client.chat_ai.create_assistant({"name": "Support Bot","workflow_name": "support_bot_v1","description": "处理一级客户支持问题","instructions": "您是支持助手。请简洁友好地回答。","provider_id": "system", # 使用组织默认的 LLM 提供商"model_id": "gpt-4o", # system 提供商支持的模型名称})assistant_id = assistant["id"]print("Assistant created:", assistant_id)provider_id与model_id为必填。传入provider_id: "system"使用组织默认的 LLM 提供商,或传入自定义提供商的 UUID。当provider_id: "system"时,model_id可填模型名称(例如"gpt-4o")或字符串"Default"以使用系统默认模型。 -
从助手流式获取聊天响应
const response = await client.aiAgent.streamChat({assistant_id: assistantId,organization_id: "org_your_org_id",messages: [{ role: "user", content: "如何重置密码?" }],// id 是会话 UUID — 重复传入以保留对话历史// 若省略,每次调用将自动生成新 UUID})const reader = response.body!.getReader()const decoder = new TextDecoder()while (true) {const { done, value } = await reader.read()if (done) breakconst text = decoder.decode(value)for (const line of text.split("\n")) {if (line.startsWith("data: ")) {const data = line.slice(6).trim()if (data && data !== "[DONE]") {try {const chunk = JSON.parse(data)process.stdout.write(chunk.delta ?? chunk.content ?? "")} catch {}}}}}response = client.ai_agent.stream_chat({"assistant_id": assistant_id,"organization_id": "org_your_org_id","messages": [{"role": "user", "content": "如何重置密码?"}],# id 是会话 UUID — 重复传入以保留对话历史# 若省略,每次调用将自动生成新 UUID})import jsonfor line in response.iter_lines():if isinstance(line, bytes):line = line.decode()if not line.startswith("data: "):continuedata = line[6:].strip()if data and data != "[DONE]":try:chunk = json.loads(data)print(chunk.get("delta") or chunk.get("content") or "", end="")except Exception:pass -
维护对话历史(session ID)
在多次调用中传入相同的
id(必须是 UUID)以保留上下文:import { randomUUID } from "crypto"const sessionId = randomUUID()// 第一条消息await client.aiAgent.streamChat({assistant_id: assistantId,organization_id: "org_your_org_id",id: sessionId,messages: [{ role: "user", content: "您的退款政策是什么?" }],})// 下一条消息 — 同一会话,助手记住上下文await client.aiAgent.streamChat({assistant_id: assistantId,organization_id: "org_your_org_id",id: sessionId,messages: [{ role: "user", content: "需要多长时间处理?" }],})import uuidsession_id = str(uuid.uuid4())# 第一条消息client.ai_agent.stream_chat({"assistant_id": assistant_id,"organization_id": "org_your_org_id","id": session_id,"messages": [{"role": "user", "content": "您的退款政策是什么?"}],})# 下一条消息 — 同一会话,助手记住上下文client.ai_agent.stream_chat({"assistant_id": assistant_id,"organization_id": "org_your_org_id","id": session_id,"messages": [{"role": "user", "content": "需要多长时间处理?"}],})
2. 使用 Activepieces 创建工作流并与助手关联
-
列出现有 flows 以获取 project ID
const { data: flows } = await client.activepieces.listFlows({ limit: 5 })const projectId = flows[0]?.projectIdconsole.log("Project ID:", projectId)res = client.activepieces.list_flows(limit=5)flows = res.get("data", [])project_id = flows[0]["projectId"] if flows else Noneprint("Project ID:", project_id) -
创建新 flow
const flow = await client.activepieces.createFlow({displayName: "新 Lead 时更新 CRM",projectId,})console.log("Flow created:", flow.id)flow = client.activepieces.create_flow(display_name="新 Lead 时更新 CRM",project_id=project_id,)print("Flow created:", flow["id"]) -
添加 Webhook 触发器并发布 flow
刚创建的 flow 处于 DRAFT 状态且没有触发器 — webhook URL 尚未存在,因此调用
triggerFlow会返回 404。添加 Webhook piece 作为触发器,然后发布:// 将 Webhook piece 设为 flow 的触发器await client.activepieces.applyFlowOperation(flow.id, {type: "UPDATE_TRIGGER",request: {name: "trigger",type: "PIECE_TRIGGER",valid: true,displayName: "Webhook",settings: {pieceName: "@activepieces/piece-webhook",pieceVersion: "0.1.24",triggerName: "catch_webhook",input: { authType: "none" },propertySettings: {},},},})// 发布 — 状态从 DISABLED → ENABLED,webhook URL 开始可用await client.activepieces.applyFlowOperation(flow.id, {type: "LOCK_AND_PUBLISH",request: {},})# 将 Webhook piece 设为 flow 的触发器client.activepieces.apply_flow_operation(flow["id"], {"type": "UPDATE_TRIGGER","request": {"name": "trigger","type": "PIECE_TRIGGER","valid": True,"displayName": "Webhook","settings": {"pieceName": "@activepieces/piece-webhook","pieceVersion": "0.1.24","triggerName": "catch_webhook","input": {"authType": "none"},"propertySettings": {},},},})# 发布 — DISABLED → ENABLED,webhook URL 开始可用client.activepieces.apply_flow_operation(flow["id"], {"type": "LOCK_AND_PUBLISH","request": {},}) -
手动触发 flow 并传入 payload
// 异步(fire and forget)await client.activepieces.triggerFlow(flow.id, {contact_name: "张三",email: "zhangsan@example.com",})// 同步触发 — 要实际拿到返回值而非超时,flow 需要通过// applyFlowOperation ADD_ACTION 添加 "Return Response" 动作const result = await client.activepieces.triggerFlowSync(flow.id, {contact_name: "张三",email: "zhangsan@example.com",})console.log("Flow result:", result)# 异步(fire and forget)client.activepieces.trigger_flow(flow["id"], {"contact_name": "张三","email": "zhangsan@example.com",})# 同步触发 — 要实际拿到返回值而非超时,flow 需要通过# apply_flow_operation ADD_ACTION 添加 "Return Response" 动作result = client.activepieces.trigger_flow_sync(flow["id"], {"contact_name": "张三","email": "zhangsan@example.com",})print("Flow result:", result) -
将 flow 与助手关联
在 Imbrace dashboard 中打开助手,进入 Tools → Workflows 并绑定 flow。助手在对话中将能够在适当时机触发 flow。
或更新助手以按名称引用工作流:
await client.chatAi.updateAssistant(assistantId, {name: "Support Bot",workflow_name: "support_bot_v1",workflow_function_call: [{ flow_id: flow.id, description: "新 lead 时更新 CRM" }],})client.chat_ai.update_assistant(assistant_id, {"name": "Support Bot","workflow_name": "support_bot_v1","workflow_function_call": [{"flow_id": flow["id"], "description": "新 lead 时更新 CRM"}],}) -
查看运行历史
const { data: runs } = await client.activepieces.listRuns({flowId: flow.id,limit: 10,})for (const run of runs) {console.log(run.id, run.status, run.startTime)}res = client.activepieces.list_runs(flow_id=flow["id"], limit=10)for run in res.get("data", []):print(run["id"], run.get("status"), run.get("startTime"))
3. 管理 Knowledge Hub 并绑定到助手
Knowledge Hub 在 data-board 服务(client.boards)中存储文件和文件夹。文件夹的 _id 是您传给助手作为知识来源的值。
-
创建文件夹
const folder = await client.boards.createFolder({name: "产品文档",organization_id: "org_your_org_id",parent_folder_id: "root",source_type: "upload",})console.log("Folder ID:", folder._id)folder = client.boards.create_folder({"name": "产品文档","organization_id": "org_your_org_id","parent_folder_id": "root","source_type": "upload",})print("Folder ID:", folder["_id"]) -
上传文件到文件夹
import { readFileSync } from "fs"const fileBuffer = readFileSync("./docs/faq.pdf")const formData = new FormData()formData.append("file", new Blob([fileBuffer], { type: "application/pdf" }), "faq.pdf")formData.append("folder_id", folder._id)formData.append("organization_id", "org_your_org_id")const uploaded = await client.boards.uploadFile(formData)console.log("File uploaded:", uploaded.file_id)from pathlib import Pathpath = Path("./docs/faq.pdf")files = {"file": (path.name, path.read_bytes(), "application/pdf"),"folder_id": (None, folder["_id"]),"organization_id": (None, "org_your_org_id"),}uploaded = client.boards.upload_file(files)print("File uploaded:", uploaded.get("file_id") or uploaded.get("_id")) -
将文件夹绑定到助手
将文件夹的
_id传入folder_ids— 助手将从该文件夹的所有文件中检索。使用board_ids可额外附加 CRM data-board。旧的knowledge_hubs字段已停用。await client.chatAi.updateAssistant(assistantId, {name: "Support Bot",workflow_name: "support_bot_v1",folder_ids: [folder._id],// board_ids: [boardId], // 可选:同时附加 CRM data-board})client.chat_ai.update_assistant(assistant_id, {"name": "Support Bot","workflow_name": "support_bot_v1","folder_ids": [folder["_id"]],# "board_ids": [board_id], # 可选:同时附加 CRM data-board}) -
查看和管理文件夹/文件
// 搜索文件夹const folders = await client.boards.searchFolders({ q: "产品" })// 获取文件夹内容const contents = await client.boards.getFolderContents(folder._id)console.log("Files:", contents.files?.length)// 重命名文件夹await client.boards.updateFolder(folder._id, { name: "产品文档 v2" })// 搜索文件夹中的文件const files = await client.boards.searchFiles({ folderId: folder._id })// 删除文件夹await client.boards.deleteFolders({ ids: [folder._id] })# 搜索文件夹folders = client.boards.search_folders(q="产品")# 获取文件夹内容contents = client.boards.get_folder_contents(folder["_id"])print("Files:", len(contents.get("files") or []))# 重命名文件夹client.boards.update_folder(folder["_id"], {"name": "产品文档 v2"})# 搜索文件夹中的文件files = client.boards.search_files(folder_id=folder["_id"])# 删除文件夹client.boards.delete_folders([folder["_id"]])
4. 管理数据看板和条目(CRM Pipelines)
-
创建看板
看板是 CRM pipeline — leads、deals、tasks 或任何结构化数据。
const board = await client.boards.create({name: "Sales Pipeline",description: "跟踪所有活跃交易",})console.log("Board ID:", board._id)board = client.boards.create(name="Sales Pipeline",description="跟踪所有活跃交易",)print("Board ID:", board["_id"]) -
添加自定义字段
字段类型:
ShortText、LongText、Number、Dropdown、Date、Checkbox等。createField返回已更新的看板 — 新字段位于board.fields中。const updated = await client.boards.createField(board._id, {name: "公司",type: "ShortText",})// 获取标识符字段(每个看板自动创建)const identifierField = updated.fields.find(f => f.is_identifier)updated = client.boards.create_field(board["_id"], {"name": "公司","type": "ShortText",})identifier_field = next(f for f in updated["fields"] if f.get("is_identifier")) -
创建看板条目(记录)
条目使用格式
{ fields: [{ board_field_id, value }] }:const item = await client.boards.createItem(board._id, {fields: [{ board_field_id: identifierField._id, value: "Acme Corp" },],})console.log("Item ID:", item._id)item = client.boards.create_item(board["_id"], {"fields": [{"board_field_id": identifier_field["_id"], "value": "Acme Corp"},],})print("Item ID:", item["_id"]) -
列出和搜索条目
// 分页条目const { data: items } = await client.boards.listItems(board._id, { limit: 20, skip: 0 })// 全文搜索const { data: results } = await client.boards.search(board._id, {q: "Acme",limit: 10,})# 分页条目items = client.boards.list_items(board["_id"], limit=20, skip=0)# 全文搜索results = client.boards.search(board["_id"], q="Acme", limit=10) -
更新和删除条目
updateItem使用数组格式{ data: [{ key: fieldId, value }] }:await client.boards.updateItem(board._id, item._id, {data: [{ key: identifierField._id, value: "Acme Corp — Closed Won" }],})await client.boards.deleteItem(board._id, item._id)client.boards.update_item(board["_id"], item["_id"], {"data": [{"key": identifier_field["_id"], "value": "Acme Corp — Closed Won"}],})client.boards.delete_item(board["_id"], item["_id"]) -
导出看板为 CSV
const csv = await client.boards.exportCsv(board._id)// csv 是字符串 — 写入文件或作为下载发送csv = client.boards.export_csv(board["_id"])# csv 是 str — 写入文件或作为下载发送