完整流程指南
本指南從頭到尾逐步說明 Imbrace SDK 中的四大主要工作流程。每個章節都是獨立的 — 可以依序閱讀或直接跳到您需要的部分。
1. 建立 AI Agent 並開始聊天
-
初始化客戶端
import { ImbraceClient } from "@imbrace/sdk"const client = new ImbraceClient({accessToken: process.env.IMBRACE_ACCESS_TOKEN,env: "stable",})import osfrom imbrace import ImbraceClientclient = ImbraceClient(access_token=os.environ["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",})import osfrom imbrace import ImbraceClientclient = ImbraceClient(api_key=os.environ["IMBRACE_API_KEY"],organization_id=os.environ.get("IMBRACE_ORGANIZATION_ID"),env="stable",) -
建立 AI agent
workflow_name在您的組織內必須是唯一的。const agent = await client.chatAi.createAiAgent({name: "Support Bot",workflow_name: "support_bot_v1",description: "Handles tier-1 customer support queries",instructions: "You are a helpful support agent. Be concise and friendly.",provider_id: "system", // 使用組織的預設 LLM 提供者model_id: "Default", // 路由到組織配置的預設模型(跨組織通用)})const aiAgentId = agent.id // UUID — 所有後續呼叫使用此 IDconsole.log("AI agent created:", aiAgentId)agent = client.chat_ai.create_ai_agent({"name": "Support Bot","workflow_name": "support_bot_v1","description": "Handles tier-1 customer support queries","instructions": "You are a helpful support agent. Be concise and friendly.","provider_id": "system", # 使用組織的預設 LLM 提供者"model_id": "Default", # 路由到組織配置的預設模型(跨組織通用)})ai_agent_id = agent["id"]print("AI agent created:", ai_agent_id)provider_id和model_id是可選的 — SDK 在省略時會自動填入{ provider_id: "system", model_id: "Default" }。"Default"路由到組織配置的系統預設模型,是跨組織通用的選擇。顯式傳入即可覆寫:provider_id: "<uuid>"指定自訂 LLM 提供者,或model_id: "gpt-4o"等 — 但具體模型名稱只在該組織的system提供者實際公開該模型時才有效。在硬編碼前,使用client.ai.listModels()(TypeScript) /client.ai.list_models()(Python) 列出組織的可用模型。 -
使用 AI agent 串流聊天回應
const response = await client.aiAgent.streamChat({assistant_id: aiAgentId,messages: [{ role: "user", content: "How do I reset my password?" }],// 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": ai_agent_id,"messages": [{"role": "user", "content": "How do I reset my password?"}],# 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 -
維護對話歷史記錄(連線 ID)
在多次呼叫中傳遞相同的
id(必須是 UUID)以保持上下文:import { randomUUID } from "crypto"const sessionId = randomUUID()// 第一則訊息await client.aiAgent.streamChat({assistant_id: aiAgentId,id: sessionId,messages: [{ role: "user", content: "What's your refund policy?" }],})// 後續 — 相同連線,AI agent 記住上下文await client.aiAgent.streamChat({assistant_id: aiAgentId,id: sessionId,messages: [{ role: "user", content: "How long does it take?" }],})import uuidsession_id = str(uuid.uuid4())# 第一則訊息client.ai_agent.stream_chat({"assistant_id": ai_agent_id,"id": session_id,"messages": [{"role": "user", "content": "What's your refund policy?"}],})# 後續 — 相同連線,AI agent 記住上下文client.ai_agent.stream_chat({"assistant_id": ai_agent_id,"id": session_id,"messages": [{"role": "user", "content": "How long does it take?"}],})
2. 建立工作流程並繫結至 AI Agent
-
列出現有流程以尋找您的專案 ID
const { data: flows } = await client.workflows.listFlows({ limit: 5 })const projectId = flows[0]?.projectIdconsole.log("Project ID:", projectId)res = client.workflows.list_flows(limit=5)flows = res.get("data", [])project_id = flows[0]["projectId"] if flows else Noneprint("Project ID:", project_id) -
建立新流程
const flow = await client.workflows.createFlow({displayName: "CRM Update on New Lead",projectId,})console.log("Flow created:", flow.id)flow = client.workflows.create_flow(display_name="CRM Update on New Lead",project_id=project_id,)print("Flow created:", flow["id"]) -
新增 Webhook 觸發條件並發佈流程
新建立的流程處於草稿狀態且沒有觸發條件 — Webhook URL 還不存在,因此
triggerFlow會回傳 404。新增 Webhook 元件作為觸發條件,然後發佈:// 將 Webhook 元件設為流程的觸發條件await client.workflows.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.workflows.applyFlowOperation(flow.id, {type: "LOCK_AND_PUBLISH",request: {},})# 將 Webhook 元件設為流程的觸發條件client.workflows.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.workflows.apply_flow_operation(flow["id"], {"type": "LOCK_AND_PUBLISH","request": {},}) -
使用酬載手動觸發流程
// 觸發後即忘(非同步)await client.workflows.triggerFlow(flow.id, {contact_name: "Jane Smith",email: "jane@example.com",})// 同步觸發 — 要讓它實際回傳資料而不會逾時,// 流程需要透過 applyFlowOperation ADD_ACTION 新增「回傳回應」動作// (否則閘道會等待 30 秒回應然後放棄)。const result = await client.workflows.triggerFlowSync(flow.id, {contact_name: "Jane Smith",email: "jane@example.com",})console.log("Flow result:", result)# 觸發後即忘(非同步)client.workflows.trigger_flow(flow["id"], {"contact_name": "Jane Smith","email": "jane@example.com",})# 同步觸發 — 要讓它實際回傳資料而不會逾時,# 流程需要透過 apply_flow_operation ADD_ACTION 新增「回傳回應」動作# (否則閘道會等待 30 秒然後放棄)。result = client.workflows.trigger_flow_sync(flow["id"], {"contact_name": "Jane Smith","email": "jane@example.com",})print("Flow result:", result) -
將流程繫結至您的 AI agent
在 Imbrace 儀表板中開啟您的 AI agent,前往工具 → 工作流程,然後附加流程。AI agent 將能夠在對話中適當時觸發它。
或者,更新 AI agent 以依名稱參考工作流程:
await client.chatAi.updateAiAgent(aiAgentId, {name: "Support Bot",workflow_name: "support_bot_v1",workflow_function_call: [{ flow_id: flow.id, description: "Update CRM on new lead" }],})client.chat_ai.update_ai_agent(ai_agent_id, {"name": "Support Bot","workflow_name": "support_bot_v1","workflow_function_call": [{"flow_id": flow["id"], "description": "Update CRM on new lead"}],}) -
檢查執行歷史記錄
const { data: runs } = await client.workflows.listRuns({flowId: flow.id,limit: 10,})for (const run of runs) {console.log(run.id, run.status, run.startTime)}res = client.workflows.list_runs(flow_id=flow["id"], limit=10)for run in res.get("data", []):print(run["id"], run.get("status"), run.get("startTime"))
3. 管理知識中心並附加至 AI Agent
知識中心檔案和資料夾存在於 data-board 服務(client.boards)中。資料夾的 _id 就是您傳遞給 AI agent 作為其知識來源的內容。
-
建立資料夾
const folder = await client.boards.createFolder({name: "Product Documentation",organization_id: process.env.IMBRACE_ORGANIZATION_ID,parent_id: "root",})console.log("Folder ID:", folder._id)folder = client.boards.create_folder({"name": "Product Documentation","organization_id": os.environ.get("IMBRACE_ORGANIZATION_ID"),"parent_id": "root",})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", process.env.IMBRACE_ORGANIZATION_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, os.environ.get("IMBRACE_ORGANIZATION_ID")),}uploaded = client.boards.upload_file(files)print("File uploaded:", uploaded.get("file_id") or uploaded.get("_id")) -
將資料夾附加至 AI agent
在
folder_ids中傳遞資料夾_id— AI agent 從該資料夾中的每個檔案檢索。使用board_ids來附加 CRM data-board(其項目成為知識來源 — 請參閱資源 → Boards 與項目)。舊的knowledge_hubs欄位已棄用。await client.chatAi.updateAiAgent(aiAgentId, {name: "Support Bot",workflow_name: "support_bot_v1",folder_ids: [folder._id],// board_ids: [boardId], // 可選:也附加 CRM data-board})client.chat_ai.update_ai_agent(ai_agent_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: "Product" })// 取得資料夾內容const contents = await client.boards.getFolderContents(folder._id)console.log("Files:", contents.files?.length)// 重新命名資料夾await client.boards.updateFolder(folder._id, { name: "Product Docs v2" })// 搜尋資料夾中的檔案const files = await client.boards.searchFiles({ folderId: folder._id })// 刪除資料夾await client.boards.deleteFolders({ ids: [folder._id] })# 搜尋資料夾folders = client.boards.search_folders(q="Product")# 取得資料夾內容contents = client.boards.get_folder_contents(folder["_id"])print("Files:", len(contents.get("files") or []))# 重新命名資料夾client.boards.update_folder(folder["_id"], {"name": "Product Docs v2"})# 搜尋資料夾中的檔案files = client.boards.search_files(folder_id=folder["_id"])# 刪除資料夾client.boards.delete_folders([folder["_id"]])
4. 管理 Data Boards 與項目(CRM 管道)
-
建立 Board
Board 就是一個 CRM 管道 — 潛在客戶、交易、任務或任何結構化資料。
const board = await client.boards.create({name: "Sales Pipeline",description: "Track all active deals",})console.log("Board ID:", board._id)board = client.boards.create(name="Sales Pipeline",description="Track all active deals",)print("Board ID:", board["_id"]) -
新增自訂欄位
欄位類型有
ShortText、LongText、Number、Dropdown、Date、Checkbox等。createField回傳更新後的 board — 在board.fields中找到您的新欄位。const updated = await client.boards.createField(board._id, {name: "Company",type: "ShortText",})// 尋找識別欄位(每個 board 自動建立)const identifierField = updated.fields.find(f => f.is_identifier)updated = client.boards.create_field(board["_id"], {"name": "Company","type": "ShortText",})identifier_field = next(f for f in updated["fields"] if f.get("is_identifier")) -
建立 board 項目(記錄)
項目使用
{ 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) -
更新和刪除項目
更新使用
{ data: [{ key, value }] }(注意:是key,不是board_field_id):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 — 寫入檔案或作為下載傳送