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 运行来执行(和 openclaw agent 用的是同一套代码),所以路由、权限、配置都和你的 Gateway 保持一致。
认证
使用 Gateway 的认证配置。发送一个 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
不需要自定义请求头:直接在 OpenAI 的 model 字段中编码 agent id:
model: "openclaw:<agentId>"(例如:"openclaw:main"、"openclaw:beta")model: "agent:<agentId>"(别名)
或者通过请求头指定特定的 OpenClaw Agent:
x-openclaw-agent-id: <agentId>(默认值:main)
高级用法:
x-openclaw-session-key: <sessionKey>可以完全控制 Session 路由。
启用接口
把 gateway.http.endpoints.chatCompletions.enabled 设置为 true:
{
gateway: {
http: {
endpoints: {
chatCompletions: { enabled: true },
},
},
},
}
关闭接口
把 gateway.http.endpoints.chatCompletions.enabled 设置为 false:
{
gateway: {
http: {
endpoints: {
chatCompletions: { enabled: false },
},
},
},
}
Session 行为
默认情况下,这个接口是每次请求无状态的(每次调用都会生成一个新的 session key)。
如果请求中包含 OpenAI 的 user 字符串,Gateway 会从中派生出一个稳定的 session key,这样重复调用就可以共享同一个 Agent Session。
Streaming (SSE)
设置 stream: true 来接收服务器发送事件(SSE):
Content-Type: text/event-stream- 每个事件行的格式是
data: <json> - 流结束时会发送
data: [DONE]
示例
非流式:
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"}]
}'
流式:
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"}]
}'