fix(openai-adapters): Use stream.usage Promise exclusively for usage tokens

The Vercel AI SDK's fullStream finish event contains preliminary/incomplete
usage data (often zeros). The authoritative usage is ONLY available via the
stream.usage Promise which resolves after the stream completes.

Changes:
- convertVercelStream: Skip finish event entirely (return null)
- OpenAI.ts: Always await stream.usage after consuming fullStream
- Anthropic.ts: Same approach with cache token support
- Tests: Updated to reflect that finish event doesn't emit usage

This is the correct architecture per Vercel AI SDK design:
- fullStream: Stream events (text, tools, etc) - finish has no reliable usage
- stream.usage: Promise that resolves with complete usage after stream ends

Co-authored-by: nate <nate@continue.dev>
Generated with [Continue](https://continue.dev)
This commit is contained in:
continue[bot] 2025-12-10 19:54:10 +00:00
parent 6e656f9a2e
commit df143e7f27
4 changed files with 62 additions and 117 deletions

View file

@ -665,50 +665,44 @@ export class AnthropicApi implements BaseLlmApi {
});
// Convert Vercel AI SDK stream to OpenAI format
let hasEmittedUsage = false;
for await (const chunk of convertVercelStream(stream.fullStream as any, {
model: body.model,
})) {
if (chunk.usage) {
hasEmittedUsage = true;
}
yield chunk;
}
// Fallback: If fullStream didn't emit usage, get it from stream.usage Promise
if (!hasEmittedUsage) {
const finalUsage = await stream.usage;
if (finalUsage) {
const { usageChatChunk } = await import("../util.js");
const promptTokens =
typeof finalUsage.promptTokens === "number"
? finalUsage.promptTokens
: 0;
const completionTokens =
typeof finalUsage.completionTokens === "number"
? finalUsage.completionTokens
: 0;
const totalTokens =
typeof finalUsage.totalTokens === "number"
? finalUsage.totalTokens
: promptTokens + completionTokens;
// Get final usage from stream.usage Promise (finish event has incomplete data)
const finalUsage = await stream.usage;
if (finalUsage) {
const { usageChatChunk } = await import("../util.js");
const promptTokens =
typeof finalUsage.promptTokens === "number"
? finalUsage.promptTokens
: 0;
const completionTokens =
typeof finalUsage.completionTokens === "number"
? finalUsage.completionTokens
: 0;
const totalTokens =
typeof finalUsage.totalTokens === "number"
? finalUsage.totalTokens
: promptTokens + completionTokens;
yield usageChatChunk({
model: body.model,
usage: {
prompt_tokens: promptTokens,
completion_tokens: completionTokens,
total_tokens: totalTokens,
prompt_tokens_details: {
cached_tokens:
(finalUsage as any).promptTokensDetails?.cachedTokens ?? 0,
cache_read_tokens:
(finalUsage as any).promptTokensDetails?.cachedTokens ?? 0,
cache_write_tokens: 0,
} as any,
},
});
}
yield usageChatChunk({
model: body.model,
usage: {
prompt_tokens: promptTokens,
completion_tokens: completionTokens,
total_tokens: totalTokens,
prompt_tokens_details: {
cached_tokens:
(finalUsage as any).promptTokensDetails?.cachedTokens ?? 0,
cache_read_tokens:
(finalUsage as any).promptTokensDetails?.cachedTokens ?? 0,
cache_write_tokens: 0,
} as any,
},
});
}
}

View file

@ -334,42 +334,36 @@ export class OpenAIApi implements BaseLlmApi {
});
// Convert Vercel AI SDK stream to OpenAI format
let hasEmittedUsage = false;
for await (const chunk of convertVercelStream(stream.fullStream as any, {
model: modifiedBody.model,
})) {
if (chunk.usage) {
hasEmittedUsage = true;
}
yield chunk;
}
// Fallback: If fullStream didn't emit usage, get it from stream.usage Promise
if (!hasEmittedUsage) {
const finalUsage = await stream.usage;
if (finalUsage) {
const promptTokens =
typeof finalUsage.promptTokens === "number"
? finalUsage.promptTokens
: 0;
const completionTokens =
typeof finalUsage.completionTokens === "number"
? finalUsage.completionTokens
: 0;
const totalTokens =
typeof finalUsage.totalTokens === "number"
? finalUsage.totalTokens
: promptTokens + completionTokens;
// Get final usage from stream.usage Promise (finish event has incomplete data)
const finalUsage = await stream.usage;
if (finalUsage) {
const promptTokens =
typeof finalUsage.promptTokens === "number"
? finalUsage.promptTokens
: 0;
const completionTokens =
typeof finalUsage.completionTokens === "number"
? finalUsage.completionTokens
: 0;
const totalTokens =
typeof finalUsage.totalTokens === "number"
? finalUsage.totalTokens
: promptTokens + completionTokens;
yield usageChatChunk({
model: modifiedBody.model,
usage: {
prompt_tokens: promptTokens,
completion_tokens: completionTokens,
total_tokens: totalTokens,
},
});
}
yield usageChatChunk({
model: modifiedBody.model,
usage: {
prompt_tokens: promptTokens,
completion_tokens: completionTokens,
total_tokens: totalTokens,
},
});
}
}
async completionNonStream(

View file

@ -78,7 +78,7 @@ describe("convertVercelStreamPart", () => {
});
});
test("converts finish to usage chunk", () => {
test("finish event returns null (usage comes from stream.usage Promise)", () => {
const part: VercelStreamPart = {
type: "finish",
finishReason: "stop",
@ -91,12 +91,8 @@ describe("convertVercelStreamPart", () => {
const result = convertVercelStreamPart(part, options);
expect(result).not.toBeNull();
expect(result?.usage).toEqual({
prompt_tokens: 100,
completion_tokens: 50,
total_tokens: 150,
});
// Finish event should not emit usage - caller will use stream.usage Promise
expect(result).toBeNull();
});
test("throws error for error event", () => {
@ -250,16 +246,15 @@ describe("convertVercelStream", () => {
chunks.push(chunk);
}
// Should only get chunks for: text-delta (2), tool-call (1), finish (1) = 4 chunks
// step-start and step-finish are filtered out
expect(chunks).toHaveLength(4);
// Should only get chunks for: text-delta (2), tool-call (1) = 3 chunks
// step-start, step-finish, and finish are filtered out (finish usage comes from stream.usage Promise)
expect(chunks).toHaveLength(3);
expect(chunks[0].choices[0].delta.content).toBe("Hello ");
expect(chunks[1].choices[0].delta.content).toBe("world");
expect(chunks[2].choices[0].delta.tool_calls?.[0].function?.name).toBe(
"test",
);
expect(chunks[3].usage).toBeDefined();
});
test("throws error when stream contains error event", async () => {

View file

@ -121,46 +121,8 @@ export function convertVercelStreamPart(
});
case "finish":
// Emit usage chunk at the end if usage data is present
if (part.usage) {
const promptTokens =
typeof part.usage.promptTokens === "number"
? part.usage.promptTokens
: 0;
const completionTokens =
typeof part.usage.completionTokens === "number"
? part.usage.completionTokens
: 0;
const totalTokens =
typeof part.usage.totalTokens === "number"
? part.usage.totalTokens
: promptTokens + completionTokens;
// Check for Anthropic-specific cache token details
const promptTokensDetails =
(part.usage as any).promptTokensDetails?.cachedTokens !== undefined
? {
cached_tokens:
(part.usage as any).promptTokensDetails.cachedTokens ?? 0,
cache_read_tokens:
(part.usage as any).promptTokensDetails.cachedTokens ?? 0,
cache_write_tokens: 0,
}
: undefined;
return usageChatChunk({
model,
usage: {
prompt_tokens: promptTokens,
completion_tokens: completionTokens,
total_tokens: totalTokens,
...(promptTokensDetails
? { prompt_tokens_details: promptTokensDetails as any }
: {}),
},
});
}
// If no usage data in finish event, return null
// Don't emit usage from finish event - it may have incomplete/preliminary data
// Caller will use stream.usage Promise which has the final accurate usage
return null;
case "error":