Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 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
2 changes: 1 addition & 1 deletion apps/gateway/src/aisdk/spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,7 @@ export function buildUsage(
outputTokens: {
total: tokens.outputTokens,
// The reasoning token count is already part of the output total for
// every provider we bill (see costs.ts); `text` is the remainder.
// every provider after usage normalization; `text` is the remainder.
text:
tokens.outputTokens === undefined
? undefined
Expand Down
21 changes: 7 additions & 14 deletions apps/gateway/src/chat/chat.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6598,8 +6598,7 @@ chat.openapi(completions, async (c) => {
totalTokens: costs.imageInputTokens
? (
(costs.promptTokens ?? promptTokens ?? 0) +
(completionTokens ?? 0) +
(reasoningTokens ?? 0)
(completionTokens ?? 0)
).toString()
: (totalTokens?.toString() ?? null),
reasoningTokens: reasoningTokens?.toString() ?? null,
Expand Down Expand Up @@ -9952,9 +9951,7 @@ chat.openapi(completions, async (c) => {

if (finalTotalTokens === null) {
finalTotalTokens =
(finalPromptTokens ?? 0) +
(finalCompletionTokens ?? 0) +
(reasoningTokens ?? 0);
(finalPromptTokens ?? 0) + (finalCompletionTokens ?? 0);
}

// Send final usage chunk before [DONE] if we have any usage data
Expand Down Expand Up @@ -10010,7 +10007,7 @@ chat.openapi(completions, async (c) => {

// Approximate reasoning tokens when the provider streamed
// reasoning content but no count (e.g. AWS Bedrock).
// Display only — totals/costs keep the raw reasoningTokens.
// Display only — totals and costs use completionTokens.
const calculatedReasoningTokens = resolveReasoningTokens(
reasoningTokens,
fullReasoningContent,
Expand All @@ -10030,8 +10027,7 @@ chat.openapi(completions, async (c) => {
(streamingCosts.promptTokens ?? finalPromptTokens ?? 0) +
(streamingCosts.completionTokens ??
finalCompletionTokens ??
0) +
(reasoningTokens ?? 0),
0),
),
...(calculatedReasoningTokens !== null &&
calculatedReasoningTokens > 0 && {
Expand Down Expand Up @@ -14161,7 +14157,7 @@ chat.openapi(completions, async (c) => {

// Approximate reasoning tokens when the provider returned reasoning content
// but no count (e.g. AWS Bedrock). Display/logging only — never fed into
// calculateCosts below, which keeps the raw reasoningTokens.
// calculateCosts below, which uses the inclusive completion token count.
const calculatedReasoningTokens = resolveReasoningTokens(
reasoningTokens,
reasoningContent,
Expand Down Expand Up @@ -14277,9 +14273,7 @@ chat.openapi(completions, async (c) => {
if (promptDelta > 0) {
calculatedPromptTokens = costs.promptTokens;
totalTokens = (
(calculatedPromptTokens ?? 0) +
(calculatedCompletionTokens ?? 0) +
(calculatedReasoningTokens ?? 0)
(calculatedPromptTokens ?? 0) + (calculatedCompletionTokens ?? 0)
).toString();
}
}
Expand All @@ -14306,8 +14300,7 @@ chat.openapi(completions, async (c) => {
costs.promptTokens ?? calculatedPromptTokens,
costs.completionTokens ?? calculatedCompletionTokens,
(costs.promptTokens ?? calculatedPromptTokens ?? 0) +
(costs.completionTokens ?? calculatedCompletionTokens ?? 0) +
(reasoningTokens ?? 0),
(costs.completionTokens ?? calculatedCompletionTokens ?? 0),
Comment on lines 14288 to +14289

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Update the E2E invariant for inclusive completion tokens

When EXPERIMENTAL is enabled and an upstream response reports positive reasoning tokens, this now returns total_tokens = prompt_tokens + completion_tokens, but apps/gateway/src/chat-basic.e2e.ts:161-165 still asserts that reasoning_tokens must be added again. Any reasoning-capable model exercised by that suite will therefore fail even though completion_tokens has intentionally become inclusive; update the existing assertion as part of this semantic change.

Useful? React with 👍 / 👎.

calculatedReasoningTokens,
cachedTokens,
toolResults,
Expand Down
26 changes: 22 additions & 4 deletions apps/gateway/src/chat/tools/extract-token-usage.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -686,12 +686,12 @@ describe("extractTokenUsage", () => {

describe("xai-style reasoning usage", () => {
it.each(["xai", "vertex-openai"] as const)(
"reads reasoning tokens from completion_tokens_details for %s",
"normalizes separately reported reasoning for %s",
(provider) => {
// Real grok-4.6 usage payload. xAI reports reasoning only in the nested
// details object and leaves it OUT of completion_tokens — note
// total_tokens = 213 + 4 + 310 — so it has to be picked up here or the
// cost engine bills the 4 visible output tokens and nothing else.
// total_tokens = 213 + 4 + 310. Extraction makes the output count
// inclusive before it reaches billing.
const data = {
usage: {
prompt_tokens: 213,
Expand All @@ -705,12 +705,30 @@ describe("extractTokenUsage", () => {
const result = extractTokenUsage(data, provider);

expect(result.promptTokens).toBe(213);
expect(result.completionTokens).toBe(4);
expect(result.completionTokens).toBe(314);
expect(result.reasoningTokens).toBe(310);
expect(result.totalTokens).toBe(527);
expect(result.cachedTokens).toBe(128);
},
);

it("keeps an inclusive completion count unchanged", () => {
const result = extractTokenUsage(
{
usage: {
prompt_tokens: 213,
completion_tokens: 314,
total_tokens: 527,
completion_tokens_details: { reasoning_tokens: 310 },
},
},
"openai",
);

expect(result.completionTokens).toBe(314);
expect(result.reasoningTokens).toBe(310);
});

it("returns null reasoning tokens for a non-reasoning response", () => {
const data = {
usage: {
Expand Down
61 changes: 43 additions & 18 deletions apps/gateway/src/chat/tools/extract-token-usage.ts
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,34 @@ export function extractBedrockCacheCreationDetails(usage: any): {
};
}

/**
* Normalize completion tokens to the inclusive billable output count.
*
* Most providers already include reasoning in completion tokens. A few return
* visible completion and reasoning separately, which is unambiguous when the
* reported total equals prompt + completion + reasoning.
*/
export function normalizeCompletionTokens(
promptTokens: number | null,
completionTokens: number | null,
reasoningTokens: number | null,
totalTokens: number | null,
): number | null {
if (
promptTokens === null ||
completionTokens === null ||
reasoningTokens === null ||
reasoningTokens <= 0 ||
totalTokens === null
) {
return completionTokens;
Comment on lines +77 to +79

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Preserve separate reasoning when total is absent

When an xAI-style response reports completion_tokens and separate reasoning_tokens but omits total_tokens, this returns the exclusive completion count unchanged; the non-streaming parser similarly synthesizes prompt + completion before calling this helper, so the equality check also fails there. Since calculateCosts now ignores its reasoning-token argument, such responses underbill output tokens and expose incorrect completion/total usage; retain a provider-aware fallback for known separate-reporting formats when the total is unavailable.

Useful? React with 👍 / 👎.

}

return totalTokens === promptTokens + completionTokens + reasoningTokens
? completionTokens + reasoningTokens
: completionTokens;
}

/**
* Extracts token usage information from streaming data based on provider format
*/
Expand Down Expand Up @@ -224,7 +252,10 @@ export function extractTokenUsage(
promptTokens = data.usage.prompt_tokens ?? null;
completionTokens = data.usage.completion_tokens ?? null;
totalTokens = data.usage.total_tokens ?? null;
reasoningTokens = data.usage.reasoning_tokens ?? null;
reasoningTokens =
data.usage.reasoning_tokens ??
data.usage.completion_tokens_details?.reasoning_tokens ??
null;
cachedTokens = data.usage.prompt_tokens_details?.cached_tokens ?? null;
const cacheCreation =
data.usage.prompt_tokens_details?.cache_creation_input_tokens ?? 0;
Expand All @@ -234,22 +265,6 @@ export function extractTokenUsage(
}
}
break;
case "xai":
case "vertex-openai":
// xAI and Vertex's xAI endpoint report reasoning outside
// `completion_tokens`, so the nested count has to reach the cost engine
// to be billed. The default OpenAI branch only reads a top-level count.
if (data.usage) {
promptTokens = data.usage.prompt_tokens ?? null;
completionTokens = data.usage.completion_tokens ?? null;
totalTokens = data.usage.total_tokens ?? null;
reasoningTokens =
data.usage.completion_tokens_details?.reasoning_tokens ??
data.usage.reasoning_tokens ??
null;
cachedTokens = data.usage.prompt_tokens_details?.cached_tokens ?? null;
}
break;
case "sakana":
// Fugu streams over Chat Completions and bills the orchestration tokens
// consumed by its underlying agent pool on top of the user-visible
Expand Down Expand Up @@ -295,7 +310,10 @@ export function extractTokenUsage(
promptTokens = data.usage.prompt_tokens ?? null;
completionTokens = data.usage.completion_tokens ?? null;
totalTokens = data.usage.total_tokens ?? null;
reasoningTokens = data.usage.reasoning_tokens ?? null;
reasoningTokens =
data.usage.reasoning_tokens ??
data.usage.completion_tokens_details?.reasoning_tokens ??
null;
cachedTokens = data.usage.prompt_tokens_details?.cached_tokens ?? null;
// GPT-5.6+ bills prompt-cache writes at 1.25x and reports them in
// `cache_write_tokens` (a subset of prompt_tokens, like cached_tokens).
Expand All @@ -308,6 +326,13 @@ export function extractTokenUsage(
break;
}

completionTokens = normalizeCompletionTokens(
promptTokens,
completionTokens,
reasoningTokens,
totalTokens,
);

return {
promptTokens,
completionTokens,
Expand Down
20 changes: 13 additions & 7 deletions apps/gateway/src/chat/tools/parse-provider-response.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1356,7 +1356,7 @@ describe("parseProviderResponse", () => {
describe("xai reasoning tokens", () => {
// Real grok-4.6 usage payload: reasoning is reported only in the nested
// details object and is NOT part of completion_tokens (note total_tokens =
// 213 + 4 + 310), so it has to be read here to be billed at all.
// 213 + 4 + 310). Parsing normalizes completion to the inclusive count.
const xaiJson = {
choices: [
{
Expand Down Expand Up @@ -1385,24 +1385,30 @@ describe("parseProviderResponse", () => {
);

expect(result.promptTokens).toBe(213);
expect(result.completionTokens).toBe(4);
expect(result.completionTokens).toBe(314);
expect(result.reasoningTokens).toBe(310);
expect(result.cachedTokens).toBe(128);
},
);

it("ignores the nested count for other OpenAI-compatible providers", () => {
// Everyone else folds reasoning into completion_tokens already, so
// reading the nested field would bill the same tokens twice.
it("keeps inclusive OpenAI-compatible completion tokens unchanged", () => {
const inclusiveJson = {
...xaiJson,
usage: {
...xaiJson.usage,
completion_tokens: 314,
},
};
const result = parseProviderResponse(
"openai",
"gpt-5.5",
xaiJson,
inclusiveJson,
[],
true,
);

expect(result.reasoningTokens).toBeNull();
expect(result.completionTokens).toBe(314);
expect(result.reasoningTokens).toBe(310);
});
});
});
39 changes: 25 additions & 14 deletions apps/gateway/src/chat/tools/parse-provider-response.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import { estimateTokens } from "./estimate-tokens.js";
import {
adjustGoogleCandidateTokens,
extractBedrockCacheCreationDetails,
normalizeCompletionTokens,
} from "./extract-token-usage.js";
import { dedupeGoogleCandidateParts } from "./google-candidates.js";
import {
Expand Down Expand Up @@ -110,12 +111,15 @@ export function parseProviderResponse(
finishReason = allChoices[0]?.finish_reason ?? null;
promptTokens = json.usage?.prompt_tokens ?? null;
completionTokens = json.usage?.completion_tokens ?? null;
reasoningTokens = json.usage?.reasoning_tokens ?? null;
reasoningTokens =
json.usage?.reasoning_tokens ??
json.usage?.completion_tokens_details?.reasoning_tokens ??
null;
cachedTokens = json.usage?.prompt_tokens_details?.cached_tokens ?? null;
totalTokens =
json.usage?.total_tokens ??
(promptTokens !== null && completionTokens !== null
? promptTokens + completionTokens + (reasoningTokens ?? 0)
? promptTokens + completionTokens
: null);
break;
}
Expand Down Expand Up @@ -584,7 +588,10 @@ export function parseProviderResponse(
finishReason = json.choices?.[0]?.finish_reason ?? null;
promptTokens = json.usage?.prompt_tokens ?? null;
completionTokens = json.usage?.completion_tokens ?? null;
reasoningTokens = json.usage?.reasoning_tokens ?? null;
reasoningTokens =
json.usage?.reasoning_tokens ??
json.usage?.completion_tokens_details?.reasoning_tokens ??
null;
cachedTokens = json.usage?.prompt_tokens_details?.cached_tokens ?? null;
totalTokens = json.usage?.total_tokens ?? null;

Expand Down Expand Up @@ -676,12 +683,15 @@ export function parseProviderResponse(
finishReason = json.choices?.[0]?.finish_reason ?? null;
promptTokens = json.usage?.prompt_tokens ?? null;
completionTokens = json.usage?.completion_tokens ?? null;
reasoningTokens = json.usage?.reasoning_tokens ?? null;
reasoningTokens =
json.usage?.reasoning_tokens ??
json.usage?.completion_tokens_details?.reasoning_tokens ??
null;
cachedTokens = json.usage?.prompt_tokens_details?.cached_tokens ?? null;
totalTokens =
json.usage?.total_tokens ??
(promptTokens !== null && completionTokens !== null
? promptTokens + completionTokens + (reasoningTokens ?? 0)
? promptTokens + completionTokens
: null);
// Alibaba uses Anthropic-style `cache_control: {type: "ephemeral"}` on
// the request, but reports usage in OpenAI shape with
Expand Down Expand Up @@ -1163,21 +1173,15 @@ export function parseProviderResponse(
// Standard OpenAI-style token parsing
promptTokens = json.usage?.prompt_tokens ?? null;
completionTokens = json.usage?.completion_tokens ?? null;
// xAI and Vertex's xAI endpoint report reasoning outside
// `completion_tokens` and only expose the count in the nested details.
// Reading it here is what makes reasoning billable at all. Providers
// that fold reasoning into `completion_tokens` must keep reading the
// top-level field only, or the same tokens would be billed twice.
reasoningTokens =
json.usage?.reasoning_tokens ??
(usedProvider === "xai" || usedProvider === "vertex-openai"
? (json.usage?.completion_tokens_details?.reasoning_tokens ?? null)
: null);
json.usage?.completion_tokens_details?.reasoning_tokens ??
null;
cachedTokens = json.usage?.prompt_tokens_details?.cached_tokens ?? null;
totalTokens =
json.usage?.total_tokens ??
(promptTokens !== null && completionTokens !== null
? promptTokens + completionTokens + (reasoningTokens ?? 0)
? promptTokens + completionTokens
: null);
// GPT-5.6+ bills prompt-cache writes at 1.25x and reports them in
// `cache_write_tokens` (a subset of prompt_tokens, like cached_tokens).
Expand Down Expand Up @@ -1269,6 +1273,13 @@ export function parseProviderResponse(
reasoningContent = null;
}

completionTokens = normalizeCompletionTokens(
promptTokens,
completionTokens,
reasoningTokens,
totalTokens,
);

return {
content,
reasoningContent,
Expand Down
Loading
Loading