Skip to content

Commit 26e73fa

Browse files
niuma996claude
andcommitted
fix(gateway): separate finish_reason from content chunks in streaming responses
Per OpenAI streaming spec, finish_reason must appear only on the final chunk at choices[0] level with an empty delta, not mixed into content chunks. Split writeAssistantContentChunk (always finish_reason: null) from a new writeAssistantFinishChunk (empty delta, finish_reason: stop). Emit the finish chunk from the lifecycle end handler, the error path, and the finally fallback path. Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
1 parent 828c64e commit 26e73fa

2 files changed

Lines changed: 52 additions & 10 deletions

File tree

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

Lines changed: 29 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -792,6 +792,21 @@ describe("OpenAI-compatible HTTP API (e2e)", () => {
792792
.filter((v): v is string => typeof v === "string")
793793
.join("");
794794
expect(allContent).toBe("hello");
795+
796+
// Per OpenAI streaming spec: content chunks have finish_reason: null,
797+
// final chunk has finish_reason: "stop" with empty delta
798+
const allChoices = jsonChunks.flatMap(
799+
(c) => (c.choices as Array<Record<string, unknown>> | undefined) ?? [],
800+
);
801+
const contentChoices = allChoices.filter(
802+
(choice) => (choice.delta as Record<string, unknown> | undefined)?.content !== undefined,
803+
);
804+
for (const choice of contentChoices) {
805+
expect(choice).toHaveProperty("finish_reason", null);
806+
}
807+
const stopChoice = allChoices.findLast((choice) => choice.finish_reason === "stop");
808+
expect(stopChoice).toBeDefined();
809+
expect((stopChoice?.delta as Record<string, unknown>)?.content).toBeUndefined();
795810
}
796811

797812
{
@@ -857,12 +872,21 @@ describe("OpenAI-compatible HTTP API (e2e)", () => {
857872
const errorChunks = errorData
858873
.filter((d) => d !== "[DONE]")
859874
.map((d) => JSON.parse(d) as Record<string, unknown>);
860-
const stopChoice = errorChunks
861-
.flatMap((c) => (c.choices as Array<Record<string, unknown>> | undefined) ?? [])
862-
.find((choice) => choice.finish_reason === "stop");
863-
expect((stopChoice?.delta as Record<string, unknown> | undefined)?.content).toBe(
864-
"Error: internal error",
875+
const allChoices = errorChunks.flatMap(
876+
(c) => (c.choices as Array<Record<string, unknown>> | undefined) ?? [],
877+
);
878+
// Error content must be in a separate chunk with finish_reason: null
879+
const errorContentChoice = allChoices.find(
880+
(choice) =>
881+
(choice.delta as Record<string, unknown> | undefined)?.content ===
882+
"Error: internal error",
865883
);
884+
expect(errorContentChoice).toBeDefined();
885+
expect(errorContentChoice).toHaveProperty("finish_reason", null);
886+
// Final stop chunk must have empty delta and finish_reason: "stop"
887+
const stopChoice = allChoices.findLast((choice) => choice.finish_reason === "stop");
888+
expect(stopChoice).toBeDefined();
889+
expect((stopChoice?.delta as Record<string, unknown> | undefined)?.content).toBeUndefined();
866890
}
867891
} finally {
868892
// shared server

‎src/gateway/openai-http.ts‎

Lines changed: 23 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -146,7 +146,7 @@ function writeAssistantRoleChunk(res: ServerResponse, params: { runId: string; m
146146

147147
function writeAssistantContentChunk(
148148
res: ServerResponse,
149-
params: { runId: string; model: string; content: string; finishReason: "stop" | null },
149+
params: { runId: string; model: string; content: string },
150150
) {
151151
writeSse(res, {
152152
id: params.runId,
@@ -157,7 +157,23 @@ function writeAssistantContentChunk(
157157
{
158158
index: 0,
159159
delta: { content: params.content },
160-
finish_reason: params.finishReason,
160+
finish_reason: null,
161+
},
162+
],
163+
});
164+
}
165+
166+
function writeAssistantFinishChunk(res: ServerResponse, params: { runId: string; model: string }) {
167+
writeSse(res, {
168+
id: params.runId,
169+
object: "chat.completion.chunk",
170+
created: Math.floor(Date.now() / 1000),
171+
model: params.model,
172+
choices: [
173+
{
174+
index: 0,
175+
delta: {},
176+
finish_reason: "stop",
161177
},
162178
],
163179
});
@@ -586,7 +602,6 @@ export async function handleOpenAiHttpRequest(
586602
runId,
587603
model,
588604
content,
589-
finishReason: null,
590605
});
591606
return;
592607
}
@@ -597,6 +612,9 @@ export async function handleOpenAiHttpRequest(
597612
closed = true;
598613
stopWatchingDisconnect();
599614
unsubscribe();
615+
if (phase === "end") {
616+
writeAssistantFinishChunk(res, { runId, model });
617+
}
600618
writeDone(res);
601619
res.end();
602620
}
@@ -629,7 +647,6 @@ export async function handleOpenAiHttpRequest(
629647
runId,
630648
model,
631649
content,
632-
finishReason: null,
633650
});
634651
}
635652
} catch (err) {
@@ -641,8 +658,8 @@ export async function handleOpenAiHttpRequest(
641658
runId,
642659
model,
643660
content: "Error: internal error",
644-
finishReason: "stop",
645661
});
662+
writeAssistantFinishChunk(res, { runId, model });
646663
emitAgentEvent({
647664
runId,
648665
stream: "lifecycle",
@@ -653,6 +670,7 @@ export async function handleOpenAiHttpRequest(
653670
closed = true;
654671
stopWatchingDisconnect();
655672
unsubscribe();
673+
writeAssistantFinishChunk(res, { runId, model });
656674
writeDone(res);
657675
res.end();
658676
}

0 commit comments

Comments
 (0)