Skip to content

Commit 4e12d05

Browse files
hartmarksteipete
andauthored
feat(ai): continue stateful OpenAI SSE turns (#122194)
* feat(ai): continue stateful OpenAI SSE turns Use the prior OpenAI Responses ID for native stateful HTTP/SSE turns, retry missing server state with full history in the same turn, and keep stateless/custom routes unchanged. Co-authored-by: Markus Hartung <[email protected]> * test(ai): assert Responses retry attempt metadata --------- Co-authored-by: Peter Steinberger <[email protected]>
1 parent c23d66e commit 4e12d05

11 files changed

Lines changed: 911 additions & 188 deletions
Lines changed: 355 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,355 @@
1+
import type { AssistantMessage, Context, Model } from "@openclaw/llm-core";
2+
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
3+
4+
type SdkResponse = { data: AsyncIterable<unknown>; response: Response };
5+
6+
const sseState = vi.hoisted(() => ({
7+
clientHeaders: [] as Array<Record<string, string>>,
8+
outcomes: [] as Array<Error | SdkResponse>,
9+
requests: [] as Array<Record<string, unknown>>,
10+
}));
11+
12+
vi.mock("openai", () => {
13+
class MockOpenAI {
14+
apiKey: string;
15+
baseURL: string;
16+
responses = {
17+
create: (request: Record<string, unknown>) => {
18+
sseState.requests.push(request);
19+
const outcome = sseState.outcomes.shift() ?? new Error("Unexpected SSE request");
20+
return {
21+
withResponse: async () => {
22+
if (outcome instanceof Error) {
23+
throw outcome;
24+
}
25+
return outcome;
26+
},
27+
};
28+
},
29+
};
30+
31+
constructor(options: {
32+
apiKey?: string;
33+
baseURL?: string;
34+
defaultHeaders?: Record<string, string>;
35+
}) {
36+
this.apiKey = options.apiKey ?? "";
37+
this.baseURL = options.baseURL ?? "https://api.openai.com/v1";
38+
sseState.clientHeaders.push(options.defaultHeaders ?? {});
39+
}
40+
}
41+
42+
return { default: MockOpenAI, AzureOpenAI: MockOpenAI };
43+
});
44+
45+
vi.mock("openai/resources/responses/ws.js", () => ({
46+
ResponsesWS: function UnexpectedResponsesWS() {
47+
throw new Error("SSE continuation tests must not construct a WebSocket");
48+
},
49+
}));
50+
51+
import { configureAiTransportHost, getAiTransportHost } from "../host.js";
52+
import { cleanupSessionResources } from "../session-resources.js";
53+
import { createOpenAIResponsesTransportStreamFn } from "./openai-responses-client.js";
54+
55+
const initialHost = getAiTransportHost();
56+
const model = {
57+
id: "gpt-5.6-luna",
58+
name: "GPT-5.6 Luna",
59+
api: "openai-responses",
60+
provider: "openai",
61+
baseUrl: "https://api.openai.com/v1",
62+
reasoning: true,
63+
input: ["text"],
64+
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
65+
contextWindow: 200_000,
66+
maxTokens: 8192,
67+
} satisfies Model<"openai-responses">;
68+
69+
function userMessage(text: string, timestamp: number) {
70+
return { role: "user" as const, content: text, timestamp };
71+
}
72+
73+
function completedEvent(responseId: string, content: string) {
74+
const output = [
75+
{
76+
id: `msg_${responseId}`,
77+
type: "message",
78+
status: "completed",
79+
content: [
80+
{
81+
annotations: [
82+
{
83+
type: "url_citation",
84+
url: "https://example.test/source",
85+
title: "source",
86+
start_index: 0,
87+
end_index: content.length,
88+
},
89+
],
90+
logprobs: [{ token: content, logprob: -0.1, bytes: [], top_logprobs: [] }],
91+
text: content,
92+
type: "output_text",
93+
},
94+
],
95+
role: "assistant",
96+
phase: "final_answer",
97+
},
98+
];
99+
return {
100+
type: "response.completed",
101+
response: {
102+
id: responseId,
103+
status: "completed",
104+
output,
105+
usage: { input_tokens: 5, output_tokens: 3, total_tokens: 8 },
106+
},
107+
};
108+
}
109+
110+
function sdkCompletion(responseId: string, content: string): SdkResponse {
111+
return sdkEvents(completedEvent(responseId, content));
112+
}
113+
114+
function sdkEvents(...events: Array<Record<string, unknown>>): SdkResponse {
115+
return {
116+
data: (async function* () {
117+
yield* events;
118+
})(),
119+
response: new Response(null, { status: 200 }),
120+
};
121+
}
122+
123+
async function run(
124+
context: Context,
125+
options: {
126+
sessionId?: string;
127+
onPayload: (payload: Record<string, unknown>) => Record<string, unknown>;
128+
signal?: AbortSignal;
129+
},
130+
): Promise<AssistantMessage> {
131+
const stream = await createOpenAIResponsesTransportStreamFn()(model, context, {
132+
apiKey: "test-key",
133+
sessionId: options.sessionId ?? "session-1",
134+
transport: "sse",
135+
reasoningEffort: "low",
136+
onPayload: options.onPayload,
137+
signal: options.signal,
138+
} as never);
139+
return stream.result();
140+
}
141+
142+
describe("native OpenAI Responses SSE continuation", () => {
143+
beforeEach(() => {
144+
cleanupSessionResources();
145+
sseState.clientHeaders.length = 0;
146+
sseState.outcomes.length = 0;
147+
sseState.requests.length = 0;
148+
let turn = 0;
149+
configureAiTransportHost({
150+
...initialHost,
151+
plugin: {
152+
...initialHost.plugin,
153+
resolveTransportTurnState: ({ context }) => {
154+
turn += 1;
155+
return {
156+
headers: {
157+
"x-openclaw-session-id": context.sessionId ?? "",
158+
"x-openclaw-turn-id": `turn-${turn}`,
159+
"x-openclaw-turn-attempt": "1",
160+
},
161+
metadata: {
162+
openclaw_session_id: context.sessionId ?? "",
163+
openclaw_turn_id: `turn-${turn}`,
164+
openclaw_turn_attempt: "1",
165+
openclaw_transport: context.transport,
166+
},
167+
};
168+
},
169+
},
170+
});
171+
});
172+
173+
afterEach(() => {
174+
cleanupSessionResources();
175+
configureAiTransportHost(initialHost);
176+
});
177+
178+
it("continues stateful literal SSE turns with only appended input", async () => {
179+
sseState.outcomes.push(
180+
sdkCompletion("resp_1", "first answer"),
181+
sdkCompletion("resp_2", "second answer"),
182+
);
183+
const firstUser = userMessage("first question", 1);
184+
const onPayload = (payload: Record<string, unknown>) => ({ ...payload, store: true });
185+
const first = await run({ messages: [firstUser], tools: [] }, { onPayload });
186+
const second = await run(
187+
{ messages: [firstUser, first, userMessage("second question", 2)], tools: [] },
188+
{ onPayload },
189+
);
190+
191+
expect(second.stopReason).toBe("stop");
192+
expect(sseState.clientHeaders).toMatchObject([
193+
{ "x-openclaw-turn-id": "turn-1" },
194+
{ "x-openclaw-turn-id": "turn-2" },
195+
]);
196+
expect(sseState.requests[1]).toMatchObject({
197+
previous_response_id: "resp_1",
198+
input: [
199+
{
200+
type: "message",
201+
role: "user",
202+
content: [{ type: "input_text", text: "second question" }],
203+
},
204+
],
205+
});
206+
});
207+
208+
it("keeps final store:false turns stateless and sends full history", async () => {
209+
sseState.outcomes.push(
210+
sdkCompletion("resp_1", "first answer"),
211+
sdkCompletion("resp_2", "second answer"),
212+
);
213+
const firstUser = userMessage("first question", 1);
214+
const onPayload = (payload: Record<string, unknown>) => ({ ...payload, store: false });
215+
const first = await run({ messages: [firstUser], tools: [] }, { onPayload });
216+
await run(
217+
{ messages: [firstUser, first, userMessage("second question", 2)], tools: [] },
218+
{ onPayload },
219+
);
220+
221+
expect(sseState.requests[1]).not.toHaveProperty("previous_response_id");
222+
expect(sseState.requests[1]?.input).toHaveLength(3);
223+
});
224+
225+
it("recovers a rejected continuation with full history and advances the baseline", async () => {
226+
sseState.outcomes.push(
227+
sdkCompletion("resp_1", "first answer"),
228+
Object.assign(new Error("previous response not found"), {
229+
code: "previous_response_not_found",
230+
status: 400,
231+
}),
232+
sdkCompletion("resp_2", "second answer"),
233+
sdkCompletion("resp_3", "third answer"),
234+
);
235+
const onPayload = (payload: Record<string, unknown>) => ({ ...payload, store: true });
236+
const firstUser = userMessage("first question", 1);
237+
const first = await run({ messages: [firstUser], tools: [] }, { onPayload });
238+
const secondContext = {
239+
messages: [firstUser, first, userMessage("second question", 2)],
240+
tools: [],
241+
};
242+
const second = await run(secondContext, { onPayload });
243+
await run(
244+
{
245+
messages: [...secondContext.messages, second, userMessage("third question", 3)],
246+
tools: [],
247+
},
248+
{ onPayload },
249+
);
250+
251+
expect(sseState.requests[1]).toMatchObject({ previous_response_id: "resp_1" });
252+
expect(sseState.requests[1]?.input).toHaveLength(1);
253+
expect(sseState.requests[2]).not.toHaveProperty("previous_response_id");
254+
expect(sseState.requests[2]?.input).toHaveLength(3);
255+
expect(sseState.requests[3]).toMatchObject({ previous_response_id: "resp_2" });
256+
expect(sseState.requests[3]?.input).toHaveLength(1);
257+
});
258+
259+
it("records the effective full-history compaction recovery request", async () => {
260+
sseState.outcomes.push(
261+
sdkCompletion("resp_1", "first answer"),
262+
Object.assign(new Error("invalid encrypted content"), {
263+
code: "invalid_encrypted_content",
264+
}),
265+
sdkCompletion("resp_2", "second answer"),
266+
sdkCompletion("resp_3", "third answer"),
267+
);
268+
const stateful = (payload: Record<string, unknown>) => ({ ...payload, store: true });
269+
const withCompaction = (payload: Record<string, unknown>) => ({
270+
...payload,
271+
store: true,
272+
input: [
273+
...((payload.input as unknown[]) ?? []),
274+
{ type: "compaction", encrypted_content: "opaque" },
275+
],
276+
});
277+
const firstUser = userMessage("first question", 1);
278+
const first = await run({ messages: [firstUser], tools: [] }, { onPayload: stateful });
279+
const secondContext = {
280+
messages: [firstUser, first, userMessage("second question", 2)],
281+
tools: [],
282+
};
283+
const second = await run(secondContext, { onPayload: withCompaction });
284+
await run(
285+
{
286+
messages: [...secondContext.messages, second, userMessage("third question", 3)],
287+
tools: [],
288+
},
289+
{ onPayload: stateful },
290+
);
291+
292+
expect(sseState.requests[1]).toMatchObject({ previous_response_id: "resp_1" });
293+
expect(JSON.stringify(sseState.requests[1]?.input)).toContain('"compaction"');
294+
expect(sseState.requests[2]).not.toHaveProperty("previous_response_id");
295+
expect(JSON.stringify(sseState.requests[2]?.input)).not.toContain('"compaction"');
296+
expect(sseState.requests[3]).toMatchObject({ previous_response_id: "resp_2" });
297+
});
298+
299+
it.each([
300+
"request failure",
301+
"continuation error without previous_response_id",
302+
"incomplete response",
303+
"post-dispatch stream rejection",
304+
"abort",
305+
])("does not commit after %s", async (failure) => {
306+
const controller = new AbortController();
307+
if (failure === "request failure") {
308+
sseState.outcomes.push(new Error("request failed"));
309+
} else if (failure === "continuation error without previous_response_id") {
310+
sseState.outcomes.push(
311+
Object.assign(new Error("previous response not found"), {
312+
code: "previous_response_not_found",
313+
status: 400,
314+
}),
315+
);
316+
} else if (failure === "incomplete response") {
317+
sseState.outcomes.push(
318+
sdkEvents({
319+
type: "response.incomplete",
320+
response: { id: "resp_incomplete", status: "incomplete", output: [] },
321+
}),
322+
);
323+
} else if (failure === "post-dispatch stream rejection") {
324+
sseState.outcomes.push(
325+
sdkEvents({
326+
type: "error",
327+
code: "previous_response_not_found",
328+
message: "previous response not found after stream acceptance",
329+
}),
330+
);
331+
} else {
332+
sseState.outcomes.push({
333+
data: (async function* () {
334+
controller.abort();
335+
yield completedEvent("resp_aborted", "ignored");
336+
})(),
337+
response: new Response(null, { status: 200 }),
338+
});
339+
}
340+
sseState.outcomes.push(sdkCompletion("resp_next", "next answer"));
341+
const onPayload = (payload: Record<string, unknown>) => ({ ...payload, store: true });
342+
const sessionId = `session-${failure}`;
343+
await run(
344+
{ messages: [userMessage("first", 1)], tools: [] },
345+
{
346+
onPayload,
347+
sessionId,
348+
signal: failure === "abort" ? controller.signal : undefined,
349+
},
350+
);
351+
await run({ messages: [userMessage("next", 2)], tools: [] }, { onPayload, sessionId });
352+
353+
expect(sseState.requests[1]).not.toHaveProperty("previous_response_id");
354+
});
355+
});

0 commit comments

Comments
 (0)