Skip to content

Commit dabe607

Browse files
committed
fix(ai): restore cached OpenAI continuation
1 parent 7e4c7f0 commit dabe607

4 files changed

Lines changed: 76 additions & 23 deletions

File tree

‎docs/concepts/model-providers.md‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -108,8 +108,8 @@ Official provider plugins publish their own model catalog rows. These providers
108108
- Example models: `openai/gpt-5.6-sol`, `openai/gpt-5.6-terra`, `openai/gpt-5.6-luna`, `openai/gpt-5.5`; the bare direct-API `openai/gpt-5.6` alias remains supported.
109109
- Verify account/model availability with `openclaw models list --provider openai` if a specific install or API key behaves differently.
110110
- CLI: `openclaw onboard --auth-choice openai-api-key`
111-
- Default transport is `auto`; OpenClaw passes the transport choice to the shared model runtime.
112-
- Override per model via `agents.defaults.models["openai/<model>"].params.transport` (`"sse"`, `"websocket"`, or `"auto"`)
111+
- Direct OpenAI API-key Responses requests default to `"sse"`.
112+
- Override per model via `agents.defaults.models["openai/<model>"].params.transport` (`"sse"`, `"websocket"`, `"websocket-cached"`, or `"auto"`). Cached WebSockets reuse the session connection and send only new input with `previous_response_id` when history still matches.
113113
- Set an explicit OpenAI API service tier with `params.serviceTier` or `params.service_tier`; Fast mode (formerly Priority processing) uses `service_tier=priority`.
114114
- On native public OpenAI and ChatGPT/Codex Responses requests, precedence is payload/transport `service_tier`, then a valid explicit model param, then the fast-mode default.
115115
- `/fast` and valid `params.fastMode` / `params.fast_mode` values are shared agent-runtime controls; on direct embedded `openai/*` Responses requests they supply `service_tier=priority` only when no higher-precedence tier exists.

‎packages/ai/src/transports/openai-responses-websocket-client.test.ts‎

Lines changed: 20 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -136,11 +136,27 @@ function completedEvent(responseId: string, content?: string | Array<Record<stri
136136
typeof content === "string"
137137
? [
138138
{
139-
type: "message",
140139
id: `msg_${responseId}`,
141-
role: "assistant",
140+
type: "message",
142141
status: "completed",
143-
content: [{ type: "output_text", text: content, annotations: [] }],
142+
content: [
143+
{
144+
annotations: [
145+
{
146+
type: "url_citation",
147+
url: "https://example.test/source",
148+
title: "source",
149+
start_index: 0,
150+
end_index: content.length,
151+
},
152+
],
153+
logprobs: [{ token: content, logprob: -0.1, bytes: [], top_logprobs: [] }],
154+
text: content,
155+
type: "output_text",
156+
},
157+
],
158+
role: "assistant",
159+
phase: "final_answer",
144160
},
145161
]
146162
: (content ?? []);
@@ -281,7 +297,7 @@ describe("native OpenAI Responses WebSocket client integration", () => {
281297
configureAiTransportHost(initialHost);
282298
});
283299

284-
it("reuses one production-path session socket and continues with only new input", async () => {
300+
it("continues past provider-only output metadata with one socket and only new input", async () => {
285301
transportState.responseBatches.push(
286302
[message(completedEvent("resp_1", "first answer"))],
287303
[message(completedEvent("resp_2", "second answer"))],

‎packages/ai/src/transports/openai-responses-websocket.test.ts‎

Lines changed: 23 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -83,6 +83,7 @@ const assistantOutput = {
8383
role: "assistant",
8484
status: "completed",
8585
content: [{ type: "output_text", text: "one", annotations: [] }],
86+
phase: "final_answer",
8687
};
8788

8889
function completion(responseId: string, output: Array<Record<string, unknown>> = []) {
@@ -206,22 +207,30 @@ describe("native OpenAI Responses WebSocket transport", () => {
206207
});
207208
});
208209

209-
it("uses the response id when persisted encrypted reasoning has a different replay shape", async () => {
210+
it("continues across equivalent request ordering, omissions, and persisted reasoning replay", async () => {
210211
const reasoning = { type: "reasoning", id: "rs_1", encrypted_content: "ciphertext" };
211212
websocketState.responseBatches.push(
212213
[completion("resp_1", [reasoning, assistantOutput])],
213214
[completion("resp_2")],
214215
);
215-
await consumeResponse(createStream({ model: "gpt-5.6-luna", input: [firstUser] }));
216+
await consumeResponse(
217+
createStream({
218+
model: "gpt-5.6-luna",
219+
metadata: { beta: "2", alpha: "1" },
220+
max_output_tokens: undefined,
221+
input: [firstUser],
222+
}),
223+
);
216224

217225
const second = createStream({
218-
model: "gpt-5.6-luna",
219226
input: [
220227
firstUser,
221228
{ type: "reasoning", summary: [] },
222229
assistantOutput,
223230
{ role: "user", content: "second" },
224231
],
232+
metadata: { alpha: "1", beta: "2" },
233+
model: "gpt-5.6-luna",
225234
});
226235

227236
expect(second.continuationStatus).toBe("continued");
@@ -304,6 +313,17 @@ describe("native OpenAI Responses WebSocket transport", () => {
304313
input: [{ role: "user", content: "rewritten" }],
305314
}),
306315
},
316+
{
317+
name: "assistant phase change",
318+
mutate: (request: Record<string, unknown>) => ({
319+
...request,
320+
input: [
321+
firstUser,
322+
{ ...assistantOutput, phase: "commentary" },
323+
{ role: "user", content: "second" },
324+
],
325+
}),
326+
},
307327
])("resets continuation on $name", async ({ mutate }) => {
308328
websocketState.responseBatches.push(
309329
[completion("resp_1", [assistantOutput])],

‎packages/ai/src/transports/openai-responses-websocket.ts‎

Lines changed: 31 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
import { stableStringify } from "@openclaw/normalization-core";
2+
import { isRecord } from "@openclaw/normalization-core/record-coerce";
13
import type OpenAI from "openai";
24
import type {
35
ResponseInput,
@@ -299,22 +301,35 @@ function sanitizeWebSocketRequest(request: Record<string, unknown>): ResponsesWe
299301
return websocketRequest as ResponsesWebSocketRequest;
300302
}
301303

304+
function jsonValuesEqual(left: object, right: object): boolean {
305+
// Round-trip first so stable key ordering retains JSON's omitted/undefined wire semantics.
306+
const leftJson = JSON.parse(JSON.stringify(left) as string);
307+
const rightJson = JSON.parse(JSON.stringify(right) as string);
308+
return stableStringify(leftJson) === stableStringify(rightJson);
309+
}
310+
302311
function normalizeAssistantReplayInput(input: readonly unknown[]): unknown[] {
303312
return input.map((item) => {
304-
if (!item || typeof item !== "object" || Array.isArray(item)) {
313+
if (!isRecord(item)) {
305314
return item;
306315
}
307-
const typedItem = item as unknown as Record<string, unknown>;
308-
if (typedItem.type === "reasoning") {
316+
if (item.type === "reasoning") {
309317
return { type: "reasoning" };
310318
}
311-
if (
312-
typedItem.type !== "function_call" &&
313-
!(typedItem.type === "message" && typedItem.role === "assistant")
314-
) {
319+
if (item.type !== "function_call" && !(item.type === "message" && item.role === "assistant")) {
315320
return item;
316321
}
317-
const { id: _id, status: _status, ...stableItem } = typedItem;
322+
const { id: _id, status: _status, ...stableItem } = item;
323+
if (item.type === "message" && Array.isArray(stableItem.content)) {
324+
// Strip only provider delivery metadata that reconstructed assistant replay cannot contain.
325+
stableItem.content = stableItem.content.map((part) => {
326+
if (!isRecord(part) || part.type !== "output_text") {
327+
return part;
328+
}
329+
const { annotations: _annotations, logprobs: _logprobs, ...stablePart } = part;
330+
return stablePart;
331+
});
332+
}
318333
return stableItem;
319334
});
320335
}
@@ -340,8 +355,7 @@ function buildCachedWebSocketRequest(
340355
return rejectContinuation("explicit_previous_response_id");
341356
}
342357
if (
343-
JSON.stringify(requestWithoutInput(request)) !==
344-
JSON.stringify(requestWithoutInput(continuation.lastRequest))
358+
!jsonValuesEqual(requestWithoutInput(request), requestWithoutInput(continuation.lastRequest))
345359
) {
346360
return rejectContinuation("request_changed");
347361
}
@@ -353,11 +367,14 @@ function buildCachedWebSocketRequest(
353367
return rejectContinuation("history_shorter");
354368
}
355369
if (
356-
JSON.stringify(normalizeAssistantReplayInput(currentInput.slice(0, previousInput.length))) !==
357-
JSON.stringify(normalizeAssistantReplayInput(previousInput)) ||
358-
JSON.stringify(
370+
!jsonValuesEqual(
371+
normalizeAssistantReplayInput(currentInput.slice(0, previousInput.length)),
372+
normalizeAssistantReplayInput(previousInput),
373+
) ||
374+
!jsonValuesEqual(
359375
normalizeAssistantReplayInput(currentInput.slice(previousInput.length, baselineLength)),
360-
) !== JSON.stringify(normalizeAssistantReplayInput(continuation.lastResponseItems))
376+
normalizeAssistantReplayInput(continuation.lastResponseItems),
377+
)
361378
) {
362379
return rejectContinuation("history_changed");
363380
}

0 commit comments

Comments
 (0)