Skip to content

Commit d106696

Browse files
committed
feat(gateway): make openai compatibility agent-first
1 parent e1d16ba commit d106696

13 files changed

Lines changed: 234 additions & 133 deletions

‎docs/gateway/index.md‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -93,9 +93,9 @@ Why this set matters:
9393

9494
Planning note:
9595

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.
96+
- `/v1/models` is agent-first: it returns `openclaw`, `openclaw/default`, and `openclaw/<agentId>`.
97+
- `openclaw/default` is the stable alias that always maps to the configured default agent.
98+
- Use `x-openclaw-model` when you want a backend provider/model override; otherwise the selected agent's normal model and embedding setup stays in control.
9999

100100
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.
101101

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

Lines changed: 42 additions & 37 deletions
Original file line numberDiff line numberDiff line change
@@ -48,26 +48,25 @@ Treat this endpoint as a **full operator-access** surface for the gateway instan
4848

4949
See [Security](/gateway/security) and [Remote access](/gateway/remote).
5050

51-
## Choosing an agent
51+
## Agent-first model contract
5252

53-
No custom headers required: encode the agent id in the OpenAI `model` field:
53+
OpenClaw treats the OpenAI `model` field as an **agent target**, not a raw provider model id.
5454

55-
- `model: "openclaw:<agentId>"` (example: `"openclaw:main"`, `"openclaw:beta"`)
56-
- `model: "agent:<agentId>"` (alias)
55+
- `model: "openclaw"` routes to the configured default agent.
56+
- `model: "openclaw/default"` also routes to the configured default agent.
57+
- `model: "openclaw/<agentId>"` routes to a specific agent.
5758

58-
Or target a specific OpenClaw agent by header:
59+
Optional request headers:
5960

60-
- `x-openclaw-agent-id: <agentId>` (default: `main`)
61+
- `x-openclaw-model: <provider/model-or-bare-id>` overrides the backend model for the selected agent.
62+
- `x-openclaw-agent-id: <agentId>` remains supported as a compatibility override.
63+
- `x-openclaw-session-key: <sessionKey>` fully controls session routing.
64+
- `x-openclaw-message-channel: <channel>` sets the synthetic ingress channel context for channel-aware prompts and policies.
6165

62-
Advanced:
66+
Compatibility aliases still accepted:
6367

64-
- `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.
68+
- `model: "openclaw:<agentId>"`
69+
- `model: "agent:<agentId>"`
7170

7271
## Enabling the endpoint
7372

@@ -120,34 +119,40 @@ This is the highest-leverage compatibility set for self-hosted frontends and too
120119

121120
<AccordionGroup>
122121
<Accordion title="What does `/v1/models` return?">
123-
A flat OpenAI-style model list.
122+
An OpenClaw agent-target list.
124123

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.
124+
The returned ids are `openclaw`, `openclaw/default`, and `openclaw/<agentId>` entries.
125+
Use them directly as OpenAI `model` values.
127126

128127
</Accordion>
129128
<Accordion title="Does `/v1/models` list agents or sub-agents?">
130-
No.
129+
It lists top-level agent targets, not backend provider models and not sub-agents.
131130

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.
131+
Sub-agents remain internal execution topology. They do not appear as pseudo-models.
133132

134133
</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.
134+
<Accordion title="Why is `openclaw/default` included?">
135+
`openclaw/default` is the stable alias for the configured default agent.
137136

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.
137+
That means clients can keep using one predictable id even if the real default agent id changes between environments.
139138

140139
</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.
140+
<Accordion title="How do I override the backend model?">
141+
Use `x-openclaw-model`.
142+
143+
Examples:
144+
`x-openclaw-model: openai/gpt-5.4`
145+
`x-openclaw-model: gpt-5.4`
143146

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.
147+
If you omit it, the selected agent runs with its normal configured model choice.
145148

146149
</Accordion>
147-
<Accordion title="What should clients do in practice?">
148-
Use `/v1/models` to populate the normal model picker.
150+
<Accordion title="How do embeddings fit this contract?">
151+
`/v1/embeddings` uses the same agent-target `model` ids.
149152

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.
153+
Use `model: "openclaw/default"` or `model: "openclaw/<agentId>"`.
154+
When you need a specific embedding model, send it in `x-openclaw-model`.
155+
Without that header, the request passes through to the selected agent's normal embedding setup.
151156

152157
</Accordion>
153158
</AccordionGroup>
@@ -168,9 +173,8 @@ Non-streaming:
168173
curl -sS http://127.0.0.1:18789/v1/chat/completions \
169174
-H 'Authorization: Bearer YOUR_TOKEN' \
170175
-H 'Content-Type: application/json' \
171-
-H 'x-openclaw-agent-id: main' \
172176
-d '{
173-
"model": "openclaw",
177+
"model": "openclaw/default",
174178
"messages": [{"role":"user","content":"hi"}]
175179
}'
176180
```
@@ -181,9 +185,9 @@ Streaming:
181185
curl -N http://127.0.0.1:18789/v1/chat/completions \
182186
-H 'Authorization: Bearer YOUR_TOKEN' \
183187
-H 'Content-Type: application/json' \
184-
-H 'x-openclaw-agent-id: main' \
188+
-H 'x-openclaw-model: openai/gpt-5.4' \
185189
-d '{
186-
"model": "openclaw",
190+
"model": "openclaw/research",
187191
"stream": true,
188192
"messages": [{"role":"user","content":"hi"}]
189193
}'
@@ -199,7 +203,7 @@ curl -sS http://127.0.0.1:18789/v1/models \
199203
Fetch one model:
200204

201205
```bash
202-
curl -sS http://127.0.0.1:18789/v1/models/openai%2Fgpt-5.4 \
206+
curl -sS http://127.0.0.1:18789/v1/models/openclaw%2Fdefault \
203207
-H 'Authorization: Bearer YOUR_TOKEN'
204208
```
205209

@@ -209,15 +213,16 @@ Create embeddings:
209213
curl -sS http://127.0.0.1:18789/v1/embeddings \
210214
-H 'Authorization: Bearer YOUR_TOKEN' \
211215
-H 'Content-Type: application/json' \
212-
-H 'x-openclaw-agent-id: main' \
216+
-H 'x-openclaw-model: openai/text-embedding-3-small' \
213217
-d '{
214-
"model": "openai/text-embedding-3-small",
218+
"model": "openclaw/default",
215219
"input": ["alpha", "beta"]
216220
}'
217221
```
218222

219223
Notes:
220224

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.
225+
- `/v1/models` returns OpenClaw agent targets, not raw provider catalogs.
226+
- `openclaw/default` is always present so one stable id works across environments.
227+
- Backend provider/model overrides belong in `x-openclaw-model`, not the OpenAI `model` field.
223228
- `/v1/embeddings` supports `input` as a string or array of strings.

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

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,8 @@ Operational behavior matches [OpenAI Chat Completions](/gateway/openai-http-api)
2424

2525
- use `Authorization: Bearer <token>` with the normal Gateway auth config
2626
- treat the endpoint as full operator access for the gateway instance
27-
- select agents with `model: "openclaw:<agentId>"`, `model: "agent:<agentId>"`, or `x-openclaw-agent-id`
27+
- select agents with `model: "openclaw"`, `model: "openclaw/default"`, `model: "openclaw/<agentId>"`, or `x-openclaw-agent-id`
28+
- use `x-openclaw-model` when you want to override the selected agent's backend model
2829
- use `x-openclaw-session-key` for explicit session routing
2930
- use `x-openclaw-message-channel` when you want a non-default synthetic ingress channel context
3031

@@ -37,7 +38,7 @@ The same compatibility surface also includes:
3738
- `POST /v1/embeddings`
3839
- `POST /v1/chat/completions`
3940

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+
For the canonical explanation of how agent-target models, `openclaw/default`, embeddings pass-through, and backend model overrides fit together, see [OpenAI Chat Completions](/gateway/openai-http-api#agent-first-model-contract) and [Model list and agent routing](/gateway/openai-http-api#model-list-and-agent-routing).
4142

4243
## Session behavior
4344

‎src/agents/models-config.providers.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import type { OpenClawConfig } from "../config/config.js";
22
import { coerceSecretRef, resolveSecretInputRef } from "../config/types.secrets.js";
3+
import { normalizeGoogleApiBaseUrl } from "../infra/google-api-base-url.js";
34
import { createSubsystemLogger } from "../logging/subsystem.js";
45
import {
56
buildAnthropicVertexProvider,

‎src/gateway/embeddings-http.test.ts‎

Lines changed: 32 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -62,7 +62,7 @@ async function postEmbeddings(body: unknown, headers?: Record<string, string>) {
6262
describe("OpenAI-compatible embeddings HTTP API (e2e)", () => {
6363
it("embeds string and array inputs", async () => {
6464
const single = await postEmbeddings({
65-
model: "text-embedding-3-small",
65+
model: "openclaw/default",
6666
input: "hello",
6767
});
6868
expect(single.status).toBe(200);
@@ -75,7 +75,7 @@ describe("OpenAI-compatible embeddings HTTP API (e2e)", () => {
7575
expect(singleJson.data?.[0]?.embedding).toEqual([0.1, 0.2]);
7676

7777
const batch = await postEmbeddings({
78-
model: "text-embedding-3-small",
78+
model: "openclaw/default",
7979
input: ["a", "b"],
8080
});
8181
expect(batch.status).toBe(200);
@@ -87,13 +87,16 @@ describe("OpenAI-compatible embeddings HTTP API (e2e)", () => {
8787
{ object: "embedding", index: 1, embedding: [1.1, 1.2] },
8888
]);
8989

90-
const qualified = await postEmbeddings({
91-
model: "openai/text-embedding-3-small",
92-
input: "hello again",
93-
});
90+
const qualified = await postEmbeddings(
91+
{
92+
model: "openclaw/default",
93+
input: "hello again",
94+
},
95+
{ "x-openclaw-model": "openai/text-embedding-3-small" },
96+
);
9497
expect(qualified.status).toBe(200);
9598
const qualifiedJson = (await qualified.json()) as { model?: string };
96-
expect(qualifiedJson.model).toBe("openai/text-embedding-3-small");
99+
expect(qualifiedJson.model).toBe("openclaw/default");
97100
const lastCall = createEmbeddingProviderMock.mock.calls.at(-1)?.[0] as
98101
| { provider?: string; model?: string }
99102
| undefined;
@@ -106,7 +109,7 @@ describe("OpenAI-compatible embeddings HTTP API (e2e)", () => {
106109
it("supports base64 encoding and agent-scoped auth/config resolution", async () => {
107110
const res = await postEmbeddings(
108111
{
109-
model: "text-embedding-3-small",
112+
model: "openclaw/beta",
110113
input: "hello",
111114
encoding_format: "base64",
112115
},
@@ -119,28 +122,44 @@ describe("OpenAI-compatible embeddings HTTP API (e2e)", () => {
119122
const lastCall = createEmbeddingProviderMock.mock.calls.at(-1)?.[0] as
120123
| { provider?: string; model?: string; fallback?: string; agentDir?: string }
121124
| undefined;
122-
expect(lastCall?.model).toBe("text-embedding-3-small");
125+
expect(typeof lastCall?.model).toBe("string");
123126
expect(lastCall?.fallback).toBe("none");
124127
expect(lastCall?.agentDir).toBe(resolveAgentDir({}, "beta"));
125128
});
126129

127130
it("rejects invalid input shapes", async () => {
128131
const res = await postEmbeddings({
129-
model: "text-embedding-3-small",
132+
model: "openclaw/default",
130133
input: [{ nope: true }],
131134
});
132135
expect(res.status).toBe(400);
133136
const json = (await res.json()) as { error?: { type?: string } };
134137
expect(json.error?.type).toBe("invalid_request_error");
135138
});
136139

137-
it("rejects disallowed provider-prefixed model overrides", async () => {
140+
it("rejects invalid agent targets", async () => {
138141
const res = await postEmbeddings({
139142
model: "ollama/nomic-embed-text",
140143
input: "hello",
141144
});
142145
expect(res.status).toBe(400);
143146
const json = (await res.json()) as { error?: { type?: string; message?: string } };
147+
expect(json.error).toEqual({
148+
type: "invalid_request_error",
149+
message: "Invalid `model`. Use `openclaw` or `openclaw/<agentId>`.",
150+
});
151+
});
152+
153+
it("rejects disallowed x-openclaw-model provider overrides", async () => {
154+
const res = await postEmbeddings(
155+
{
156+
model: "openclaw/default",
157+
input: "hello",
158+
},
159+
{ "x-openclaw-model": "ollama/nomic-embed-text" },
160+
);
161+
expect(res.status).toBe(400);
162+
const json = (await res.json()) as { error?: { type?: string; message?: string } };
144163
expect(json.error).toEqual({
145164
type: "invalid_request_error",
146165
message: "This agent does not allow that embedding provider on `/v1/embeddings`.",
@@ -149,7 +168,7 @@ describe("OpenAI-compatible embeddings HTTP API (e2e)", () => {
149168

150169
it("rejects oversized batches", async () => {
151170
const res = await postEmbeddings({
152-
model: "text-embedding-3-small",
171+
model: "openclaw/default",
153172
input: Array.from({ length: 129 }, () => "x"),
154173
});
155174
expect(res.status).toBe(400);
@@ -163,7 +182,7 @@ describe("OpenAI-compatible embeddings HTTP API (e2e)", () => {
163182
it("sanitizes provider failures", async () => {
164183
createEmbeddingProviderMock.mockRejectedValueOnce(new Error("secret upstream failure"));
165184
const res = await postEmbeddings({
166-
model: "text-embedding-3-small",
185+
model: "openclaw/default",
167186
input: "hello",
168187
});
169188
expect(res.status).toBe(500);

‎src/gateway/embeddings-http.ts‎

Lines changed: 21 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,12 @@ import type { AuthRateLimiter } from "./auth-rate-limit.js";
1414
import type { ResolvedGatewayAuth } from "./auth.js";
1515
import { sendJson } from "./http-common.js";
1616
import { handleGatewayPostJsonEndpoint } from "./http-endpoint-helpers.js";
17-
import { resolveAgentIdFromHeader } from "./http-utils.js";
17+
import {
18+
OPENCLAW_MODEL_ID,
19+
getHeader,
20+
resolveAgentIdForRequest,
21+
resolveAgentIdFromModel,
22+
} from "./http-utils.js";
1823

1924
type OpenAiEmbeddingsHttpOptions = {
2025
auth: ResolvedGatewayAuth;
@@ -148,6 +153,17 @@ export async function handleOpenAiEmbeddingsHttpRequest(
148153
return true;
149154
}
150155

156+
const cfg = loadConfig();
157+
if (requestModel !== OPENCLAW_MODEL_ID && !resolveAgentIdFromModel(requestModel, cfg)) {
158+
sendJson(res, 400, {
159+
error: {
160+
message: "Invalid `model`. Use `openclaw` or `openclaw/<agentId>`.",
161+
type: "invalid_request_error",
162+
},
163+
});
164+
return true;
165+
}
166+
151167
const texts = resolveInputTexts(payload.input);
152168
if (!texts) {
153169
sendJson(res, 400, {
@@ -166,15 +182,12 @@ export async function handleOpenAiEmbeddingsHttpRequest(
166182
return true;
167183
}
168184

169-
const cfg = loadConfig();
170-
const agentId = resolveAgentIdFromHeader(req) ?? "main";
185+
const agentId = resolveAgentIdForRequest({ req, model: requestModel });
171186
const agentDir = resolveAgentDir(cfg, agentId);
172187
const memorySearch = resolveMemorySearchConfig(cfg, agentId);
173188
const configuredProvider = (memorySearch?.provider ?? "openai") as EmbeddingProviderRequest;
174-
const target = resolveEmbeddingsTarget({
175-
requestModel,
176-
configuredProvider,
177-
});
189+
const overrideModel = getHeader(req, "x-openclaw-model")?.trim() || memorySearch?.model || "";
190+
const target = resolveEmbeddingsTarget({ requestModel: overrideModel, configuredProvider });
178191
if ("errorMessage" in target) {
179192
sendJson(res, 400, {
180193
error: {
@@ -229,10 +242,7 @@ export async function handleOpenAiEmbeddingsHttpRequest(
229242
index,
230243
embedding: encodingFormat === "base64" ? encodeEmbeddingBase64(embedding) : embedding,
231244
})),
232-
model:
233-
requestModel.includes("/") || target.provider === "auto"
234-
? requestModel
235-
: `${target.provider}/${target.model}`,
245+
model: requestModel,
236246
usage: {
237247
prompt_tokens: 0,
238248
total_tokens: 0,

0 commit comments

Comments
 (0)