Chuyển đến nội dung

Hướng dẫn Thiết lập

Hướng dẫn này bao gồm mọi thứ bạn cần để đi từ số không đến một tích hợp Imbrace SDK hoạt động — cài đặt, thông tin xác thực, môi trường và ghi đè URL dịch vụ.


Yêu cầu Hệ thống

Yêu cầuPhiên bản tối thiểu
Node.js18.0.0+
npm8.0.0+
Python3.9+
pip23.0+

Cài đặt

Từ npm registry:

Terminal window
npm install @imbrace/sdk
# hoặc
yarn add @imbrace/sdk
# hoặc
pnpm add @imbrace/sdk

Monorepo / phát triển cục bộ:

Terminal window
# Bước 1 — cài đặt phụ thuộc và xây dựng
cd ts
npm install
npm run build
# Bước 2 (tùy chọn) — liên kết toàn cục để sử dụng trong dự án khác trên cùng máy
npm link

Sau đó trong dự án bên ngoài của bạn:

Terminal window
npm link @imbrace/sdk

Xác minh:

import { ImbraceClient } from "@imbrace/sdk";
console.log("SDK loaded:", typeof ImbraceClient); // 'function'

Môi trường

TênURL GatewaySử dụng khi
develophttps://app-gateway.dev.imbrace.coPhát triển nội bộ
sandboxhttps://app-gateway.sandbox.imbrace.coKiểm thử tích hợp
stablehttps://app-gatewayv2.imbrace.coSản xuất (mặc định)

Chuyển đổi môi trường qua tùy chọn constructor env, hoặc ghi đè URL trực tiếp bằng baseUrl:

const client = new ImbraceClient({ env: "sandbox" });

Cấu hình Thông tin Xác thực

Tạo tệp .env

SDK không tự động đọc biến môi trường — bạn truyền thông tin xác thực trực tiếp vào constructor. Tệp .env là một quy ước người dùng để lưu trữ bí mật; sử dụng dotenv hoặc trình tải env của framework để đọc chúng.

# Thông tin xác thực
IMBRACE_API_KEY=api_key_của_bạn
IMBRACE_ACCESS_TOKEN=jwt_token_của_bạn
# ID Tổ chức — được gửi với mọi yêu cầu
IMBRACE_ORGANIZATION_ID=org_id_của_bạn
# Tùy chọn: ghi đè URL gateway trực tiếp
IMBRACE_GATEWAY_URL=https://app-gatewayv2.imbrace.co

Lấy API Key

Xem Hướng dẫn lấy API Key để biết hướng dẫn đầy đủ.


Khởi tạo Client

import { ImbraceClient } from "@imbrace/sdk";
// Phía máy chủ — API Key
const client = new ImbraceClient({
apiKey: process.env.IMBRACE_API_KEY,
organizationId: process.env.IMBRACE_ORGANIZATION_ID,
env: "stable", // hoặc dùng env: "stable"
});
// Phía client — Access Token (ví dụ: từ lần đăng nhập trước, hoặc token bạn tự lưu)
const client = new ImbraceClient({
accessToken: process.env.IMBRACE_ACCESS_TOKEN,
env: "stable",
});
// Đăng nhập bằng mật khẩu (POST /v1/login/sign_in) — phổ biến nhất cho ứng dụng end-user.
// Trả về { token: "login_acc_...", organizations: [...] } trong một lần gọi; chọn một
// bằng selectOrganization() và SDK sẽ đổi sang acc_ token gắn với tổ chức đó.
const anon = new ImbraceClient({ env: "stable" });
const { organizations } = await anon.login("user@example.com", "password");
await anon.selectOrganization(organizations[0].id);
// Luồng đăng nhập OTP (thay thế — cho UX dùng email-OTP thay vì mật khẩu)
await anon.requestOtp("user@example.com");
await anon.loginWithOtp("user@example.com", "123456");
// Token được lưu tự động trên client

Cài đặt CLI

Terminal window
# Cài đặt toàn cục
npm install -g @imbrace/cli
# Đăng nhập để bắt đầu
imbrace login --api-key api_xxx...

Xem Cài đặt CLI để biết các phương pháp cài đặt thay thế và CLI Commands để biết tài liệu tham khảo lệnh đầy đủ.


Ví dụ Sử dụng Nhanh

import { ImbraceClient } from '@imbrace/sdk'
const client = new ImbraceClient({ apiKey: process.env.IMBRACE_API_KEY })
// Lấy người dùng hiện tại
const me = await client.platform.getMe()
// Liệt kê kênh
const channels = await client.channel.list()
// Gửi tin nhắn
await client.messages.send({ type: 'text', text: 'Xin chào!' })
// AI completion
const result = await client.ai.complete({
model: 'gpt-4o',
messages: [{ role: 'user', content: 'Tóm tắt điều này.' }],
})
// AI streaming
for await (const chunk of client.ai.stream({ model: 'gpt-4o', messages: [...] })) {
process.stdout.write(chunk.choices[0]?.delta?.content ?? '')
}
// AI Agent — streaming chat
const response = await client.aiAgent.streamChat({
id: 'chat_id',
assistant_id: 'asst_abc',
messages: [{ role: 'user', content: 'Xin chào' }],
})
const reader = response.body!.getReader()
const decoder = new TextDecoder()
while (true) {
const { done, value } = await reader.read()
if (done) break
console.log(decoder.decode(value))
}

Ghi đè URL Dịch vụ

Sử dụng khi một microservice chạy ở địa chỉ khác (ví dụ: dev cục bộ, staging chuyên dụng).

const client = new ImbraceClient({
env: "develop",
services: {
aiAgent: "http://localhost:4000/ai-agent",
dataBoard: "http://localhost:3001/data-board",
channelService: "http://localhost:3002/channel-service",
},
});

Tất cả các key dịch vụ hợp lệ:

Python keyTypeScript keyDịch vụ
gatewaygatewayApp Gateway
platformplatformPlatform service
channel_servicechannelServiceChannel service
data_boarddataBoardData Board
backendbackendLegacy monolith (/v1/backend) — auth signin, templates, a few legacy routes
ipsipsIPS service
aiaiAI service
marketplacesmarketplacesMarketplace service
file_servicefileServiceFile service
message_suggestionmessageSuggestionMessage Suggestion service
predictpredictPredict service
workflow_engineworkflowEngineWorkflows
ai_agentaiAgentAI Agent service

Khắc phục sự cố

Cannot find package '@imbrace/sdk'

Gói chưa được liên kết. Chạy lại từ ts:

Terminal window
npm link
cd /path/to/your-project && npm link @imbrace/sdk
ERR_MODULE_NOT_FOUND cho tệp trong dist/

Gói chưa được xây dựng:

Terminal window
cd ts && npm run build
ModuleNotFoundError: No module named 'imbrace'
Terminal window
cd py && pip install -e ".[dev]"
401 Unauthorized

API Key đã hết hạn hoặc không hợp lệ. Tạo key mới:

Terminal window
curl -X POST https://app-gatewayv2.imbrace.co/private/backend/v1/third_party_token \
-H "x-access-token: <token_hiện_có_của_bạn>" \
-H "Content-Type: application/json" \
-d '{"expirationDays": 30}'
UserWarning: ImbraceClient: no credentials provided

Không có api_key hoặc access_token nào được truyền. Nếu cố ý (ví dụ: luồng chỉ đăng nhập), bỏ qua cảnh báo này. Nếu không, hãy kiểm tra tệp .env của bạn.