diff --git a/apps/gateway/src/aisdk/spec.ts b/apps/gateway/src/aisdk/spec.ts index d6704ed373..d02d6581ce 100644 --- a/apps/gateway/src/aisdk/spec.ts +++ b/apps/gateway/src/aisdk/spec.ts @@ -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 diff --git a/apps/gateway/src/chat/chat.ts b/apps/gateway/src/chat/chat.ts index ba3e141ced..45d2bdcd73 100644 --- a/apps/gateway/src/chat/chat.ts +++ b/apps/gateway/src/chat/chat.ts @@ -6597,8 +6597,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, @@ -9950,9 +9949,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 @@ -10008,7 +10005,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, @@ -10028,8 +10025,7 @@ chat.openapi(completions, async (c) => { (streamingCosts.promptTokens ?? finalPromptTokens ?? 0) + (streamingCosts.completionTokens ?? finalCompletionTokens ?? - 0) + - (reasoningTokens ?? 0), + 0), ), ...(calculatedReasoningTokens !== null && calculatedReasoningTokens > 0 && { @@ -14147,7 +14143,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, @@ -14263,9 +14259,7 @@ chat.openapi(completions, async (c) => { if (promptDelta > 0) { calculatedPromptTokens = costs.promptTokens; totalTokens = ( - (calculatedPromptTokens ?? 0) + - (calculatedCompletionTokens ?? 0) + - (calculatedReasoningTokens ?? 0) + (calculatedPromptTokens ?? 0) + (calculatedCompletionTokens ?? 0) ).toString(); } } @@ -14292,8 +14286,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), calculatedReasoningTokens, cachedTokens, toolResults, diff --git a/apps/gateway/src/chat/tools/extract-token-usage.spec.ts b/apps/gateway/src/chat/tools/extract-token-usage.spec.ts index 08d9d3de8c..aa5947558f 100644 --- a/apps/gateway/src/chat/tools/extract-token-usage.spec.ts +++ b/apps/gateway/src/chat/tools/extract-token-usage.spec.ts @@ -709,12 +709,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, @@ -728,12 +728,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: { diff --git a/apps/gateway/src/chat/tools/extract-token-usage.ts b/apps/gateway/src/chat/tools/extract-token-usage.ts index e6efb1b45f..1d054fbdf3 100644 --- a/apps/gateway/src/chat/tools/extract-token-usage.ts +++ b/apps/gateway/src/chat/tools/extract-token-usage.ts @@ -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; + } + + return totalTokens === promptTokens + completionTokens + reasoningTokens + ? completionTokens + reasoningTokens + : completionTokens; +} + /** * Extracts token usage information from streaming data based on provider format */ @@ -225,7 +253,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; @@ -235,22 +266,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 @@ -296,7 +311,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). @@ -309,6 +327,13 @@ export function extractTokenUsage( break; } + completionTokens = normalizeCompletionTokens( + promptTokens, + completionTokens, + reasoningTokens, + totalTokens, + ); + return { promptTokens, completionTokens, diff --git a/apps/gateway/src/chat/tools/parse-provider-response.spec.ts b/apps/gateway/src/chat/tools/parse-provider-response.spec.ts index a1309a02ae..cd575b5871 100644 --- a/apps/gateway/src/chat/tools/parse-provider-response.spec.ts +++ b/apps/gateway/src/chat/tools/parse-provider-response.spec.ts @@ -1426,7 +1426,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: [ { @@ -1455,24 +1455,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); }); }); }); diff --git a/apps/gateway/src/chat/tools/parse-provider-response.ts b/apps/gateway/src/chat/tools/parse-provider-response.ts index 6db57825ba..353a966c71 100644 --- a/apps/gateway/src/chat/tools/parse-provider-response.ts +++ b/apps/gateway/src/chat/tools/parse-provider-response.ts @@ -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 { @@ -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; } @@ -585,7 +589,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; @@ -677,12 +684,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 @@ -1186,21 +1196,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). @@ -1292,6 +1296,13 @@ export function parseProviderResponse( reasoningContent = null; } + completionTokens = normalizeCompletionTokens( + promptTokens, + completionTokens, + reasoningTokens, + totalTokens, + ); + return { content, reasoningContent, diff --git a/apps/gateway/src/chat/tools/transform-response-to-openai.spec.ts b/apps/gateway/src/chat/tools/transform-response-to-openai.spec.ts index e995bddfcc..a6168ae76a 100644 --- a/apps/gateway/src/chat/tools/transform-response-to-openai.spec.ts +++ b/apps/gateway/src/chat/tools/transform-response-to-openai.spec.ts @@ -488,6 +488,52 @@ describe("transformResponseToOpenai", () => { expect(response.choices[1].message.content).toBe("variant 2"); }); + test("writes normalized xAI token counts to the response", () => { + const response = transformResponseToOpenai( + "xai", + "grok-4-6", + { + id: "chatcmpl-test", + object: "chat.completion", + created: 1, + model: "grok-4-6", + choices: [ + { + index: 0, + message: { role: "assistant", content: "42" }, + finish_reason: "stop", + }, + ], + usage: { + prompt_tokens: 213, + completion_tokens: 4, + total_tokens: 527, + completion_tokens_details: { reasoning_tokens: 310 }, + }, + }, + "42", + null, + "stop", + 213, + 314, + 527, + 310, + 128, + null, + [], + "xai/grok-4-6", + "xai", + "grok-4-6", + ); + + expect(response.usage).toMatchObject({ + prompt_tokens: 213, + completion_tokens: 314, + total_tokens: 527, + completion_tokens_details: { reasoning_tokens: 310 }, + }); + }); + // The OpenAI-compatible provider branches route through the same // choice-aggregating parser default as the "openai" branch above, so the // per-choice guard has to hold for them too. diff --git a/apps/gateway/src/chat/tools/transform-response-to-openai.ts b/apps/gateway/src/chat/tools/transform-response-to-openai.ts index a74c840100..73301c9a45 100644 --- a/apps/gateway/src/chat/tools/transform-response-to-openai.ts +++ b/apps/gateway/src/chat/tools/transform-response-to-openai.ts @@ -360,8 +360,7 @@ function buildUsageObject( prompt_tokens: Math.max(1, promptTokens ?? 1), completion_tokens: completionTokens ?? 0, total_tokens: (() => { - const fallbackTotal = - (promptTokens ?? 0) + (completionTokens ?? 0) + (reasoningTokens ?? 0); + const fallbackTotal = (promptTokens ?? 0) + (completionTokens ?? 0); return Math.max(1, totalTokens ?? fallbackTotal); })(), ...(reasoningTokens !== null && { @@ -1534,5 +1533,20 @@ export function transformResponseToOpenai( transformedResponse.service_tier = serviceTier; } + if ( + transformedResponse?.usage && + typeof transformedResponse.usage === "object" + ) { + if (promptTokens !== null) { + transformedResponse.usage.prompt_tokens = promptTokens; + } + if (completionTokens !== null) { + transformedResponse.usage.completion_tokens = completionTokens; + } + if (totalTokens !== null) { + transformedResponse.usage.total_tokens = totalTokens; + } + } + return transformedResponse; } diff --git a/apps/gateway/src/lib/costs.spec.ts b/apps/gateway/src/lib/costs.spec.ts index 58dffd10e7..ef73921b06 100644 --- a/apps/gateway/src/lib/costs.spec.ts +++ b/apps/gateway/src/lib/costs.spec.ts @@ -695,6 +695,24 @@ describe("calculateCosts", () => { expect(result.estimatedCost).toBe(false); }); + it("uses separately reported reasoning when completion is unavailable", async () => { + const result = await calculateCosts( + "gemini-2.5-pro", + "google-ai-studio", + null, + 1000, + null, + null, + undefined, + 200, + ); + + expect(result.outputCost).toBeCloseTo(0.002); + expect(result.totalCost).toBeCloseTo(0.00325); + expect(result.completionTokens).toBe(200); + expect(result.estimatedCost).toBe(false); + }); + it("should bill RanoAI cached tokens at the cache-read rate", async () => { // RanoAI does automatic prefix caching and charges input_cache_read // (0.05/M), half the input rate. Without cachedInputPrice the engine @@ -1682,17 +1700,16 @@ describe("calculateCosts", () => { } }); - it("matches xAI's own reported cost for grok-4-6", async () => { + it("matches xAI's own reported cost with normalized completion tokens", async () => { // Real grok-4.6 response: 213 prompt tokens (128 cached), 4 completion and // 310 reasoning tokens, billed by xAI at 21180000 usd ticks = $0.002118. - // xAI reports reasoning tokens outside completion_tokens, so they are - // billed on top of the completion count. + // Extraction normalizes the raw output to 314 inclusive completion tokens. const result = await calculateCosts( "grok-4-6", "xai", null, 213, - 4, + 314, 128, undefined, 310, @@ -1700,13 +1717,13 @@ describe("calculateCosts", () => { expect(result.totalCost).toBeCloseTo(0.002118, 9); }); - it("bills Vertex Grok 4.6 reasoning outside completion tokens", async () => { + it("bills normalized Vertex Grok 4.6 completion tokens", async () => { const result = await calculateCosts( "grok-4-6", "vertex-openai", "global", 216, - 1, + 101, 0, undefined, 100, diff --git a/apps/gateway/src/lib/costs.ts b/apps/gateway/src/lib/costs.ts index a359c2e4ba..1f9eb637cd 100644 --- a/apps/gateway/src/lib/costs.ts +++ b/apps/gateway/src/lib/costs.ts @@ -414,6 +414,11 @@ export async function calculateCosts( } } + if (completionTokens === null && reasoningTokens !== null) { + calculatedCompletionTokens = + (calculatedCompletionTokens ?? 0) + reasoningTokens; + } + // Derived from what was actually estimated, not from merely entering the // block above: a request whose prompt tokens the provider reported and whose // output estimation was declined has invented nothing, so it must not be @@ -738,39 +743,7 @@ export async function calculateCosts( .plus(imageInputCost ?? 0) .plus(audioInputCost ?? 0); - // For Google models, completionTokens already includes reasoning tokens - // (merged during extraction). The same holds for OpenAI-style Responses API - // providers (OpenAI, Azure, Sakana, Meta), whose `output_tokens` counts - // reasoning — their `reasoning_tokens` detail is informational only. RanoAI - // reports reasoning in `completion_tokens_details` (which the streaming - // transform hoists to a top-level `reasoning_tokens`) while already counting - // it inside `completion_tokens`, so adding it again would roughly double the - // billed output on reasoning requests. DeepSeek and Baidu's Qianfan report - // the same way - // (a thinking-only reply returns completion_tokens === reasoning_tokens). - // Gonka24 is the same shape without reporting any reasoning count of its own: - // its `completion_tokens` covers the `reasoning` text too, and with thinking - // on the chars-per-token ratio only matches the non-reasoning baseline once - // that text is counted. For remaining providers, add reasoning separately. - const completionIncludesReasoning = - provider === "google-ai-studio" || - provider === "glacier" || - provider === "iceberg" || - provider === "google-vertex" || - provider === "quartz" || - provider === "openai" || - provider === "azure" || - provider === "sakana" || - provider === "meta" || - provider === "deepseek" || - provider === "ranoai" || - provider === "baidu" || - provider === "permafrost" || - provider === "gonka24" || - provider === "aws-mantle"; - const totalOutputTokens = completionIncludesReasoning - ? calculatedCompletionTokens - : calculatedCompletionTokens + (reasoningTokens ?? 0); + const totalOutputTokens = calculatedCompletionTokens; // Calculate output cost, handling separate image output pricing if applicable. // Models with token-based image pricing use imageOutputTokensByResolution diff --git a/packages/models/src/models/deepseek.ts b/packages/models/src/models/deepseek.ts index 759ad6f963..99d00c8f91 100644 --- a/packages/models/src/models/deepseek.ts +++ b/packages/models/src/models/deepseek.ts @@ -842,8 +842,7 @@ export const deepseekModels = [ // Reasoning arrives as `reasoning_content` (streamed as deltas) only // when `reasoning_effort` is passed explicitly — a request without it // returns no reasoning at all, and "none" suppresses it. - // `reasoning_tokens` is reported inside completion_tokens, so costs.ts - // lists this provider in completionIncludesReasoning. + // `reasoning_tokens` is reported inside completion_tokens. // // All four tool_choice modes are honoured, so none are declared here. // The endpoint silently ignores n > 1 and returns one choice, so this diff --git a/packages/models/src/models/google.ts b/packages/models/src/models/google.ts index 83573a661e..ddcd4fa7ef 100644 --- a/packages/models/src/models/google.ts +++ b/packages/models/src/models/google.ts @@ -2521,8 +2521,7 @@ export const googleModels = [ // arrives as `reasoning_content` (streamed as deltas) only when // `reasoning_effort` is passed explicitly — a request without it // returns no reasoning at all, and "none" suppresses it. - // `reasoning_tokens` is reported inside completion_tokens, so - // costs.ts lists this provider in completionIncludesReasoning. + // `reasoning_tokens` is reported inside completion_tokens. // // All four tool_choice modes are honoured, so none are declared // here. Prompt caching is automatic prefix caching — the first