Skip to content

Commit eaad4ad

Browse files
authored
feat(gateway): add missing OpenAI-compatible endpoints (models and embeddings) (#53992)
* feat(gateway): add OpenAI-compatible models and embeddings * docs(gateway): clarify model list and agent routing * Update index.md * fix(gateway): harden embeddings HTTP provider selection * fix(gateway): validate compat model overrides * fix(gateway): harden embeddings and response continuity * fix(gateway): restore compat model id handling
1 parent 0709224 commit eaad4ad

14 files changed

Lines changed: 1011 additions & 27 deletions

‎CHANGELOG.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@ Docs: https://docs.openclaw.ai
1919
- CLI/containers: add `--container` and `OPENCLAW_CONTAINER` to run `openclaw` commands inside a running Docker or Podman OpenClaw container. (#52651) Thanks @sallyom.
2020
- Discord/auto threads: add optional `autoThreadName: "generated"` naming so new auto-created threads can be renamed asynchronously with concise LLM-generated titles while keeping the existing message-based naming as the default. (#43366) Thanks @davidguttman.
2121
- Slack/interactive replies: restore rich reply parity for direct deliveries, auto-render simple trailing `Options:` lines as buttons/selects, improve Slack interactive setup defaults, and isolate reply controls from plugin interactive handlers. (#53389) Thanks @vincentkoc.
22+
- Gateway/OpenAI compatibility: add `/v1/models` and `/v1/embeddings`, and forward explicit model overrides through `/v1/chat/completions` and `/v1/responses` for broader client and RAG compatibility. Thanks @vincentkoc.
2223

2324
### Fixes
2425

‎docs/gateway/index.md‎

Lines changed: 25 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -70,11 +70,35 @@ Default mode is `gateway.reload.mode="hybrid"`.
7070
- One always-on process for routing, control plane, and channel connections.
7171
- Single multiplexed port for:
7272
- WebSocket control/RPC
73-
- HTTP APIs (OpenAI-compatible, Responses, tools invoke)
73+
- HTTP APIs, OpenAI compatible (`/v1/models`, `/v1/embeddings`, `/v1/chat/completions`, `/v1/responses`, `/tools/invoke`)
7474
- Control UI and hooks
7575
- Default bind mode: `loopback`.
7676
- Auth is required by default (`gateway.auth.token` / `gateway.auth.password`, or `OPENCLAW_GATEWAY_TOKEN` / `OPENCLAW_GATEWAY_PASSWORD`).
7777

78+
## OpenAI-compatible endpoints
79+
80+
OpenClaw’s highest-leverage compatibility surface is now:
81+
82+
- `GET /v1/models`
83+
- `GET /v1/models/{id}`
84+
- `POST /v1/embeddings`
85+
- `POST /v1/chat/completions`
86+
- `POST /v1/responses`
87+
88+
Why this set matters:
89+
90+
- Most Open WebUI, LobeChat, and LibreChat integrations probe `/v1/models` first.
91+
- Many RAG and memory pipelines expect `/v1/embeddings`.
92+
- Agent-native clients increasingly prefer `/v1/responses`.
93+
94+
Planning note:
95+
96+
- Keep `/v1/models` as a flat `provider/model` list for client compatibility.
97+
- Treat agent and sub-agent selection as separate OpenClaw routing concerns, not pseudo-model entries.
98+
- When you need agent-scoped filtering, pass `x-openclaw-agent-id` on both model-list and request calls.
99+
100+
All of these run on the main Gateway port and use the same trusted operator auth boundary as the rest of the Gateway HTTP API.
101+
78102
### Port and bind precedence
79103

80104
| Setting | Resolution order |

‎docs/gateway/openai-http-api.md‎

Lines changed: 91 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,13 @@ This endpoint is **disabled by default**. Enable it in config first.
1414
- `POST /v1/chat/completions`
1515
- Same port as the Gateway (WS + HTTP multiplex): `http://<gateway-host>:<port>/v1/chat/completions`
1616

17+
When the Gateway’s OpenAI-compatible HTTP surface is enabled, it also serves:
18+
19+
- `GET /v1/models`
20+
- `GET /v1/models/{id}`
21+
- `POST /v1/embeddings`
22+
- `POST /v1/responses`
23+
1724
Under the hood, requests are executed as a normal Gateway agent run (same codepath as `openclaw agent`), so routing/permissions/config match your Gateway.
1825

1926
## Authentication
@@ -55,6 +62,12 @@ Or target a specific OpenClaw agent by header:
5562
Advanced:
5663

5764
- `x-openclaw-session-key: <sessionKey>` to fully control session routing.
65+
- `x-openclaw-message-channel: <channel>` to set the synthetic ingress channel context for channel-aware prompts and policies.
66+
67+
For `/v1/models` and `/v1/embeddings`, `x-openclaw-agent-id` is still useful:
68+
69+
- `/v1/models` uses it for agent-scoped model filtering where relevant.
70+
- `/v1/embeddings` uses it to resolve agent-specific memory-search embedding config.
5871

5972
## Enabling the endpoint
6073

@@ -94,6 +107,51 @@ By default the endpoint is **stateless per request** (a new session key is gener
94107

95108
If the request includes an OpenAI `user` string, the Gateway derives a stable session key from it, so repeated calls can share an agent session.
96109

110+
## Why this surface matters
111+
112+
This is the highest-leverage compatibility set for self-hosted frontends and tooling:
113+
114+
- Most Open WebUI, LobeChat, and LibreChat setups expect `/v1/models`.
115+
- Many RAG systems expect `/v1/embeddings`.
116+
- Existing OpenAI chat clients can usually start with `/v1/chat/completions`.
117+
- More agent-native clients increasingly prefer `/v1/responses`.
118+
119+
## Model list and agent routing
120+
121+
<AccordionGroup>
122+
<Accordion title="What does `/v1/models` return?">
123+
A flat OpenAI-style model list.
124+
125+
The returned ids are canonical `provider/model` values such as `openai/gpt-5.4`.
126+
These ids are meant to be passed back directly as the OpenAI `model` field.
127+
128+
</Accordion>
129+
<Accordion title="Does `/v1/models` list agents or sub-agents?">
130+
No.
131+
132+
`/v1/models` lists model choices, not execution topology. Agents and sub-agents are OpenClaw routing concerns, so they are selected separately with `x-openclaw-agent-id` or the `openclaw:<agentId>` / `agent:<agentId>` model aliases on chat and responses requests.
133+
134+
</Accordion>
135+
<Accordion title="How does agent-scoped filtering work?">
136+
Send `x-openclaw-agent-id: <agentId>` when you want the model list for a specific agent.
137+
138+
OpenClaw filters the model list against that agent's allowed models and fallbacks when configured. If no allowlist is configured, the endpoint returns the full catalog.
139+
140+
</Accordion>
141+
<Accordion title="How do sub-agents pick a model?">
142+
Sub-agent model choice is resolved at spawn time from OpenClaw agent config.
143+
144+
That means sub-agent model selection does not create extra `/v1/models` entries. Keep the compatibility list flat, and treat agent and sub-agent selection as separate OpenClaw-native routing behavior.
145+
146+
</Accordion>
147+
<Accordion title="What should clients do in practice?">
148+
Use `/v1/models` to populate the normal model picker.
149+
150+
If your client or integration also knows which OpenClaw agent it wants, set `x-openclaw-agent-id` when listing models and when sending chat, responses, or embeddings requests. That keeps the picker aligned with the target agent's allowed model set.
151+
152+
</Accordion>
153+
</AccordionGroup>
154+
97155
## Streaming (SSE)
98156

99157
Set `stream: true` to receive Server-Sent Events (SSE):
@@ -130,3 +188,36 @@ curl -N http://127.0.0.1:18789/v1/chat/completions \
130188
"messages": [{"role":"user","content":"hi"}]
131189
}'
132190
```
191+
192+
List models:
193+
194+
```bash
195+
curl -sS http://127.0.0.1:18789/v1/models \
196+
-H 'Authorization: Bearer YOUR_TOKEN'
197+
```
198+
199+
Fetch one model:
200+
201+
```bash
202+
curl -sS http://127.0.0.1:18789/v1/models/openai%2Fgpt-5.4 \
203+
-H 'Authorization: Bearer YOUR_TOKEN'
204+
```
205+
206+
Create embeddings:
207+
208+
```bash
209+
curl -sS http://127.0.0.1:18789/v1/embeddings \
210+
-H 'Authorization: Bearer YOUR_TOKEN' \
211+
-H 'Content-Type: application/json' \
212+
-H 'x-openclaw-agent-id: main' \
213+
-d '{
214+
"model": "openai/text-embedding-3-small",
215+
"input": ["alpha", "beta"]
216+
}'
217+
```
218+
219+
Notes:
220+
221+
- `/v1/models` returns canonical ids in `provider/model` form so they can be passed back directly as OpenAI `model` values.
222+
- `/v1/models` stays flat on purpose: it does not enumerate agents or sub-agents as pseudo-model ids.
223+
- `/v1/embeddings` supports `input` as a string or array of strings.

‎docs/gateway/openresponses-http-api.md‎

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -26,9 +26,19 @@ Operational behavior matches [OpenAI Chat Completions](/gateway/openai-http-api)
2626
- treat the endpoint as full operator access for the gateway instance
2727
- select agents with `model: "openclaw:<agentId>"`, `model: "agent:<agentId>"`, or `x-openclaw-agent-id`
2828
- use `x-openclaw-session-key` for explicit session routing
29+
- use `x-openclaw-message-channel` when you want a non-default synthetic ingress channel context
2930

3031
Enable or disable this endpoint with `gateway.http.endpoints.responses.enabled`.
3132

33+
The same compatibility surface also includes:
34+
35+
- `GET /v1/models`
36+
- `GET /v1/models/{id}`
37+
- `POST /v1/embeddings`
38+
- `POST /v1/chat/completions`
39+
40+
For the canonical explanation of how model listing, agent routing, and sub-agent model selection fit together, see [OpenAI Chat Completions](/gateway/openai-http-api#model-list-and-agent-routing).
41+
3242
## Session behavior
3343

3444
By default the endpoint is **stateless per request** (a new session key is generated each call).
@@ -54,9 +64,12 @@ Accepted but **currently ignored**:
5464
- `reasoning`
5565
- `metadata`
5666
- `store`
57-
- `previous_response_id`
5867
- `truncation`
5968

69+
Supported:
70+
71+
- `previous_response_id`: OpenClaw reuses the earlier response session when the request stays within the same agent/user/requested-session scope.
72+
6073
## Items (input)
6174

6275
### `message`
Lines changed: 176 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,176 @@
1+
import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";
2+
import { resolveAgentDir } from "../agents/agent-scope.js";
3+
import { getFreePort, installGatewayTestHooks } from "./test-helpers.js";
4+
5+
installGatewayTestHooks({ scope: "suite" });
6+
7+
let startGatewayServer: typeof import("./server.js").startGatewayServer;
8+
let createEmbeddingProviderMock: ReturnType<typeof vi.fn>;
9+
let enabledServer: Awaited<ReturnType<typeof startServer>>;
10+
let enabledPort: number;
11+
12+
beforeAll(async () => {
13+
vi.resetModules();
14+
createEmbeddingProviderMock = vi.fn(async (options: { provider: string; model: string }) => ({
15+
provider: {
16+
id: options.provider,
17+
model: options.model,
18+
embedQuery: async () => [0.1, 0.2],
19+
embedBatch: async (texts: string[]) =>
20+
texts.map((_text, index) => [index + 0.1, index + 0.2]),
21+
},
22+
}));
23+
vi.doMock("../memory/embeddings.js", async () => {
24+
const actual =
25+
await vi.importActual<typeof import("../memory/embeddings.js")>("../memory/embeddings.js");
26+
return {
27+
...actual,
28+
createEmbeddingProvider: createEmbeddingProviderMock,
29+
};
30+
});
31+
({ startGatewayServer } = await import("./server.js"));
32+
enabledPort = await getFreePort();
33+
enabledServer = await startServer(enabledPort, { openAiChatCompletionsEnabled: true });
34+
});
35+
36+
afterAll(async () => {
37+
await enabledServer.close({ reason: "embeddings http enabled suite done" });
38+
vi.resetModules();
39+
});
40+
41+
async function startServer(port: number, opts?: { openAiChatCompletionsEnabled?: boolean }) {
42+
return await startGatewayServer(port, {
43+
host: "127.0.0.1",
44+
auth: { mode: "token", token: "secret" },
45+
controlUiEnabled: false,
46+
openAiChatCompletionsEnabled: opts?.openAiChatCompletionsEnabled ?? false,
47+
});
48+
}
49+
50+
async function postEmbeddings(body: unknown, headers?: Record<string, string>) {
51+
return await fetch(`http://127.0.0.1:${enabledPort}/v1/embeddings`, {
52+
method: "POST",
53+
headers: {
54+
authorization: "Bearer secret",
55+
"content-type": "application/json",
56+
...headers,
57+
},
58+
body: JSON.stringify(body),
59+
});
60+
}
61+
62+
describe("OpenAI-compatible embeddings HTTP API (e2e)", () => {
63+
it("embeds string and array inputs", async () => {
64+
const single = await postEmbeddings({
65+
model: "text-embedding-3-small",
66+
input: "hello",
67+
});
68+
expect(single.status).toBe(200);
69+
const singleJson = (await single.json()) as {
70+
object?: string;
71+
data?: Array<{ object?: string; embedding?: number[]; index?: number }>;
72+
};
73+
expect(singleJson.object).toBe("list");
74+
expect(singleJson.data?.[0]?.object).toBe("embedding");
75+
expect(singleJson.data?.[0]?.embedding).toEqual([0.1, 0.2]);
76+
77+
const batch = await postEmbeddings({
78+
model: "text-embedding-3-small",
79+
input: ["a", "b"],
80+
});
81+
expect(batch.status).toBe(200);
82+
const batchJson = (await batch.json()) as {
83+
data?: Array<{ embedding?: number[]; index?: number }>;
84+
};
85+
expect(batchJson.data).toEqual([
86+
{ object: "embedding", index: 0, embedding: [0.1, 0.2] },
87+
{ object: "embedding", index: 1, embedding: [1.1, 1.2] },
88+
]);
89+
90+
const qualified = await postEmbeddings({
91+
model: "openai/text-embedding-3-small",
92+
input: "hello again",
93+
});
94+
expect(qualified.status).toBe(200);
95+
const qualifiedJson = (await qualified.json()) as { model?: string };
96+
expect(qualifiedJson.model).toBe("openai/text-embedding-3-small");
97+
const lastCall = createEmbeddingProviderMock.mock.calls.at(-1)?.[0] as
98+
| { provider?: string; model?: string }
99+
| undefined;
100+
expect(lastCall).toMatchObject({
101+
provider: "openai",
102+
model: "text-embedding-3-small",
103+
});
104+
});
105+
106+
it("supports base64 encoding and agent-scoped auth/config resolution", async () => {
107+
const res = await postEmbeddings(
108+
{
109+
model: "text-embedding-3-small",
110+
input: "hello",
111+
encoding_format: "base64",
112+
},
113+
{ "x-openclaw-agent-id": "beta" },
114+
);
115+
expect(res.status).toBe(200);
116+
const json = (await res.json()) as { data?: Array<{ embedding?: string }> };
117+
expect(typeof json.data?.[0]?.embedding).toBe("string");
118+
expect(createEmbeddingProviderMock).toHaveBeenCalled();
119+
const lastCall = createEmbeddingProviderMock.mock.calls.at(-1)?.[0] as
120+
| { provider?: string; model?: string; fallback?: string; agentDir?: string }
121+
| undefined;
122+
expect(lastCall?.model).toBe("text-embedding-3-small");
123+
expect(lastCall?.fallback).toBe("none");
124+
expect(lastCall?.agentDir).toBe(resolveAgentDir({}, "beta"));
125+
});
126+
127+
it("rejects invalid input shapes", async () => {
128+
const res = await postEmbeddings({
129+
model: "text-embedding-3-small",
130+
input: [{ nope: true }],
131+
});
132+
expect(res.status).toBe(400);
133+
const json = (await res.json()) as { error?: { type?: string } };
134+
expect(json.error?.type).toBe("invalid_request_error");
135+
});
136+
137+
it("rejects disallowed provider-prefixed model overrides", async () => {
138+
const res = await postEmbeddings({
139+
model: "ollama/nomic-embed-text",
140+
input: "hello",
141+
});
142+
expect(res.status).toBe(400);
143+
const json = (await res.json()) as { error?: { type?: string; message?: string } };
144+
expect(json.error).toEqual({
145+
type: "invalid_request_error",
146+
message: "This agent does not allow that embedding provider on `/v1/embeddings`.",
147+
});
148+
});
149+
150+
it("rejects oversized batches", async () => {
151+
const res = await postEmbeddings({
152+
model: "text-embedding-3-small",
153+
input: Array.from({ length: 129 }, () => "x"),
154+
});
155+
expect(res.status).toBe(400);
156+
const json = (await res.json()) as { error?: { type?: string; message?: string } };
157+
expect(json.error).toEqual({
158+
type: "invalid_request_error",
159+
message: "Too many inputs (max 128).",
160+
});
161+
});
162+
163+
it("sanitizes provider failures", async () => {
164+
createEmbeddingProviderMock.mockRejectedValueOnce(new Error("secret upstream failure"));
165+
const res = await postEmbeddings({
166+
model: "text-embedding-3-small",
167+
input: "hello",
168+
});
169+
expect(res.status).toBe(500);
170+
const json = (await res.json()) as { error?: { type?: string; message?: string } };
171+
expect(json.error).toEqual({
172+
type: "api_error",
173+
message: "internal error",
174+
});
175+
});
176+
});

0 commit comments

Comments
 (0)