fix(openai): report cached tokens disjoint from input_tokens - #303
Merged
Conversation
OpenAI-style usage counts prompt_tokens_details.cached_tokens INSIDE prompt_tokens, while UsageParam consumers (conversation statistics callback, HTML reporting) treat the fields as disjoint, Anthropic-style — so cached tokens were counted and billed twice for OpenAI-route models (observed ~5x cost overstatement on cache-heavy Gemini agentic runs). Subtract the cached subset at the response boundary so UsageParam means the same thing on every route. Guarded so absent/malformed details pass through unchanged.
philipph-askui
approved these changes
Jul 31, 2026
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
OpenAI-style usage counts
prompt_tokens_details.cached_tokensinsideprompt_tokens, whileUsageParamconsumers (conversation statistics callback, HTML reporting) treat the fields as disjoint, Anthropic-style. As a result, cached tokens were counted and billed twice for OpenAI-route models — observed as a ~5x cost overstatement on cache-heavy Gemini agentic runs.This PR subtracts the cached subset from
input_tokensat the response boundary (_from_openai_response), soUsageParammeans the same thing on every route:input_tokens= uncached prompt tokens onlycache_read_input_tokens= cached prompt tokensThe subtraction is guarded so absent or malformed
prompt_tokens_detailspass through unchanged, andinput_tokensis clamped to never go negative.Test plan
input_tokens(1000 prompt / 400 cached → 600 input, 400 cache read)input_tokensnever goes negative when reportedcached_tokensexceedsprompt_tokenstests/unit/models/openai/test_messages_api.pypass🤖 Generated with Claude Code