Skip to content

Commit 741b748

Browse files
committed
fix(providers): prevent idle timeouts during hidden reasoning
1 parent d894a23 commit 741b748

4 files changed

Lines changed: 150 additions & 0 deletions

File tree

‎packages/ai/src/providers/openai-completions.test.ts‎

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,11 +3,14 @@ import type { ChatCompletionChunk } from "openai/resources/chat/completions.js";
33
import { beforeEach, describe, expect, it, vi } from "vitest";
44
import { configureAiTransportHost } from "../host.js";
55
import type { Context, Model, SimpleStreamOptions, TextContent } from "../types.js";
6+
import { onLlmRequestActivity } from "../utils/llm-request-activity.js";
67
import { SYSTEM_PROMPT_CACHE_BOUNDARY } from "../utils/system-prompt-cache-boundary.js";
78

89
type DeepPartial<T> = { [P in keyof T]?: DeepPartial<T[P]> };
910
type OpenAICompatibleDelta = DeepPartial<ChatCompletionChunk["choices"][number]["delta"]> & {
1011
reasoning_content?: string;
12+
reasoning?: string;
13+
reasoning_text?: string;
1114
};
1215
type OpenAICompatibleChoice = Omit<
1316
DeepPartial<ChatCompletionChunk["choices"][number]>,
@@ -1430,6 +1433,40 @@ describe("openai-completions stop-reason tool-call guard", () => {
14301433
expect(result.content.some((block) => block.type === "thinking")).toBe(false);
14311434
});
14321435

1436+
it.each(["reasoning_content", "reasoning", "reasoning_text"] as const)(
1437+
"reports hidden %s chunks as request activity",
1438+
async (reasoningField) => {
1439+
mockChunksRef.chunks = [
1440+
{
1441+
id: "chatcmpl-test",
1442+
choices: [{ index: 0, delta: { [reasoningField]: "private reasoning" } }],
1443+
},
1444+
{
1445+
id: "chatcmpl-test",
1446+
choices: [{ index: 0, delta: { [reasoningField]: "still private" } }],
1447+
},
1448+
makeTextChunk("visible answer"),
1449+
makeFinishChunk("stop"),
1450+
];
1451+
const abortController = new AbortController();
1452+
const onActivity = vi.fn();
1453+
const unsubscribe = onLlmRequestActivity(abortController.signal, onActivity);
1454+
1455+
try {
1456+
const result = await streamOpenAICompletions(model, context, {
1457+
apiKey: "sk-test",
1458+
signal: abortController.signal,
1459+
}).result();
1460+
1461+
expect(onActivity).toHaveBeenCalledTimes(mockChunksRef.chunks.length);
1462+
expect(result.content).toContainEqual({ type: "text", text: "visible answer" });
1463+
expect(result.content.some((block) => block.type === "thinking")).toBe(false);
1464+
} finally {
1465+
unsubscribe();
1466+
}
1467+
},
1468+
);
1469+
14331470
it("seals the native reasoning block before the answer text begins", async () => {
14341471
// deepseek streams reasoning_content, then switches to content with no
14351472
// boundary event; thinking_end must precede the answer so channels do not

‎packages/ai/src/providers/openai-completions.ts‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -45,6 +45,7 @@ import {
4545
import { AssistantMessageEventStream } from "../utils/event-stream.js";
4646
import { headersToRecord } from "../utils/headers.js";
4747
import { parseStreamingJson } from "../utils/json-parse.js";
48+
import { notifyLlmRequestActivity } from "../utils/llm-request-activity.js";
4849
import { formatProviderError } from "../utils/provider-error.js";
4950
import { createReasoningTagTextPartitioner } from "../utils/reasoning-tag-text-partitioner.js";
5051
import {
@@ -393,6 +394,9 @@ export const streamOpenAICompletions: StreamFunction<
393394
continue;
394395
}
395396

397+
// Hidden reasoning is still provider progress; keep the idle watchdog alive without exposing it.
398+
notifyLlmRequestActivity(options?.signal);
399+
396400
// OpenAI documents ChatCompletionChunk.id as the unique chat completion identifier,
397401
// and each chunk in a streamed completion carries the same id.
398402
output.responseId ||= chunk.id;

‎packages/ai/src/transports/openai-completions-transport.ts‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,7 @@ import {
3333
} from "../utils/assistant-text-phase.js";
3434
import { createAssistantMessageEventStream } from "../utils/event-stream.js";
3535
import { parseStreamingJson } from "../utils/json-parse.js";
36+
import { notifyLlmRequestActivity } from "../utils/llm-request-activity.js";
3637
import { createReasoningTagTextPartitioner } from "../utils/reasoning-tag-text-partitioner.js";
3738
import {
3839
createFirstStreamEventAbortController,
@@ -631,6 +632,8 @@ async function processOpenAICompletionsStream(
631632
await cooperativeScheduler.afterEvent();
632633
continue;
633634
}
635+
// Hidden reasoning is still provider progress; keep the idle watchdog alive without exposing it.
636+
notifyLlmRequestActivity(options?.signal);
634637
const chunk = rawChunk as ChatCompletionChunk;
635638
output.responseId ||= chunk.id;
636639
let hasReasoningUsageActivity = false;

‎src/agents/openai-transport-stream.streaming.test.ts‎

Lines changed: 106 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ import {
66
classifyAssistantFailoverReason,
77
formatUserFacingAssistantErrorText,
88
} from "./embedded-agent-helpers.js";
9+
import { streamWithIdleTimeout } from "./embedded-agent-runner/run/llm-idle-timeout.js";
910
import {
1011
parseTransportChunkUsage,
1112
type CapturedStreamEvent,
@@ -181,6 +182,111 @@ describe("openai transport stream", () => {
181182
}
182183
});
183184

185+
it.each(["reasoning_content", "reasoning"] as const)(
186+
"keeps hidden local %s streams alive beyond the model idle timeout",
187+
async (reasoningField) => {
188+
const reasoningChunkCount = 5;
189+
const reasoningChunkDelayMs = 35;
190+
const idleTimeoutMs = 100;
191+
const server = createServer((req, res) => {
192+
req.resume();
193+
req.on("end", () => {
194+
res.writeHead(200, {
195+
"content-type": "text/event-stream; charset=utf-8",
196+
"cache-control": "no-cache",
197+
connection: "keep-alive",
198+
});
199+
200+
let reasoningChunksSent = 0;
201+
const writeNextChunk = () => {
202+
if (res.destroyed) {
203+
return;
204+
}
205+
if (reasoningChunksSent < reasoningChunkCount) {
206+
reasoningChunksSent += 1;
207+
const reasoningChunk = {
208+
id: "chatcmpl-local-reasoning",
209+
object: "chat.completion.chunk",
210+
created: 1,
211+
model: "nemotron-local",
212+
choices: [
213+
{
214+
index: 0,
215+
delta: { [reasoningField]: "private reasoning" },
216+
finish_reason: null,
217+
},
218+
],
219+
};
220+
res.write(`data: ${JSON.stringify(reasoningChunk)}\n\n`);
221+
setTimeout(writeNextChunk, reasoningChunkDelayMs);
222+
return;
223+
}
224+
225+
res.write(
226+
`data: ${JSON.stringify(makeCompletionsChunk({ role: "assistant", content: "OK" }))}\n\n`,
227+
);
228+
res.write(`data: ${JSON.stringify(makeCompletionsChunk({}, "stop"))}\n\n`);
229+
res.write("data: [DONE]\n\n");
230+
res.end();
231+
};
232+
233+
writeNextChunk();
234+
});
235+
});
236+
237+
await new Promise<void>((resolve) => {
238+
server.listen(0, "127.0.0.1", resolve);
239+
});
240+
try {
241+
const address = server.address();
242+
if (!address || typeof address === "string") {
243+
throw new Error("Missing loopback server address");
244+
}
245+
const model = makeCompletionsModel({
246+
id: "nemotron-local",
247+
name: "Local Nemotron",
248+
provider: "inference",
249+
baseUrl: `http://127.0.0.1:${address.port}/v1`,
250+
reasoning: false,
251+
});
252+
const onIdleTimeout = vi.fn();
253+
const streamFn = streamWithIdleTimeout(
254+
createOpenAICompletionsTransportStreamFn(),
255+
idleTimeoutMs,
256+
onIdleTimeout,
257+
);
258+
const stream = streamFn(
259+
model,
260+
{
261+
systemPrompt: "system",
262+
messages: [{ role: "user", content: "Reply OK", timestamp: Date.now() }],
263+
tools: [],
264+
} as never,
265+
{ apiKey: "test-key" } as never,
266+
);
267+
268+
let text = "";
269+
let thinking = "";
270+
for await (const event of stream as AsyncIterable<{ type: string; delta?: string }>) {
271+
if (event.type === "text_delta") {
272+
text += event.delta ?? "";
273+
}
274+
if (event.type === "thinking_delta") {
275+
thinking += event.delta ?? "";
276+
}
277+
}
278+
279+
expect(text).toBe("OK");
280+
expect(thinking).toBe("");
281+
expect(onIdleTimeout).not.toHaveBeenCalled();
282+
} finally {
283+
await new Promise<void>((resolve, reject) => {
284+
server.close((error) => (error ? reject(error) : resolve()));
285+
});
286+
}
287+
},
288+
);
289+
184290
it("refuses ModelStudio chat streams with no user or assistant payload turns", async () => {
185291
const model = makeCompletionsModel({
186292
id: "qwen-coder-plus",

0 commit comments

Comments
 (0)