Skip to content

Fix Anthropic usage double-counting cache in input - #617

Open
elrensmin wants to merge 1 commit into
huggingface:mainfrom
elrensmin:fix/anthropic-usage-fresh-input
Open

Fix Anthropic usage double-counting cache in input#617
elrensmin wants to merge 1 commit into
huggingface:mainfrom
elrensmin:fix/anthropic-usage-fresh-input

Conversation

@elrensmin

Copy link
Copy Markdown

Problem

Anthropic's message_start/message_delta stored input_tokens verbatim, but Anthropic's input_tokens already includes cache reads+writes. total_tokens was then recomputed as input+output+cache_read+cache_write, double-counting cache (e.g. input=100, cache_read=40, cache_write=25 → total=172). Every OpenAI-family path (openai_compatible, openai_codex) instead stores fresh input = max(0, input - cache_read - cache_write). Downstream consumers (session_stats.py:83, session_usage.py, context_window.py:183, _response_cost) all assume the fresh convention, so Anthropic silently over-reported stats and overcharged cost.

Fix

store fresh input in both _usage_from_message_start and _apply_message_delta_usage, matching the OpenAI convention; total_tokens computed from fresh input.

Tests

test_tau_ai.py updated to the corrected numbers (input 100→35, total 172→107); test_session_stats.py already encodes the correct convention, unchanged.

Validation

uv run pytest tests/test_tau_ai.py tests/test_session_stats.py (89 passed).

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.

1 participant