Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 24 additions & 0 deletions extensions/ext-llm-openai/src/openai-chat-stream.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -407,6 +407,30 @@ describe("ext-llm-openai/openai-chat-stream", () => {
);
});

it("accepts repeated post-finish usage events without double counting", async () => {
// OpenAI's include_usage chunk uses `choices: []`; aggregators add a bare
// `{usage}`. Repeated cumulative totals must merge, not accumulate.
const usage = { prompt_tokens: 100, completion_tokens: 20, total_tokens: 120 };
const finish = data({ choices: [{ delta: {}, finish_reason: "stop" }] });
const emptyChoices = data({ choices: [], usage });
const bare = data({ usage });

for (
const tail of [[emptyChoices, emptyChoices], [emptyChoices, bare], [bare, bare]]
) {
assertEquals(
await collectParts(
streamFromText([finish, ...tail, "data: [DONE]\r\n\r\n"].join("")),
),
[{
type: "finish",
finishReason: "stop",
usage: { inputTokens: 100, outputTokens: 20, totalTokens: 120 },
}],
);
}
});

it("rejects structurally empty and unterminated successful streams", async () => {
await assertRejects(
() => collectParts(streamFromText(data({}))),
Expand Down
13 changes: 0 additions & 13 deletions extensions/ext-llm-openai/src/openai-chat-stream.ts
Original file line number Diff line number Diff line change
Expand Up @@ -226,7 +226,6 @@ export async function* streamOpenAICompatibleParts(
let sawChoiceEnvelope = false;
let sawFinishReason = false;
let sawDone = false;
let sawPostFinishUsage = false;
const toolArgumentBudget: OpenAIStreamToolArgumentBudget = {
bytes: 0,
fragments: 0,
Expand Down Expand Up @@ -258,12 +257,6 @@ export async function* streamOpenAICompatibleParts(
if (!usageRecord) {
throw invalidOpenAIStream(context, "event had neither choices nor usage");
}
if (sawFinishReason) {
if (sawPostFinishUsage) {
throw invalidOpenAIStream(context, "stream contained multiple post-finish usage events");
}
sawPostFinishUsage = true;
}
return;
}
if (!Array.isArray(record.choices)) {
Expand All @@ -273,12 +266,6 @@ export async function* streamOpenAICompatibleParts(
if (!usageRecord) {
throw invalidOpenAIStream(context, "empty choices event had no usage");
}
if (sawFinishReason) {
if (sawPostFinishUsage) {
throw invalidOpenAIStream(context, "stream contained multiple post-finish usage events");
}
sawPostFinishUsage = true;
}
return;
}
if (sawFinishReason) {
Expand Down