Skip to content

fix(anthropic): only inject cache_control when the request carries none - #33886

Merged
tin-berri merged 3 commits into
litellm_internal_stagingfrom
litellm_lit4582_cache_control_present
Jul 20, 2026
Merged

tin-berri merged 3 commits into
litellm_internal_stagingfrom
litellm_lit4582_cache_control_present

Conversation

@tin-berri

@tin-berri tin-berri commented Jul 18, 2026 •

Copy link
Copy Markdown
Contributor

Relevant issues

  • config-driven cache_control_injection_points now stands down entirely when the request already carries client cache_control anywhere (messages, system, or tools)
  • closes the tool-blind cap gap that produced Anthropic's "A maximum of 4 blocks with cache_control may be provided. Found 5." 400 for clients that cache their tool definitions
  • brings the config path (what v1.92.0 rollouts used) up to the stand-down contract the docs and the enable_anthropic_prompt_caching flag already promise

Linear ticket

Resolves LIT-4582

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 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 127.0.0.1:4152, real Anthropic API, model anthropic/claude-sonnet-5 configured with an injection point, exactly the v1.92.0 rollout shape:

model_list:
  - model_name: cached-claude
    litellm_params:
      model: anthropic/claude-sonnet-5
      api_key: os.environ/ANTHROPIC_API_KEY
      cache_control_injection_points:
        - location: message
          role: system

The client request carries 4 breakpoints of its own: cache_control on 3 content blocks plus 1 on a tool definition (marked_chat.json; marked_v1.json is the same request in Anthropic shape). The tool breakpoint is invisible to the injection cap, so unfixed litellm injects a 5th onto the system prompt

Before, at 366ec6f (branch point, unfixed):

$ curl -s http://127.0.0.1:4152/v1/chat/completions -H "Authorization: Bearer sk-1234" \
    -H "Content-Type: application/json" -d @marked_chat.json
{"error": {"message": "litellm.BadRequestError: AnthropicException - {\"type\":\"error\",\"error\":{\"type\":\"invalid_request_error\",\"message\":\"A maximum of 4 blocks with cache_control may be provided. Found 5.\"}, ...", "code": "400"}}

$ curl -s http://127.0.0.1:4152/v1/messages -H "Authorization: Bearer sk-1234" \
    -H "Content-Type: application/json" -d @marked_v1.json
{"error": {"message": "{\"type\":\"error\",\"error\":{\"type\":\"invalid_request_error\",\"message\":\"A maximum of 4 blocks with cache_control may be provided. Found 5.\"}, ...", "code": "400"}}

After, at 0268d01 (this PR), the same two requests succeed and the client's own 4 breakpoints reach Anthropic untouched (the cache the first call writes is read back by the second):

$ curl -s http://127.0.0.1:4152/v1/chat/completions ... -d @marked_chat.json   # -> 200
{'finish_reason': 'length', 'cache_creation_input_tokens': 3805, 'cache_read_input_tokens': 0}

$ curl -s http://127.0.0.1:4152/v1/messages ... -d @marked_v1.json             # -> 200
{'stop_reason': 'max_tokens', 'usage': {'cache_creation_input_tokens': 0, 'cache_read_input_tokens': 3805}}

A request with no client cache_control still gets the configured injection, so the feature keeps working for the traffic it was built for (same output at both SHAs):

$ curl -s http://127.0.0.1:4152/v1/chat/completions ... -d @unmarked_chat.json  # -> 200
{'cache_creation_input_tokens': 0, 'cache_read_input_tokens': 3363}

All three requests were re-run at e064857 (the judged-stamp revision) with identical results: both marked requests 200 with the client's four breakpoints intact, the unmarked request cached by injection (cache_creation_input_tokens: 3363 on a cold cache)

Type

🐛 Bug Fix

Changes

  • configured cache_control_injection_points now stand down entirely when the request already carries client cache_control anywhere: message level, content block, system block, or tool definition
  • the shared stand-down predicate also learned the OpenAI tool shape (tool["function"]["cache_control"]), which the Anthropic chat transform accepts as a client breakpoint but the predicate missed; this hardens the enable_anthropic_prompt_caching path too
  • the judgment happens once per request at the two chokepoints where tools are visible (maybe_seed_default_injection_points for /chat/completions, maybe_inject_cache_control for /v1/messages); non-message points written back for provider transforms carry an internal judged stamp so no later pass re-judges them
  • stamping builds copies because config-owned point dicts are shared across requests; the stamp never reaches the provider (the Bedrock transform consumes the points and reads only location and control)
  • unchanged: requests without client cache_control keep getting the configured points, and the existing per-point overwrite guard and four-block cap still apply among litellm's own points

The docs already promise this contract ("Never double-injects. If the request already carries its own cache_control, LiteLLM stands down and the client's checkpoints win", https://docs.litellm.ai/docs/tutorials/prompt_caching); the code only honored it on the newer enable_anthropic_prompt_caching path, not on the config-driven path this ticket is about

Two things a reviewer will ask about. Full stand-down was chosen over teaching the four-block cap to count tool breakpoints because counting only avoids the 400; partial injection would still reshape the caching layout of a client that is managing its own breakpoints, which is the other half of the complaint. The judged stamp exists because the injection machinery re-runs on the same request through several paths (acompletion re-enters completion, the async /v1/messages entry re-dispatches into the sync handler, and interceptor sub-calls re-enter anthropic_messages with the outer request's kwargs); by then the messages carry litellm's own injected marks, so a re-judgment would misread them as client breakpoints and drop the written-back tool_config remainder the Bedrock transform consumes. Carrying the judgment inside the written-back points makes every such re-entry, present and future, skip it by construction; an earlier revision gated this with per-entry is_first_pass flags, which review correctly showed cannot cover re-entry paths that reuse kwargs wholesale

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

Note

Medium Risk
Changes behavior on the Anthropic prompt-caching path for proxy and native messages traffic, but narrows injection to match documented contract and reduces provider 400 risk; re-entry stamping is localized to injection-point handling.

Overview
Config-driven cache_control_injection_points now honor the same stand-down rule as auto-caching: if the request already has client cache_control on messages, system blocks, or tools, LiteLLM skips injection instead of adding more breakpoints (fixing Anthropic 400s when clients cache tools plus content).

Stand-down runs once per request via _should_stand_down on /chat/completions seeding (maybe_seed_default_injection_points) and /v1/messages (maybe_inject_cache_control). Non-message points written back for provider transforms are copied with _litellm_judged so later re-entries (async/sync dispatch, interceptor sub-calls) do not treat LiteLLM’s own marks as client breakpoints.

Tool detection now treats OpenAI-shaped tools (function.cache_control) as client breakpoints, matching what the Anthropic chat transform already accepts.

Reviewed by Cursor Bugbot for commit e064857. Bugbot is set up for automated code reviews on this repo. Configure here.

@greptile-apps

greptile-apps Bot commented Jul 18, 2026 •

Copy link
Copy Markdown
Contributor

Greptile Summary

This PR fixes a bug where cache_control_injection_points configured in the proxy config would still fire even when the client already supplied its own cache_control breakpoints, potentially pushing the request past Anthropic's four-block limit and producing a 400 error. The fix introduces a "stand-down" predicate that is evaluated once per request entry point and a judged stamp that prevents re-evaluation on re-entries (e.g. acompletion → completion or the async-to-sync /v1/messages dispatch).

  • Adds _should_stand_down / _stamped_as_judged helpers and wires them into both the /chat/completions seeding path (maybe_seed_default_injection_points) and the /v1/messages injection path (maybe_inject_cache_control).
  • Extends _request_has_cache_control to detect OpenAI-shaped tool definitions where cache_control is nested under tool["function"] rather than at the top level.
  • Updates CacheControlMessageInjectionPoint and CacheControlToolConfigInjectionPoint TypedDicts with a NotRequired[bool] _litellm_judged field; adds a comprehensive test class covering all stand-down and re-entry scenarios.

Confidence Score: 5/5

Safe to merge — the change is scoped to the Anthropic cache-control injection hook, the stand-down logic is correctly guarded at both entry points, and the judged stamp reliably prevents re-judgment on all known re-entry paths.

The stand-down predicate is evaluated with the right parameters at each entry point: maybe_seed_default_injection_points passes system=None (correct for /chat/completions where system lives inside messages) and maybe_inject_cache_control passes the actual system block. The _should_stand_down fast-path — returning False when all points carry the judged stamp — is the correct guard against misreading litellm's own injected marks as client breakpoints on re-entry. Config-owned point dicts are copied before stamping, preventing cross-request leakage. The updated test assertion correctly reflects the new behavior rather than masking a regression. No real network calls are introduced in the test suite.

No files require special attention.

Important Files Changed

Filename Overview
litellm/integrations/anthropic_cache_control_hook.py Adds _should_stand_down / _stamped_as_judged helpers and wires them into both the /chat/completions seeding path and the /v1/messages injection path; also extends _request_has_cache_control to handle OpenAI-shaped tool definitions. Logic is correct and well-guarded.
litellm/types/integrations/anthropic_cache_control_hook.py Adds NotRequired[bool] _litellm_judged field to both TypedDicts so the internal stamp is type-safe; import of NotRequired from typing_extensions is correct.
tests/test_litellm/integrations/test_anthropic_cache_control_hook.py Adds TestConfiguredInjectionPointsStandDown class with 10 new unit tests covering all stand-down scenarios; updates existing test assertion to include the new judged stamp (correctly reflects changed behavior, not a regression mask); all tests use mocks with no real network calls.

Reviews (3): Last reviewed commit: "fix(anthropic): carry the stand-down jud..." | Re-trigger Greptile

Comment thread litellm/main.py Resolved
@tin-berri

Copy link
Copy Markdown
Contributor Author

bugbot run

@codecov

codecov Bot commented Jul 18, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.

📢 Thoughts on this report? Let us know!

@tin-berri

Copy link
Copy Markdown
Contributor Author

@greptileai

@tin-berri

Copy link
Copy Markdown
Contributor Author

@greptileai

@codspeed

codspeed Bot commented Jul 19, 2026

Copy link
Copy Markdown
Contributor

Merging this PR will not alter performance

✅ 31 untouched benchmarks


Comparing litellm_lit4582_cache_control_present (e064857) with litellm_internal_staging (366ec6f)

Open in CodSpeed

@tin-berri

Copy link
Copy Markdown
Contributor Author

bugbot run

@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 e064857. Configure here.

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

LGTM; thanks!

@tin-berri
tin-berri merged commit f9b10eb into litellm_internal_staging Jul 20, 2026
82 checks passed
@tin-berri
tin-berri deleted the litellm_lit4582_cache_control_present branch July 20, 2026 23:20
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