Hướng Dẫn Cài Đặt
Hướng dẫn này bao gồm mọi thứ cần thiết để bắt đầu tích hợp Imbrace SDK — từ cài đặt, cấu hình thông tin xác thực, môi trường cho đến override 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 nội bộ:
# Bước 1 — cài dependencies và buildcd tsnpm installnpm run build
# Bước 2 (tuỳ chọn) — link global để dùng trong project khácnpm linkSau đó trong project bên ngoài:
npm link @imbrace/sdkKiểm tra:
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 nội bộ (editable mode):
cd pypip install -e ".[dev]"Cờ [dev] cài thêm: pytest, pytest-asyncio, pytest-httpx, ruff, mypy.
Kiểm tra:
from imbrace import ImbraceClientprint("SDK loaded:", ImbraceClient)Cấu Hình Thông Tin Xác Thực
Tạo file .env
SDK không tự đọc biến môi trường — bạn truyền credentials trực tiếp vào constructor. File .env là quy ước của người dùng; dùng dotenv hoặc env loader của framework để đọc.
# CredentialsIMBRACE_API_KEY=your_api_key_hereIMBRACE_ACCESS_TOKEN=your_jwt_token_here
# ID tổ chức — gửi kèm mọi requestIMBRACE_ORGANIZATION_ID=your_org_id_here
# Tuỳ chọn: override URL gateway trực tiếpIMBRACE_BASE_URL=https://app-gatewayv2.imbrace.coLấy API Key
Cách 1 — Imbrace Portal: đăng nhập và vào Settings → API Keys.
Cách 2 — qua API (cần có access token hiện tại):
curl -X POST https://app-gatewayv2.imbrace.co/private/backend/v1/third_party_token \ -H "x-access-token: <your_existing_token>" \ -H "Content-Type: application/json" \ -d '{"expirationDays": 30}'Giá trị cần dùng là response.apiKey.apiKey.
Môi Trường
| Tên | Gateway URL | 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 | Production (mặc định) |
Chuyển môi trường qua option env trong constructor, hoặc override URL trực tiếp bằng baseUrl:
const client = new ImbraceClient({ env: 'sandbox' })client = ImbraceClient(env="sandbox")Khởi Tạo Client
import { ImbraceClient } from '@imbrace/sdk'
// Server-side — API Keyconst client = new ImbraceClient({ apiKey: process.env.IMBRACE_API_KEY, organizationId: process.env.IMBRACE_ORGANIZATION_ID, baseUrl: 'https://app-gatewayv2.imbrace.co', // hoặc dùng env: 'stable'})
// Client-side — Access Token (ví dụ sau khi đăng nhập OTP)const client = new ImbraceClient({ accessToken: process.env.IMBRACE_ACCESS_TOKEN, baseUrl: 'https://app-gatewayv2.imbrace.co',})
// Luồng đăng nhập OTPconst anon = new ImbraceClient({ baseUrl: 'https://app-gatewayv2.imbrace.co' })await anon.requestOtp('user@example.com')await anon.loginWithOtp('user@example.com', '123456')// Token được lưu tự động vào clientimport osfrom imbrace import ImbraceClient
# Server-side — API Keyclient = ImbraceClient( api_key=os.environ["IMBRACE_API_KEY"], organization_id=os.environ.get("IMBRACE_ORGANIZATION_ID"), env="stable",)
# Client-side — Access Tokenclient = ImbraceClient( access_token="eyJhbGci...", organization_id="org_xxx",)
# Luồng đăng nhập OTPanon = ImbraceClient(env="stable")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="sk-...") as client: me = await client.platform.get_me() print(me)Ví Dụ Sử Dụng Nhanh
import { ImbraceClient } from '@imbrace/sdk'
const client = new ImbraceClient({ apiKey: process.env.IMBRACE_API_KEY })
// Lấy thông tin user hiện tạiconst me = await client.platform.getMe()
// Danh sách channelconst channels = await client.channel.listChannels()
// Gửi tin nhắnawait client.channel.sendMessage('conv_123', { content: 'Xin chào!', type: 'text' })
// AI completionconst result = await client.ai.complete({ model: 'gpt-4o', messages: [{ role: 'user', content: 'Tóm tắt báo cáo.' }],})
// 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', organization_id: 'org_abc', messages: [{ role: 'user', content: 'Xin chào' }],})from imbrace import ImbraceClient
with ImbraceClient(api_key="sk-...") as client: # Lấy thông tin user me = client.platform.get_me()
# Danh sách channel và boards channels = client.channel.list_channels() boards = client.boards.list() items = client.boards.get_items(boards[0]["id"])
# AI completion result = client.ai.complete( model="gpt-4o", messages=[{"role": "user", "content": "Xin chào"}], )
# AI Agent — streaming chat response = client.ai_agent.stream_chat({ "id": "chat_id", "assistant_id": "asst_abc", "organization_id": "org_abc", "messages": [{"role": "user", "content": "Xin chào"}], }) for line in response.iter_lines(): print(line)Override URL Dịch Vụ
Dùng khi một microservice chạy ở địa chỉ khác (ví dụ: local dev, staging riê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ả service keys 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 | Board/Items backend (/v1/backend) |
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 |
activepieces | activepieces | ActivePieces |
ai_agent | aiAgent | AI Agent service |
Xử Lý Lỗi Thường Gặp
Cannot find package '@imbrace/sdk'
Package chưa được link. Chạy lại từ ts:
npm linkcd /path/to/your-project && npm link @imbrace/sdkERR_MODULE_NOT_FOUND cho file trong dist/
Package chưa được build:
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 sai. Tạo API Key mới:
curl -X POST https://app-gatewayv2.imbrace.co/private/backend/v1/third_party_token \ -H "x-access-token: <your_existing_token>" \ -H "Content-Type: application/json" \ -d '{"expirationDays": 30}'UserWarning: ImbraceClient: no credentials provided
Không truyền api_key hoặc access_token. Nếu cố ý (ví dụ: chỉ dùng để đăng nhập), có thể bỏ qua warning này. Nếu không, hãy kiểm tra lại file .env.