Skip to content

fix(openai): report cached tokens disjoint from input_tokens - #303

Merged
mlikasam-askui merged 1 commit into
mainfrom
fix/openai-usage-cached-tokens
Jul 31, 2026
Merged

fix(openai): report cached tokens disjoint from input_tokens#303
mlikasam-askui merged 1 commit into
mainfrom
fix/openai-usage-cached-tokens

Conversation

@mlikasam-askui

Copy link
Copy Markdown
Contributor

Summary

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. 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_tokens at the response boundary (_from_openai_response), so UsageParam means the same thing on every route:

  • input_tokens = uncached prompt tokens only
  • cache_read_input_tokens = cached prompt tokens

The subtraction is guarded so absent or malformed prompt_tokens_details pass through unchanged, and input_tokens is clamped to never go negative.

Test plan

  • New unit test: cached tokens are subtracted from input_tokens (1000 prompt / 400 cached → 600 input, 400 cache read)
  • New unit test: input_tokens never goes negative when reported cached_tokens exceeds prompt_tokens
  • All 35 tests in tests/unit/models/openai/test_messages_api.py pass

🤖 Generated with Claude Code

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.
@mlikasam-askui mlikasam-askui self-assigned this Jul 31, 2026
@mlikasam-askui
mlikasam-askui merged commit c7e094b into main Jul 31, 2026
1 check passed
@mlikasam-askui
mlikasam-askui deleted the fix/openai-usage-cached-tokens branch July 31, 2026 13:31
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants