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ầu | Phiên bản tối thiểu |
|---|---|
| Node.js | 18.0.0+ |
| npm | 8.0.0+ |
| Python | 3.9+ |
| pip | 23.0+ |
Cài đặt
Từ npm registry:
npm install @imbrace/sdk# hoặcyarn add @imbrace/sdk# hoặcpnpm add @imbrace/sdkMonorepo / phát triển cục bộ:
# Bước 1 — cài đặt phụ thuộc và xây dựngcd tsnpm installnpm 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áynpm linkSau đó trong dự án bên ngoài của bạn:
npm link @imbrace/sdkXác minh:
import { ImbraceClient } from "@imbrace/sdk";console.log("SDK loaded:", typeof ImbraceClient); // 'function'Từ PyPI:
pip install imbrace# hoặcuv add imbraceMonorepo / phát triển cục bộ (chế độ editable):
cd pypip install -e ".[dev]"Cờ [dev] cài đặt: pytest, pytest-asyncio, pytest-httpx, ruff, mypy.
Xác minh:
from imbrace import ImbraceClientprint("SDK loaded:", ImbraceClient)Môi trường
| Tên | URL Gateway | Sử dụng khi |
|---|---|---|
develop | https://app-gateway.dev.imbrace.co | Phát triển nội bộ |
sandbox | https://app-gateway.sandbox.imbrace.co | Kiểm thử tích hợp |
stable | https://app-gatewayv2.imbrace.co | Sả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" });client = 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ựcIMBRACE_API_KEY=api_key_của_bạnIMBRACE_ACCESS_TOKEN=jwt_token_của_bạn
# ID Tổ chức — được gửi với mọi yêu cầuIMBRACE_ORGANIZATION_ID=org_id_của_bạn
# Tùy chọn: ghi đè URL gateway trực tiếpIMBRACE_GATEWAY_URL=https://app-gatewayv2.imbrace.coLấ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 Keyconst 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 clientimport osfrom imbrace import ImbraceClient
# Phía máy chủ — API Keyclient = ImbraceClient( api_key=os.environ["IMBRACE_API_KEY"], organization_id=os.environ.get("IMBRACE_ORGANIZATION_ID"), env="stable",)
# Phía client — Access Tokenclient = ImbraceClient( access_token=os.environ["IMBRACE_ACCESS_TOKEN"], organization_id="org_xxx",)
# Đăng nhập bằng mật khẩu (POST /platform/v1/login/authenticate) — phổ biến nhất cho ứng dụng end-user.# login() trả về danh sách tổ chức; chọn 1 rồi select_organization() đổi token# login_acc_ ngắn hạn lấy token acc_ gắn theo tổ chức.anon = ImbraceClient(env="stable")res = anon.login("user@example.com", "password")anon.select_organization(res["organizations"][0]["organization_id"])
# Luồng đăng nhập OTP (thay thế — cho UX dùng email-OTP thay vì mật khẩu)anon.request_otp("user@example.com")anon.login_with_otp("user@example.com", "123456")from imbrace import AsyncImbraceClient
async def main(): async with AsyncImbraceClient(api_key=os.environ["IMBRACE_API_KEY"]) as client: me = await client.platform.get_me() print(me)Cài đặt CLI
# Cài đặt toàn cụcnpm install -g @imbrace/cli
# Đăng nhập để bắt đầuimbrace 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ạiconst me = await client.platform.getMe()
// Liệt kê kênhconst channels = await client.channel.list()
// Gửi tin nhắnawait client.messages.send({ type: 'text', text: 'Xin chào!' })
// AI completionconst result = await client.ai.complete({ model: 'gpt-4o', messages: [{ role: 'user', content: 'Tóm tắt điều này.' }],})
// AI streamingfor await (const chunk of client.ai.stream({ model: 'gpt-4o', messages: [...] })) { process.stdout.write(chunk.choices[0]?.delta?.content ?? '')}
// AI Agent — streaming chatconst 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))}from imbrace import ImbraceClientfrom imbrace.types.ai import CompletionInput, CompletionMessage
with ImbraceClient(api_key=os.environ["IMBRACE_API_KEY"]) as client: # Lấy người dùng hiện tại me = client.platform.get_me()
# Liệt kê kênh và board channels = client.channel.list() boards_res = client.boards.list() boards_data = boards_res.get("data", []) if boards_data: board_id = boards_data[0].get("_id") or boards_data[0]["id"] items = client.boards.list_items(board_id)
# AI completion result = client.ai.complete(CompletionInput( model="gpt-4o", messages=[CompletionMessage(role="user", content="Xin chào")], ))
# AI Agent — streaming chat response = client.ai_agent.stream_chat({ "id": "chat_id", "assistant_id": "asst_abc", "messages": [{"role": "user", "content": "Xin chào"}], }) for line in response.iter_lines(): print(line)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", },});client = ImbraceClient( env="develop", services={ "ai_agent": "http://localhost:4000/ai-agent", "data_board": "http://localhost:3001/data-board", "channel_service":"http://localhost:3002/channel-service", },)Tất cả các key dịch vụ hợp lệ:
| Python key | TypeScript key | Dịch vụ |
|---|---|---|
gateway | gateway | App Gateway |
platform | platform | Platform service |
channel_service | channelService | Channel service |
data_board | dataBoard | Data Board |
backend | backend | Legacy monolith (/v1/backend) — auth signin, templates, a few legacy routes |
ips | ips | IPS service |
ai | ai | AI service |
marketplaces | marketplaces | Marketplace service |
file_service | fileService | File service |
message_suggestion | messageSuggestion | Message Suggestion service |
predict | predict | Predict service |
workflow_engine | workflowEngine | Workflows |
ai_agent | aiAgent | AI 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:
npm linkcd /path/to/your-project && npm link @imbrace/sdkERR_MODULE_NOT_FOUND cho tệp trong dist/
Gói chưa được xây dựng:
cd ts && npm run buildModuleNotFoundError: No module named 'imbrace'
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:
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.