Chuyển đến nội dung

Hướng Dẫn Luồng Đầy Đủ

Hướng dẫn này đi qua bốn luồng chính của Imbrace SDK từ đầu đến cuối. Mỗi phần độc lập — có thể theo thứ tự hoặc nhảy thẳng đến phần cần dùng. Chuyển tab ngôn ngữ một lần và phần còn lại của trang sẽ ghi nhớ lựa chọn của bạn.


1. Tạo AI Assistant và Bắt Đầu Chat

  1. Khởi tạo client

    import { ImbraceClient } from "@imbrace/sdk"
    const client = new ImbraceClient({
    baseUrl: "https://app-gatewayv2.imbrace.co",
    accessToken: "acc_your_token",
    })

    Xem Xác Thực → nên chọn credential nào để biết thêm chi tiết.

  2. Tạo assistant

    workflow_name phải là duy nhất trong tổ chức.

    const assistant = await client.chatAi.createAssistant({
    name: "Support Bot",
    workflow_name: "support_bot_v1",
    description: "Xử lý các câu hỏi hỗ trợ khách hàng cấp 1",
    instructions: "Bạn là trợ lý hỗ trợ. Hãy trả lời ngắn gọn và thân thiện.",
    provider_id: "system", // dùng provider LLM mặc định của tổ chức
    model_id: "gpt-4o", // tên model mà system provider hỗ trợ
    })
    const assistantId = assistant.id // UUID — dùng cho tất cả các call tiếp theo
    console.log("Assistant created:", assistantId)

    provider_idmodel_id là bắt buộc. Truyền provider_id: "system" để dùng provider LLM mặc định của tổ chức, hoặc truyền UUID của provider tuỳ chỉnh. Với provider_id: "system", model_id nhận tên model (ví dụ "gpt-4o") hoặc giá trị "Default" để dùng model mặc định của hệ thống.

  3. Stream phản hồi chat từ assistant

    const response = await client.aiAgent.streamChat({
    assistant_id: assistantId,
    organization_id: "org_your_org_id",
    messages: [{ role: "user", content: "Làm sao để đặt lại mật khẩu?" }],
    // id là session UUID — truyền lại để giữ lịch sử hội thoại
    // Nếu bỏ qua, UUID mới sẽ tự tạo mỗi lần gọi
    })
    const reader = response.body!.getReader()
    const decoder = new TextDecoder()
    while (true) {
    const { done, value } = await reader.read()
    if (done) break
    const 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 {}
    }
    }
    }
    }
  4. Duy trì lịch sử hội thoại (session ID)

    Truyền cùng một id (phải là UUID) qua các lượt gọi để giữ ngữ cảnh:

    import { randomUUID } from "crypto"
    const sessionId = randomUUID()
    // Tin nhắn đầu tiên
    await client.aiAgent.streamChat({
    assistant_id: assistantId,
    organization_id: "org_your_org_id",
    id: sessionId,
    messages: [{ role: "user", content: "Chính sách hoàn tiền của bạn là gì?" }],
    })
    // Tin nhắn tiếp theo — cùng session, assistant nhớ ngữ cảnh
    await client.aiAgent.streamChat({
    assistant_id: assistantId,
    organization_id: "org_your_org_id",
    id: sessionId,
    messages: [{ role: "user", content: "Mất bao lâu để xử lý?" }],
    })

2. Tạo Workflow với Activepieces và Liên Kết với Assistant

  1. Liệt kê flows hiện có để lấy project ID

    const { data: flows } = await client.activepieces.listFlows({ limit: 5 })
    const projectId = flows[0]?.projectId
    console.log("Project ID:", projectId)
  2. Tạo flow mới

    const flow = await client.activepieces.createFlow({
    displayName: "Cập Nhật CRM Khi Có Lead Mới",
    projectId,
    })
    console.log("Flow created:", flow.id)
  3. Thêm Webhook trigger và publish flow

    Flow vừa tạo đang ở trạng thái DRAFT không có trigger — webhook URL chưa tồn tại nên gọi triggerFlow sẽ trả 404. Thêm piece Webhook làm trigger rồi publish:

    // Đặt piece Webhook làm trigger của 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: {},
    },
    },
    })
    // Publish — status chuyển DISABLED → ENABLED và webhook URL được kích hoạt
    await client.activepieces.applyFlowOperation(flow.id, {
    type: "LOCK_AND_PUBLISH",
    request: {},
    })
  4. Kích hoạt flow thủ công với payload

    // Bất đồng bộ (fire and forget)
    await client.activepieces.triggerFlow(flow.id, {
    contact_name: "Nguyễn Văn A",
    email: "nva@example.com",
    })
    // Sync trigger — để có dữ liệu trả về thay vì timeout, flow cần
    // thêm action "Return Response" qua applyFlowOperation ADD_ACTION
    const result = await client.activepieces.triggerFlowSync(flow.id, {
    contact_name: "Nguyễn Văn A",
    email: "nva@example.com",
    })
    console.log("Flow result:", result)
  5. Liên kết flow với assistant

    Mở assistant trong dashboard Imbrace, vào Tools → Workflows và gắn flow vào. Assistant sẽ có thể kích hoạt flow trong quá trình hội thoại khi phù hợp.

    Hoặc cập nhật assistant để tham chiếu workflow theo tên:

    await client.chatAi.updateAssistant(assistantId, {
    name: "Support Bot",
    workflow_name: "support_bot_v1",
    workflow_function_call: [{ flow_id: flow.id, description: "Cập nhật CRM khi có lead mới" }],
    })
  6. Xem lịch sử chạy

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

3. Quản Lý Knowledge Hub và Gắn Vào Assistant

Knowledge Hub chứa files và folders trong service data-board (client.boards). _id của folder là giá trị bạn truyền vào assistant làm nguồn tri thức.

  1. Tạo folder

    const folder = await client.boards.createFolder({
    name: "Tài Liệu Sản Phẩm",
    organization_id: "org_your_org_id",
    parent_folder_id: "root",
    source_type: "upload",
    })
    console.log("Folder ID:", folder._id)
  2. Upload file vào folder

    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)
  3. Gắn folder vào assistant

    Truyền _id của folder vào folder_ids — assistant sẽ truy xuất từ mọi file trong folder đó. Dùng board_ids để gắn thêm một CRM data-board (các item của board trở thành nguồn tri thức). Trường knowledge_hubs cũ đã ngừng hỗ trợ.

    await client.chatAi.updateAssistant(assistantId, {
    name: "Support Bot",
    workflow_name: "support_bot_v1",
    folder_ids: [folder._id],
    // board_ids: [boardId], // tuỳ chọn: gắn thêm một CRM data-board
    })
  4. Xem và quản lý folders/files

    // Tìm kiếm folders
    const folders = await client.boards.searchFolders({ q: "Sản Phẩm" })
    // Lấy nội dung folder
    const contents = await client.boards.getFolderContents(folder._id)
    console.log("Files:", contents.files?.length)
    // Đổi tên folder
    await client.boards.updateFolder(folder._id, { name: "Tài Liệu Sản Phẩm v2" })
    // Tìm kiếm files trong folder
    const files = await client.boards.searchFiles({ folderId: folder._id })
    // Xóa folder
    await client.boards.deleteFolders({ ids: [folder._id] })

4. Quản Lý Data Boards và Items (CRM Pipeline)

  1. Tạo board

    Board là một CRM pipeline — leads, deals, tasks, hoặc bất kỳ dữ liệu có cấu trúc nào.

    const board = await client.boards.create({
    name: "Sales Pipeline",
    description: "Theo dõi tất cả deals đang hoạt động",
    })
    console.log("Board ID:", board._id)
  2. Thêm custom field

    Các loại field: ShortText, LongText, Number, Dropdown, Date, Checkbox, v.v. createField trả về board đã cập nhật — field mới nằm trong board.fields.

    const updated = await client.boards.createField(board._id, {
    name: "Công Ty",
    type: "ShortText",
    })
    // Lấy identifier field (tự tạo kèm mỗi board)
    const identifierField = updated.fields.find(f => f.is_identifier)
  3. Tạo board items (records)

    Items dùng format { 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)
  4. Liệt kê và tìm kiếm items

    // Phân trang items
    const { data: items } = await client.boards.listItems(board._id, { limit: 20, skip: 0 })
    // Tìm kiếm full-text
    const { data: results } = await client.boards.search(board._id, {
    q: "Acme",
    limit: 10,
    })
  5. Cập nhật và xóa items

    updateItem dùng format mảng { 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)
  6. Xuất board ra CSV

    const csv = await client.boards.exportCsv(board._id)
    // csv là string — ghi ra file hoặc gửi dưới dạng download