OpenAI Chat Completions(HTTP)

OpenClaw 的 Gateway 可以提供一個小型的 OpenAI 相容 Chat Completions 端點。

這個端點預設是停用的,需要先在設定中啟用。

  • POST /v1/chat/completions
  • 與 Gateway 共用相同連接埠(WS + HTTP 多工):http://<gateway-host>:<port>/v1/chat/completions

底層實作上,請求會以標準的 Gateway 代理執行流程處理(和 openclaw agent 走相同的程式碼路徑),路由、權限、設定全部共用。

認證

使用 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)。
  • 如果設定了 gateway.auth.rateLimit 且認證失敗次數過多,端點會回傳 429 並帶有 Retry-After 標頭。

安全邊界(重要)

請將此端點視為 gateway 實例的完整操作者存取介面。

  • 這裡的 HTTP bearer 認證不是細粒度的個別使用者權限模型。
  • 這個端點的有效 Gateway token/password 應視同擁有者/操作者等級的憑證。
  • 請求會走與受信任操作者相同的控制層代理路徑。
  • 此端點沒有獨立的非擁有者/個別使用者工具邊界;只要通過 Gateway 認證,OpenClaw 就把該呼叫者當作此 gateway 的受信任操作者。
  • 如果目標代理的策略允許敏感工具,此端點就能使用它們。
  • 請只在 loopback/tailnet/私有入口使用此端點,不要直接暴露在公網上。

詳見 安全性遠端存取

選擇代理

不需要自訂標頭,直接在 OpenAI 的 model 欄位中編碼代理 ID:

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

或用標頭指定特定的 OpenClaw 代理:

  • 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,讓重複呼叫可以共用同一個代理 session。

串流(SSE)

設定 stream: true 接收 Server-Sent Events(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"}]
  }'