连接 OpenAI SDK

连接 OpenAI SDK

将兼容 OpenAI 的客户端连接到 gateway:使用 endpoint mode 完整检查,或使用 proxy mode 转发。

兼容 OpenAI 的客户端可以通过两种方式连接 gateway:

  1. Endpoint mode(推荐):将客户端 base URL 指向 gateway 的 /v1。每个请求都经过完整检查。
  2. Proxy mode:将 gateway 配置为 HTTP forward proxy。

Endpoint mode#

任何兼容 OpenAI 的 SDK 都可使用,只需更改 base URL。

Python#

from openai import OpenAI
 
client = OpenAI(
    api_key="<provider-api-key>",  # 透传给 backend
    base_url="http://<gateway-host>:443/v1",  # AI-FW gateway
    default_headers={"X-Agent-ID": "my-agent-01"},
)
 
resp = client.chat.completions.create(
    model="gpt-4o",
    messages=[{"role": "user", "content": "Hello!"}],
)
print(resp.choices[0].message.content)

Node.js#

import OpenAI from "openai";
 
const client = new OpenAI({
  apiKey: "<provider-api-key>",
  baseURL: "http://<gateway-host>:443/v1",
  defaultHeaders: { "X-Agent-ID": "my-agent-01" },
});
 
const resp = await client.chat.completions.create({
  model: "gpt-4o",
  messages: [{ role: "user", content: "Hello!" }],
});
console.log(resp.choices[0].message.content);

curl#

curl http://<gateway-host>:443/v1/chat/completions   -H "Content-Type: application/json"   -H "X-Agent-ID: my-agent-01"   -d '{
    "model": "gpt-4o",
    "messages": [{"role": "user", "content": "Hello!"}]
  }'

请求标头

标头用途
Authorization: Bearer <key>根据模式进行客户端认证和/或提供 upstream key。
X-Agent-ID用于跟踪、路由和风险评估的 Agent 身份。
X-User-Id用户身份;优先使用 token 的 sub claim。
x-aifw-cache-refresh跳过缓存查询,但仍允许写入。

Proxy mode#

curl --proxy http://<gateway-host>:443 https://api.openai.com/v1/chat/completions   -H "Content-Type: application/json"   -d '{"model":"gpt-4o","messages":[{"role":"user","content":"hi"}]}'
Proxy mode行为检查
HTTP absolute-form规范化为 /v1/* 并运行完整 pipeline。完整
CONNECT tunnel (HTTPS)TCP 隧道连接至允许的 backend。仅元数据;TLS 端到端加密。

CONNECT allow-list 允许默认 backend host、已注册模型 backend,以及 Settings -> Forward Proxy -> Allowed Tunnel Hosts 中添加的 host。其他 host 返回 403。Forward proxy 可整体禁用。

HTTPS 隧道内容不会被检查

要检查内容请使用 endpoint mode。CONNECT tunnel 是端到端加密的,只记录元数据。

Streaming#

stream: true 与 OpenAI backend 相同。buffered 在交付前检查完整响应;stream 实时发送 token,违规时结束流。

故障排查

  • 401:检查认证模式和 API key。
  • model_not_registered:注册模型或关闭 Reject Unregistered Models。
  • model_disabled:在 Model Inventory 启用模型。
  • 没有内容检查:使用 endpoint mode,而非 CONNECT tunnel。

后续阅读

后续阅读