Skip to content

fix(anthropic): bill streaming 1h prompt-cache writes at the 1h rate - #32073

Merged
mateo-berri merged 3 commits into
litellm_internal_stagingfrom
litellm_anthropic_1hr_cache_streaming_cost
Jul 4, 2026
Merged

mateo-berri merged 3 commits into
litellm_internal_stagingfrom
litellm_anthropic_1hr_cache_streaming_cost

Conversation

@mateo-berri

@mateo-berri mateo-berri commented Jul 3, 2026 •

Copy link
Copy Markdown
Contributor

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 them

Linear ticket

Pre-Submission checklist

Please complete all items before asking a LiteLLM maintainer to review your PR

  • I have added meaningful tests
  • My PR passes all CI/CD checks (e.g., lint, format, unit tests)
  • My PR's scope is as isolated as possible; it only solves 1 specific problem
  • I have requested a Greptile review by commenting @greptileai and received a Confidence Score of at least 4/5 before requesting a maintainer review

Screenshots / 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:

curl --location 'http://localhost:4000/v1/chat/completions' \
  --header 'Content-Type: application/json' \
  --header 'Authorization: Bearer sk-1234' \
  --data @body.json
# body.json: stream=true, stream_options.include_usage=true, a >1024-token
# system block with cache_control {"type":"ephemeral","ttl":"1h"}

Final streamed usage (note the preserved 1h breakdown):

"usage": {
  "prompt_tokens": 4818,
  "completion_tokens": 47,
  "prompt_tokens_details": {
    "cached_tokens": 0,
    "text_tokens": 15,
    "cache_creation_tokens": 4803,
    "cache_creation_token_details": {
      "ephemeral_5m_input_tokens": 0,
      "ephemeral_1h_input_tokens": 4803
    }
  },
  "cache_creation_input_tokens": 4803,
  "cache_read_input_tokens": 0
}

Computed cost (proxy detailed_debug log):

response_cost: 0.029568

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 streaming message_start event; the later message_delta carries the flat cache_creation_input_tokens count but drops the nested object. ChunkProcessor._calculate_usage_per_chunk aggregates prompt_tokens_details last-wins, so message_delta's details (with cache_creation_token_details=None) overwrote the breakdown captured from message_start. Cost calc then took 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 about 37.5% on streaming requests. Non-streaming was unaffected because its usage is parsed once from the full response body

This tracks cache_creation_token_details across chunks with the same non-null-wins semantics already used for the flat cache counts, then stitches it back onto the final prompt_tokens_details when 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_chunk stays within the strict C901 complexity budget enforced by the lint gate. A regression test feeds the real two-event Anthropic usage shapes through calculate_usage and 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 capture


Note

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_details on message_start; the final message_delta still has flat cache counts but drops that nested breakdown. ChunkProcessor._calculate_usage_per_chunk was taking last-wins prompt_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_details across chunks (first non-null wins) and re-attaches it to the final prompt_tokens_details when the last chunk lacks it, without overwriting a breakdown already present on the final chunk. Logic lives in _capture_cache_creation_token_details and _attach_cache_creation_token_details. Regression tests cover the message_start→delta case (including cost_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.

…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.
@mateo-berri

Copy link
Copy Markdown
Contributor Author

@greptileai


Generated by Claude Code

@greptile-apps

greptile-apps Bot commented Jul 3, 2026 •

Copy link
Copy Markdown
Contributor

Greptile Summary

Fixes under-billing of Anthropic 1-hour ephemeral prompt-cache writes on streaming responses by preserving the cache_creation_token_details breakdown from the message_start event and reattaching it when the later message_delta event overwrites prompt_tokens_details without the breakdown.

  • Introduces _capture_cache_creation_token_details and _attach_cache_creation_token_details static helpers in ChunkProcessor._calculate_usage_per_chunk to track the 5m/1h TTL split across chunks with non-null-wins semantics; the post-loop stitch only applies when the final prompt_tokens_details does not already carry the breakdown.
  • Adds two focused unit tests: one reproduces the exact Anthropic two-event trace and asserts the 1h write rate is applied end-to-end (including a guard asserting the old buggy cost differs), and a second verifies the final-chunk-carries-breakdown case is handled without regressing.

Confidence Score: 5/5

Safe 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 cache_creation_token_details across streaming chunks. Both helpers are pure functions with clear invariants, the model_copy stitch is Pydantic-idiomatic, and the post-loop guard (existing is not None) prevents overwriting a breakdown that the final chunk already carries. Two regression tests cover the primary bug scenario end-to-end (including an explicit cost assertion) and the alternative path where the final chunk has its own breakdown.

No files require special attention.

Important Files Changed

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-apps

greptile-apps Bot commented Jul 3, 2026

Copy link
Copy Markdown
Contributor

Greptile Summary

Fixes 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 message_start SSE event carries the cache_creation_token_details 5m/1h breakdown, but the subsequent message_delta event drops it; the last-wins aggregation in _calculate_usage_per_chunk then discarded the breakdown before cost calculation.

  • Introduces a dedicated cache_creation_token_details accumulator (non-null-wins) in the chunk loop, mirroring the same semantics already used for the flat cache counts; after the loop, stitches the preserved breakdown back onto the final prompt_tokens_details only when the last chunk lacks it.
  • Adds a focused regression test that feeds the real two-event Anthropic usage shapes through calculate_usage and asserts both structural preservation of the breakdown and the correct 1h-rate cost, guarded by an explicit assertion that the pre-fix (5m-rate) amount does not match.

Confidence Score: 4/5

The change is a safe, targeted addition to the streaming chunk aggregator — it only runs the new stitching logic when the last chunk's prompt_tokens_details lacks the breakdown and a previous chunk preserved one, so existing aggregation paths are unaffected.

The fix is mechanically correct: AnthropicConfig.calculate_usage() always produces a non-None prompt_tokens_details (confirmed by reading the source), so the post-loop guard conditions hold in all real Anthropic streaming cases. The regression test faithfully reproduces the two-event shape and validates both the structural fix and the cost calculation. The only modest concern is that prompt_tokens_details is still assigned unconditionally (pre-existing behavior, not introduced here), so a hypothetical intermediate chunk that returns prompt_tokens_details=None would overwrite a previously captured value — though this does not happen in any current provider's streaming output and is not a regression introduced by this PR.

No files require special attention; both changed files are self-contained and well-covered by the new test.

Important Files Changed

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

codecov Bot commented Jul 3, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.

📢 Thoughts on this report? Let us know!

@mateo-berri

Copy link
Copy Markdown
Contributor Author

@greptileai


Generated by Claude Code

@mateo-berri

Copy link
Copy Markdown
Contributor Author

bugbot run


Generated by Claude Code

@cursor cursor Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

✅ 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.

@mateo-berri

Copy link
Copy Markdown
Contributor Author

@greptileai


Generated by Claude Code

@mateo-berri

Copy link
Copy Markdown
Contributor Author

bugbot run


Generated by Claude Code

@mateo-berri
mateo-berri requested a review from tin-berri July 3, 2026 21:08

@cursor cursor Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

✅ 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.

@mateo-berri
mateo-berri merged commit 1e7dbe5 into litellm_internal_staging Jul 4, 2026
79 checks passed
@mateo-berri
mateo-berri deleted the litellm_anthropic_1hr_cache_streaming_cost branch July 4, 2026 00:34
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.

3 participants