OpenAI SDK 接入
任何 OpenAI 兼容 SDK 只需替换 base_url 与 api_key,model 改成 TokenHouse 的模型名(如 claude-sonnet-4-6、glm-5,完整列表见 /models)。OpenAI SDK 默认就用 Authorization: Bearer 发送密钥,与网关鉴权方式一致,无需额外设置。
gpt-* 模型当前不可调用,model 请指向 claude-* 或 glm-*。各模型价格见 /pricing。
Python
from openai import OpenAI
client = OpenAI(
base_url="https://api.tokenhouse.ai/v1",
api_key="<your-key>",
)
resp = client.chat.completions.create(
model="claude-sonnet-4-6",
messages=[{"role": "user", "content": "你好"}],
)
print(resp.choices[0].message.content)Node.js
import OpenAI from 'openai';
const client = new OpenAI({
baseURL: 'https://api.tokenhouse.ai/v1',
apiKey: '<your-key>',
});
const resp = await client.chat.completions.create({
model: 'claude-sonnet-4-6',
messages: [{ role: 'user', content: '你好' }],
});
console.log(resp.choices[0].message.content);流式输出
加 stream=True / stream: true 即可,SSE 增量帧按 OpenAI 标准格式返回。
Python:
stream = client.chat.completions.create(
model="claude-sonnet-4-6",
messages=[{"role": "user", "content": "写一首关于山的短诗"}],
stream=True,
)
for chunk in stream:
delta = chunk.choices[0].delta.content
if delta:
print(delta, end="", flush=True)Node.js:
const stream = await client.chat.completions.create({
model: 'claude-sonnet-4-6',
messages: [{ role: 'user', content: '写一首关于山的短诗' }],
stream: true,
});
for await (const chunk of stream) {
const delta = chunk.choices[0]?.delta?.content;
if (delta) process.stdout.write(delta);
}如果流式连接中断且网关已观测到至少一帧输出,会按已观测到的 token 数计费,并在用量记录中标记 estimated。
环境变量
OpenAI SDK 会自动读取 OPENAI_API_KEY 与 OPENAI_BASE_URL,配置好后代码里无需显式传参:
export OPENAI_API_KEY="<your-key>"
export OPENAI_BASE_URL="https://api.tokenhouse.ai/v1"from openai import OpenAI
client = OpenAI() # 自动读取上面两个环境变量import OpenAI from 'openai';
const client = new OpenAI(); // 自动读取上面两个环境变量列出模型
GET /v1/models 需鉴权,返回当前可调用的模型列表(OpenAI list 格式),SDK 直接调用即可:
for model in client.models.list():
print(model.id)模型能力与价格明细见 /models 与 /pricing。
错误处理
网关错误统一为如下形状,SDK 会将其抛为对应的异常(如 Python 的 openai.AuthenticationError):
{
"error": {
"type": "auth_error",
"code": "invalid_api_key",
"message": "..."
}
}| 状态码 | type | 常见 code | 含义 |
|---|---|---|---|
| 401 | auth_error | missing_or_malformed / invalid_api_key / key_revoked_or_disabled | 未携带 Bearer 头、密钥无效或已被撤销 |
| 400 | invalid_request_error | unknown_model | model 不在可调用列表中 |
| 402 | insufficient_funds_error | strict_reserve_failed / flex_threshold_breached | 余额不足,详见余额与计费 |
| 503 | upstream_unavailable | no_route / credential_error | 上游暂时不可用 |
上游供应商返回的错误以 upstream_error 类型透传。
失败请求(4xx / 5xx / 超时)一律不扣费。