Skip to content

fix(anthropic): map Responses API cached input tokens to cache_read_input_tokens on /v1/messages - #36097

Closed
devin-ai-integration[bot] wants to merge 1 commit into
litellm_internal_stagingfrom
devin_ai_anthropic_responses_cache_usage_36091
Closed

devin-ai-integration[bot] wants to merge 1 commit into
litellm_internal_stagingfrom
devin_ai_anthropic_responses_cache_usage_36091

Conversation

@devin-ai-integration

Copy link
Copy Markdown
Contributor

TLDR

Problem this solves:

  • /v1/messages on Responses-API models never returned cache_read_input_tokens
  • Anthropic-shape clients saw an uncached prompt on every call
  • Streaming read cache counts from fields a Responses usage never has

How it solves it:

  • Map input_tokens_details.cached_tokens to cache_read_input_tokens
  • Subtract it from Anthropic input_tokens, as Anthropic clients expect
  • Share one mapper between the streaming and non-streaming bridge

Relevant issues

Fixes #36091

Linear ticket

Pre-Submission checklist

  • 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 received a Greptile Confidence Score of at least 4/5 before requesting a maintainer review (Greptile reviews automatically once the PR is opened; only comment @greptileai to re-request a review after pushing changes)

Delays in PR merge?

If you're seeing a delay in your PR being merged, ping the LiteLLM Team on Slack (#pr-review).

Screenshots / Proof of Fix

Live proxy on localhost:4000, one model routed to a Responses-API upstream that reports a cache hit on the second identical prompt (input_tokens: 25616, input_tokens_details.cached_tokens: 25613, output_tokens: 5). The upstream here is a local stand-in rather than api.openai.com, which this environment cannot reach, so a reviewer should re-run the same two calls against a real openai/gpt-5.x deployment: the numbers below come straight from whatever the upstream reports, so any cached prompt reproduces it

Before, at 24dbd2b

$ for i in 1 2; do curl -s -X POST localhost:4000/v1/messages -H 'x-api-key: sk-1234' -H 'content-type: application/json' \
    -d '{"model":"gpt-5.6-luna","max_tokens":16,"messages":[{"role":"user","content":"hi"}]}' | jq -c .usage; done
{"input_tokens":25616,"output_tokens":5}
{"input_tokens":25616,"output_tokens":5}

The same prompt through /v1/chat/completions showed the upstream cache working the whole time (prompt_tokens=25616 cached_tokens=25613), so only the Anthropic shape lost it

After, at e030038

$ for i in 1 2; do curl -s -X POST localhost:4000/v1/messages -H 'x-api-key: sk-1234' -H 'content-type: application/json' \
    -d '{"model":"gpt-5.6-luna","max_tokens":16,"messages":[{"role":"user","content":"hi"}]}' | jq -c .usage; done
{"input_tokens": 25616, "output_tokens": 5}
{"input_tokens": 3, "output_tokens": 5, "cache_read_input_tokens": 25613}

$ curl -s -N -X POST localhost:4000/v1/messages -H 'x-api-key: sk-1234' -H 'content-type: application/json' \
    -d '{"model":"gpt-5.6-luna","max_tokens":16,"stream":true,"messages":[{"role":"user","content":"hi"}]}' | grep message_delta
data: {"type": "message_delta", "delta": {"stop_reason": "end_turn", "stop_sequence": null}, "usage": {"input_tokens": 3, "output_tokens": 5, "cache_read_input_tokens": 25613}}

Call 1 is the cold prompt and call 2 is the cache hit, so input_tokens drops to the 3 uncached tokens and the 25613 cached ones show up where an Anthropic client reads them. /v1/chat/completions and /v1/responses are unaffected by this change: it only touches the Anthropic bridge's Responses adapters

Type

🐛 Bug Fix

Changes

responses_adapters/transformation.py built AnthropicUsage from input_tokens and output_tokens only, and responses_adapters/streaming_iterator.py fetched the two details objects into the cache variables and then overwrote both with cache_creation_input_tokens / cache_read_input_tokens off the usage object, names that only exist on Anthropic usage and never on a Responses one, so both counts were pinned to 0 on every call

Both now go through responses_adapters/usage.py::anthropic_usage_from_responses_usage, which reads input_tokens_details.cached_tokens (object or dict shaped) and returns

AnthropicUsage(
    input_tokens=input_tokens - cache_read_input_tokens,
    output_tokens=output_tokens,
    cache_read_input_tokens=cache_read_input_tokens,
)

omitting the cache field entirely when there is no hit, which matches how the chat-completions bridge already reports it. The subtraction is the part that is easy to miss: the Responses API counts cached tokens inside input_tokens, while Anthropic reports them alongside it, so passing the total through unchanged would double-count the prompt for anything summing the fields. The cached count is clamped to input_tokens so an upstream reporting more cached than total can't yield a negative

Regression tests cover both paths in the existing adapter test files: the mapped fields and the subtraction, the no-cache-hit case still omitting the fields, and a usage object missing the counts falling back to zeroes instead of raising mid-stream

Final Attestation

  • The tests check the right things, including the edge cases, and regressions in the respective real-world customer use-cases are not possible after this PR

…nput_tokens

The Anthropic /v1/messages bridge for Responses API models never populated cache_read_input_tokens, so clients reading the Anthropic shape saw an uncached prompt on every call even when upstream served ~100% of it from cache. Streaming read the cache counts from Anthropic-named attributes that a Responses usage object does not have, and the non-streaming path dropped them entirely.

Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
@CLAassistant

Copy link
Copy Markdown

CLA assistant check
Thank you for your submission! We really appreciate it. Like many open source projects, we ask that you sign our Contributor License Agreement before we can accept your contribution.
You have signed the CLA already but the status is still pending? Let us recheck it.

@greptile-apps

greptile-apps Bot commented Aug 6, 2026

Copy link
Copy Markdown
Contributor

Greptile Summary

This PR centralizes conversion of Responses API usage into Anthropic usage and applies it to both streaming and non-streaming /v1/messages responses.

  • Maps cached input tokens to cache_read_input_tokens.
  • Removes cached tokens from Anthropic input_tokens while clamping inconsistent upstream values.
  • Adds regression coverage for cache hits, misses, and missing usage.

Confidence Score: 4/5

The PR appears safe to merge after addressing the non-blocking coarse type annotations in the new streaming test helper.

The shared usage conversion matches established Anthropic cache-token semantics and is covered across streaming and non-streaming paths; the only accepted concern is reduced static checking in a test helper.

Files Needing Attention: tests/test_litellm/llms/anthropic/experimental_pass_through/responses_adapters/test_responses_adapters_streaming_iterator.py

Important Files Changed

Filename Overview
litellm/llms/anthropic/experimental_pass_through/responses_adapters/usage.py Adds a defensive shared mapper that converts Responses API token and cache usage into Anthropic semantics.
litellm/llms/anthropic/experimental_pass_through/responses_adapters/streaming_iterator.py Replaces ineffective direct cache-field reads with the shared usage mapper for terminal stream events.
litellm/llms/anthropic/experimental_pass_through/responses_adapters/transformation.py Uses the shared mapper for non-streaming Anthropic response translation.
tests/test_litellm/llms/anthropic/experimental_pass_through/responses_adapters/test_responses_adapters_streaming_iterator.py Adds focused streaming usage tests, but the new helper violates the repository’s precise-typing convention.
tests/test_litellm/llms/anthropic/experimental_pass_through/responses_adapters/test_responses_adapters_transformation.py Adds non-streaming regression coverage for cached-token mapping, subtraction, and omitted zero-value fields.

Reviews (1): Last reviewed commit: "fix(anthropic): map Responses API cached..." | Re-trigger Greptile

``input_tokens`` to exclude it."""

@staticmethod
def _message_delta_usage(usage: dict) -> dict:

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.

P2 Specify the usage dictionary types

The bare dict annotations discard the expected usage shape from static checking, allowing malformed fixtures and accesses to pass without diagnostics. Parameterize the input and return dictionaries to preserve type checking in these new tests.

Suggested change
def _message_delta_usage(usage: dict) -> dict:
def _message_delta_usage(usage: dict[str, object]) -> dict[str, object]:

Context Used: CLAUDE.md (source)

Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!

@mateo-berri

Copy link
Copy Markdown
Contributor

Closing as superseded: #34957 merged Aug 5 already maps Responses API cache tokens into Anthropic usage on both paths and shipped in v1.97.0-rc.1.

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.

Anthropic /v1/messages bridge for Responses-API models drops cache accounting (cache_read_input_tokens always 0)

2 participants