设置指南
本指南涵盖了你从零开始到完成 Imbrace SDK 集成所需的一切 — 安装、凭证、环境和服务 URL 覆盖。
系统要求
| 要求 | 最低版本 |
|---|---|
| Node.js | 18.0.0+ |
| npm | 8.0.0+ |
| Python | 3.9+ |
| pip | 23.0+ |
安装
从 npm 注册表:
npm install @imbrace/sdk# 或yarn add @imbrace/sdk# 或pnpm add @imbrace/sdkMonorepo / 本地开发:
# 步骤 1 — 安装依赖并构建cd tsnpm installnpm run build
# 步骤 2(可选)— 链接到全局,以在同一台机器上的另一个项目中使用npm link然后在你的外部项目中:
npm link @imbrace/sdk验证:
import { ImbraceClient } from "@imbrace/sdk";console.log("SDK loaded:", typeof ImbraceClient); // 'function'从 PyPI:
pip install imbrace# 或uv add imbraceMonorepo / 本地开发(editable 模式):
cd pypip install -e ".[dev]"[dev] 标志安装:pytest、pytest-asyncio、pytest-httpx、ruff、mypy。
验证:
from imbrace import ImbraceClientprint("SDK loaded:", ImbraceClient)配置凭证
创建 .env 文件
SDK 不会自动读取环境变量 — 你需要将凭证直接传递给构造函数。.env 文件是存储密钥的用户约定;使用 dotenv 或你的框架的环境变量加载器来读取它们。
# 凭证IMBRACE_API_KEY=your_api_key_hereIMBRACE_ACCESS_TOKEN=your_jwt_token_here
# 组织 ID — 随每个请求发送IMBRACE_ORGANIZATION_ID=your_org_id_here
# 可选:直接覆盖网关 URLIMBRACE_GATEWAY_URL=https://app-gatewayv2.imbrace.co获取 API Key
选项 1 — Imbrace 门户: 登录后转到 设置 → API 密钥。
选项 2 — 通过 API(需要现有的访问令牌):
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}'你需要的值是 response.apiKey.apiKey。
环境
| 名称 | 网关 URL | 使用场景 |
|---|---|---|
develop | https://app-gateway.dev.imbrace.co | 内部开发 |
sandbox | https://app-gateway.sandbox.imbrace.co | 集成测试 |
stable | https://app-gatewayv2.imbrace.co | 生产环境(默认) |
通过 env 构造函数选项切换环境,或直接用 baseUrl 覆盖 URL:
const client = new ImbraceClient({ env: "sandbox" });client = ImbraceClient(env="sandbox")初始化客户端
import { ImbraceClient } from "@imbrace/sdk";
// 服务端 — API Keyconst client = new ImbraceClient({ apiKey: process.env.IMBRACE_API_KEY, organizationId: process.env.IMBRACE_ORGANIZATION_ID, env: "stable", // 或使用 env: "stable"});
// 客户端 — Access Token(例如来自之前的登录,或你自己存储的 token)const client = new ImbraceClient({ accessToken: process.env.IMBRACE_ACCESS_TOKEN, env: "stable",});
// 密码登录(POST /v1/login/sign_in)— 终端用户应用最常用的方式。// 在一次调用中返回 { token: "login_acc_...", organizations: [...] };用// selectOrganization() 选择其中一个,SDK 会自动切换为该组织的 acc_ token。const anon = new ImbraceClient({ env: "stable" });const { organizations } = await anon.login("user@example.com", "password");await anon.selectOrganization(organizations[0].id);
// OTP 登录流程(替代方案 — 用 email-OTP 体验替代密码)await anon.requestOtp("user@example.com");await anon.loginWithOtp("user@example.com", "123456");// 令牌自动存储在客户端上import osfrom imbrace import ImbraceClient
# 服务端 — API Keyclient = ImbraceClient( api_key=os.environ["IMBRACE_API_KEY"], organization_id=os.environ.get("IMBRACE_ORGANIZATION_ID"), env="stable",)
# 客户端 — Access Tokenclient = ImbraceClient( access_token=os.environ["IMBRACE_ACCESS_TOKEN"], organization_id="org_xxx",)
# 密码登录(POST /platform/v1/login/authenticate)— 终端用户应用最常用的方式。# login() 返回用户所属的组织;选择其一后用 select_organization()# 将短期 login_acc_ token 换成绑定组织的 acc_ token。anon = ImbraceClient(env="stable")res = anon.login("user@example.com", "password")anon.select_organization(res["organizations"][0]["organization_id"])
# OTP 登录流程(替代方案 — 用 email-OTP 体验替代密码)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)CLI 安装
# 全局安装npm install -g @imbrace/cli
# 登录开始使用imbrace login --api-key api_xxx...其他安装方法请参见 CLI 安装,完整命令参考请参见 CLI 命令。
快速使用示例
import { ImbraceClient } from '@imbrace/sdk'
const client = new ImbraceClient({ apiKey: process.env.IMBRACE_API_KEY })
// 获取当前用户const me = await client.platform.getMe()
// 列出频道const channels = await client.channel.list()
// 发送消息await client.messages.send({ type: 'text', text: 'Hello!' })
// AI 补全const result = await client.ai.complete({ model: 'gpt-4o', messages: [{ role: 'user', content: 'Summarize this.' }],})
// AI 流式传输for await (const chunk of client.ai.stream({ model: 'gpt-4o', messages: [...] })) { process.stdout.write(chunk.choices[0]?.delta?.content ?? '')}
// AI 代理 — 流式聊天const response = await client.aiAgent.streamChat({ id: 'chat_id', assistant_id: 'asst_abc', messages: [{ role: 'user', content: 'Hello' }],})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: # 获取当前用户 me = client.platform.get_me()
# 列出频道和面板 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 补全 result = client.ai.complete(CompletionInput( model="gpt-4o", messages=[CompletionMessage(role="user", content="Hello")], ))
# AI 代理 — 流式聊天 response = client.ai_agent.stream_chat({ "id": "chat_id", "assistant_id": "asst_abc", "messages": [{"role": "user", "content": "Hello"}], }) for line in response.iter_lines(): print(line)覆盖服务 URL
当微服务运行在不同地址时使用(例如本地开发、专用预发布环境)。
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", },)所有有效的服务键:
| Python 键 | TypeScript 键 | 服务 |
|---|---|---|
gateway | gateway | App Gateway |
platform | platform | Platform service |
channel_service | channelService | Channel service |
data_board | dataBoard | Data Board |
backend | backend | 旧版单体(/v1/backend)— 用于身份验证 signin、模板和少数遗留路由 |
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 |
故障排除
Cannot find package '@imbrace/sdk'
包未链接。从 ts 重新运行:
npm linkcd /path/to/your-project && npm link @imbrace/sdkERR_MODULE_NOT_FOUND for files in dist/
包尚未构建:
cd ts && npm run buildModuleNotFoundError: No module named 'imbrace'
cd py && pip install -e ".[dev]"401 Unauthorized
API Key 过期或无效。生成一个新的:
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
未传入 api_key 或 access_token。如果是有意为之(例如仅登录流程),忽略此警告。否则请检查你的 .env 文件。