Skip to content

OpenAI Chat Completions(HTTP)

OpenClaw 的 Gateway 可以提供一个小型的、兼容 OpenAI 的 Chat Completions 端点。

该端点 默认关闭,需要先在配置中启用。

  • POST /v1/chat/completions
  • 与 Gateway 同端口(WS + HTTP 复用):http://<gateway-host>:<port>/v1/chat/completions

在实现上,请求会作为一次普通的 Gateway agent run 执行(与 openclaw agent 走同一条代码路径),因此路由/权限/config 都与当前 Gateway 一致。

认证

使用 Gateway 的 auth 配置。发送 bearer token:

  • Authorization: Bearer <token>

备注:

  • gateway.auth.mode="token" 时,使用 gateway.auth.token(或 OPENCLAW_GATEWAY_TOKEN)。
  • gateway.auth.mode="password" 时,使用 gateway.auth.password(或 OPENCLAW_GATEWAY_PASSWORD)。

选择 agent

不需要自定义 header:把 agent id 编码进 OpenAI 的 model 字段:

  • model: "openclaw:<agentId>"(例如:"openclaw:main""openclaw:beta"
  • model: "agent:<agentId>"(别名)

或者通过 header 指定 OpenClaw agent:

  • x-openclaw-agent-id: <agentId>(默认:main

高级用法:

  • x-openclaw-session-key: <sessionKey> 用于完全控制 session 路由。

启用端点

gateway.http.endpoints.chatCompletions.enabled 设置为 true

json5
{
  gateway: {
    http: {
      endpoints: {
        chatCompletions: { enabled: true },
      },
    },
  },
}

禁用端点

gateway.http.endpoints.chatCompletions.enabled 设置为 false

json5
{
  gateway: {
    http: {
      endpoints: {
        chatCompletions: { enabled: false },
      },
    },
  },
}

Session 行为

默认情况下,该端点对每个请求都是 无状态的(每次调用都会生成一个新的 session key)。

如果请求里包含 OpenAI 的 user 字符串,Gateway 会从中派生一个稳定的 session key,因此重复调用可以复用同一个 agent session。

Streaming(SSE)

设置 stream: true 即可接收 Server-Sent Events(SSE):

  • Content-Type: text/event-stream
  • 每条 event line 的格式为 data: <json>
  • data: [DONE] 结束

示例

非流式:

bash
curl -sS http://127.0.0.1:18789/v1/chat/completions \
  -H 'Authorization: Bearer YOUR_TOKEN' \
  -H 'Content-Type: application/json' \
  -H 'x-openclaw-agent-id: main' \
  -d '{
    "model": "openclaw",
    "messages": [{"role":"user","content":"hi"}]
  }'

流式:

bash
curl -N http://127.0.0.1:18789/v1/chat/completions \
  -H 'Authorization: Bearer YOUR_TOKEN' \
  -H 'Content-Type: application/json' \
  -H 'x-openclaw-agent-id: main' \
  -d '{
    "model": "openclaw",
    "stream": true,
    "messages": [{"role":"user","content":"hi"}]
  }'