Repository navigation
fix(anthropic): bill streaming 1h prompt-cache writes at the 1h rate - #32073
mateo-berri merged 3 commits into
Conversation
…ming usage chunks Anthropic emits the cache-creation TTL breakdown (ephemeral 5m/1h split) only on the message_start SSE event; the later message_delta carries the flat cache_creation_input_tokens count but drops the nested cache_creation object. ChunkProcessor aggregates prompt_tokens_details last-wins, so message_delta's details (with cache_creation_token_details=None) clobbered the breakdown captured from message_start. Cost calc then fell into the flat-rate branch of calculate_cache_writing_cost and billed 1-hour cache writes at the 5-minute rate, undercounting the cache-creation cost component by ~37.5% on streaming requests. Track cache_creation_token_details with the same non-null-wins semantics already used for the flat cache counts and stitch it back onto the final prompt_tokens_details when the last chunk lacks it. Non-streaming was unaffected because its usage is parsed once from the full response body.
|
Generated by Claude Code |
Greptile SummaryFixes under-billing of Anthropic 1-hour ephemeral prompt-cache writes on streaming responses by preserving the
Confidence Score: 5/5Safe to merge; the change is narrowly scoped to streaming usage aggregation, is fully covered by new regression tests, and does not touch non-streaming paths or any auth/routing logic. The fix correctly applies non-null-wins semantics to No files require special attention.
|
| Filename | Overview |
|---|---|
| litellm/litellm_core_utils/streaming_chunk_builder_utils.py | Adds two static helpers to track and reattach cache_creation_token_details across streaming chunks using non-null-wins semantics, fixing 1h prompt-cache writes being billed at the 5m rate on streaming responses. |
| tests/test_litellm/litellm_core_utils/test_streaming_chunk_builder_utils.py | Adds two regression tests: one for the primary bug (start chunk has breakdown, delta drops it), including an end-to-end cost assertion; one for the case where the final chunk itself carries the breakdown. |
Reviews (4): Last reviewed commit: "test(streaming): cover final-chunk cache..." | Re-trigger Greptile
Greptile SummaryFixes a streaming cost-calculation bug where Anthropic's 1-hour prompt-cache write rate was incorrectly billed at the 5-minute rate (~37.5% undercount). The root cause was that the
Confidence Score: 4/5The change is a safe, targeted addition to the streaming chunk aggregator — it only runs the new stitching logic when the last chunk's The fix is mechanically correct: No files require special attention; both changed files are self-contained and well-covered by the new test.
|
| Filename | Overview |
|---|---|
| litellm/litellm_core_utils/streaming_chunk_builder_utils.py | Adds a separate cache_creation_token_details accumulator with non-null-wins semantics to preserve Anthropic's 1h/5m cache-write breakdown across streaming chunks; post-loop stitching restores the breakdown onto the final prompt_tokens_details when the last chunk lacks it — correctly fixing the 1h-billed-at-5m-rate regression without changing any other aggregation behavior. |
| tests/test_litellm/litellm_core_utils/test_streaming_chunk_builder_utils.py | Adds test_streaming_preserves_anthropic_1hr_cache_creation_breakdown, a mock-only regression test that feeds the real two-event Anthropic usage shapes through calculate_usage, asserts the 1h breakdown is preserved in prompt_tokens_details, and verifies the correct write-rate cost; no network calls made. |
Reviews (2): Last reviewed commit: "fix(anthropic): preserve 1h cache-creati..." | Re-trigger Greptile
Codecov Report✅ All modified and coverable lines are covered by tests. 📢 Thoughts on this report? Let us know! |
… within strict complexity budget
|
Generated by Claude Code |
|
bugbot run Generated by Claude Code |
There was a problem hiding this comment.
✅ Bugbot reviewed your changes and found no new issues!
Comment @cursor review or bugbot run to trigger another review on this PR
Reviewed by Cursor Bugbot for commit 1b31afd. Configure here.
|
Generated by Claude Code |
|
bugbot run Generated by Claude Code |
There was a problem hiding this comment.
✅ Bugbot reviewed your changes and found no new issues!
Comment @cursor review or bugbot run to trigger another review on this PR
Reviewed by Cursor Bugbot for commit b8e2265. Configure here.
Relevant issues
Copy of #31724 by @rich-warbo, moved to an internal
litellm_branch so CircleCI can run on it. The commit preserves the original author's authorship; all credit to themLinear ticket
Pre-Submission checklist
Please complete all items before asking a LiteLLM maintainer to review your PR
@greptileaiand received a Confidence Score of at least 4/5 before requesting a maintainer reviewScreenshots / Proof of Fix
From the original PR: live streaming request through a local proxy against the real Anthropic API (claude-sonnet-4-6), writing a system block to the 1-hour ephemeral cache
Request:
Final streamed usage (note the preserved 1h breakdown):
Computed cost (proxy detailed_debug log):
This matches the 1-hour write rate: cache creation 4803 * 6e-06 = 0.028818, plus input 15 * 3e-06 = 0.000045, plus output 47 * 1.5e-05 = 0.000705, total 0.029568. Before the fix the streaming aggregator dropped cache_creation_token_details, so the same write was billed at the 5-minute rate (4803 * 3.75e-06 = 0.01801125) for a total of 0.01876125, undercounting the cache-creation component by ~37.5%
Type
🐛 Bug Fix
Changes
Anthropic sends the cache-creation TTL breakdown (the ephemeral 5m/1h split,
usage.cache_creation) only on the streamingmessage_startevent; the latermessage_deltacarries the flatcache_creation_input_tokenscount but drops the nested object.ChunkProcessor._calculate_usage_per_chunkaggregatesprompt_tokens_detailslast-wins, somessage_delta's details (withcache_creation_token_details=None) overwrote the breakdown captured frommessage_start. Cost calc then took the flat-rate branch ofcalculate_cache_writing_costand billed 1-hour cache writes at the 5-minute rate, undercounting the cache-creation cost component by about 37.5% on streaming requests. Non-streaming was unaffected because its usage is parsed once from the full response bodyThis tracks
cache_creation_token_detailsacross chunks with the same non-null-wins semantics already used for the flat cache counts, then stitches it back onto the finalprompt_tokens_detailswhen the last chunk lacks it. The capture and stitch steps live in two small static helpers (_capture_cache_creation_token_details,_attach_cache_creation_token_details) so_calculate_usage_per_chunkstays within the strict C901 complexity budget enforced by the lint gate. A regression test feeds the real two-event Anthropic usage shapes throughcalculate_usageand asserts the 1h write rate is applied; it fails on the pre-fix code and passes after. A second test pins the other stitch branch: when the final chunk itself carries the breakdown, aggregation keeps it instead of re-attaching a stale earlier captureNote
Medium Risk
Touches streaming usage aggregation and billing-related token metadata; scope is narrow helpers plus tests, but incorrect stitching could still misreport costs or usage on Anthropic streams.
Overview
Fixes under-billing of Anthropic streaming prompt-cache writes when tokens use the 1-hour ephemeral TTL. Anthropic only sends the 5m/1h
cache_creation_token_detailsonmessage_start; the finalmessage_deltastill has flat cache counts but drops that nested breakdown.ChunkProcessor._calculate_usage_per_chunkwas taking last-winsprompt_tokens_details, so the delta chunk wiped the TTL split and cost logic fell back to the 5-minute write rate (~37.5% low on 1h writes).The aggregator now captures
cache_creation_token_detailsacross chunks (first non-null wins) and re-attaches it to the finalprompt_tokens_detailswhen the last chunk lacks it, without overwriting a breakdown already present on the final chunk. Logic lives in_capture_cache_creation_token_detailsand_attach_cache_creation_token_details. Regression tests cover the message_start→delta case (includingcost_per_token) and the case where the final chunk carries the authoritative breakdown.Reviewed by Cursor Bugbot for commit b8e2265. Bugbot is set up for automated code reviews on this repo. Configure here.