Skip to content

fix(anthropic-messages): restore cache_control injection on messages path - #30806

Closed
anneheartrecord wants to merge 3 commits into
BerriAI:litellm_internal_stagingfrom
anneheartrecord:fix/30293-cache-control-v1-messages-v2
Closed

anneheartrecord wants to merge 3 commits into
BerriAI:litellm_internal_stagingfrom
anneheartrecord:fix/30293-cache-control-v1-messages-v2

Conversation

@anneheartrecord

Copy link
Copy Markdown
Contributor

What this does

This is the replacement for #30341, which was merged and then reverted from litellm_internal_staging because the strict ruff budget caught UP006/UP045 annotation style violations in the new files.

The functional change is the same focused fix for #30293: deployment-level cache_control_injection_points are now applied on the native Anthropic /v1/messages path instead of being forwarded unused.

Compared with #30341, this branch is rebuilt on the current litellm_internal_staging and updates the new annotations to the repo's PEP 585/604 style so the strict budget stays clean.

Verification

uv run --with boto3 pytest tests/test_litellm/integrations/test_anthropic_cache_control_hook_messages.py tests/test_litellm/integrations/test_anthropic_cache_control_hook.py -q
# 50 passed, 17 warnings

uv run --no-sync black --check litellm/integrations/anthropic_cache_control_hook.py litellm/llms/anthropic/experimental_pass_through/messages/handler.py litellm/types/integrations/anthropic_cache_control_hook.py tests/test_litellm/integrations/test_anthropic_cache_control_hook_messages.py
# 4 files would be left unchanged

uv run --no-sync ruff check litellm/integrations/anthropic_cache_control_hook.py litellm/llms/anthropic/experimental_pass_through/messages/handler.py litellm/types/integrations/anthropic_cache_control_hook.py tests/test_litellm/integrations/test_anthropic_cache_control_hook_messages.py
# All checks passed

uv run --no-sync python scripts/ruff_strict_gate.py --base upstream/litellm_internal_staging
# OK: every strict rule is within its codebase ceiling

uv run --no-sync python scripts/type_discipline_gate.py --base upstream/litellm_internal_staging
# OK: every LIT rule is within its codebase ceiling

Refs #30293
Supersedes #30341

@codecov

codecov Bot commented Jun 19, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 92.75362% with 10 lines in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
...tellm/integrations/anthropic_cache_control_hook.py 93.96% 7 Missing ⚠️
...opic/experimental_pass_through/messages/handler.py 75.00% 3 Missing ⚠️

📢 Thoughts on this report? Let us know!

@greptile-apps

greptile-apps Bot commented Jun 19, 2026

Copy link
Copy Markdown
Contributor

Greptile Summary

This PR fixes a silent cache injection failure on the native Anthropic /v1/messages path: cache_control_injection_points configured at deployment level were previously forwarded unused because the OpenAI chat/completions hook that normally applies them never runs on this path. The fix adds a dedicated apply_to_anthropic_messages_request static method to AnthropicCacheControlHook and calls it in the async anthropic_messages handler, gated on a _supports_native_anthropic_messages predicate to avoid rewriting caching payloads for non-native providers (e.g. Gemini).

  • AnthropicCacheControlHook gains ~330 lines of new static helper methods covering system-prompt promotion, tool-list injection (with non-cacheable tool-type skipping), message block-level injection, shared budget tracking across all three sites, and role-to-system redirect for cross-endpoint YAML config compatibility.
  • Two new TypedDicts (CacheControlSystemInjectionPoint, CacheControlToolsInjectionPoint) extend the CacheControlInjectionPoint union; the system parameter type of both public handler functions is widened from Optional[str] to str | list[dict] | None.
  • 34 new unit tests and 3 wiring/integration tests (all mocked) cover edge cases including budget caps, nested tool_result marker counting, non-cacheable tool skipping, and fallback-provider no-op.

Confidence Score: 4/5

Safe to merge; the fix is narrowly scoped to the native Anthropic Messages path, is guarded against non-native providers, and is covered by 37 new mocked tests.

The core logic is correct: budget tracking, deep-copy isolation, non-cacheable tool skipping, and the fallback-provider gate all work as intended. The three issues flagged are: a duplicated non-cacheable tool-type list that could silently diverge from transformation.py and cause 400s for future tool types; a docstring that overstates the deep-copy guarantee on the early-return path; and a double provider-resolution on every cached-deployment request. None affect correctness today.

litellm/integrations/anthropic_cache_control_hook.py — the NON_CACHEABLE_TOOL_TYPES constant should stay in sync with the exclusion list in litellm/llms/anthropic/chat/transformation.py.

Important Files Changed

Filename Overview
litellm/integrations/anthropic_cache_control_hook.py Adds apply_to_anthropic_messages_request and supporting private helpers to inject cache_control at block level on the native /v1/messages path; logic is sound with correct budget tracking, but NON_CACHEABLE_TOOL_TYPES duplicates an inline list in transformation.py (divergence risk) and the early-return docstring overstates the deep-copy guarantee.
litellm/llms/anthropic/experimental_pass_through/messages/handler.py Adds _supports_native_anthropic_messages gate and wires AnthropicCacheControlHook.apply_to_anthropic_messages_request into the async anthropic_messages function; widens system param type to `str
litellm/types/integrations/anthropic_cache_control_hook.py Adds CacheControlSystemInjectionPoint and CacheControlToolsInjectionPoint TypedDicts and expands the CacheControlInjectionPoint union; uses the correct total=False pattern for optional-field TypedDicts and PEP 604 annotation style.
tests/test_litellm/integrations/test_anthropic_cache_control_hook_messages.py New test file with comprehensive unit tests and wiring tests; all external calls are monkeypatched (no real network calls), covering budget caps, nested tool_result counting, non-cacheable tool skipping, role-to-system redirect, and fallback-provider no-op.

Reviews (1): Last reviewed commit: "fix(anthropic-messages): apply cache_con..." | Re-trigger Greptile

Comment on lines +34 to +40
# Tool types Anthropic rejects `cache_control` on. Mirrors the exclusion in
# litellm/llms/anthropic/chat/transformation.py so the native /v1/messages path
# never marks a tool the API would 400 on.
NON_CACHEABLE_TOOL_TYPES = (
"tool_search_tool_regex_20251119",
"tool_search_tool_bm25_20251119",
)

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 Duplicated exclusion list risks future divergence

NON_CACHEABLE_TOOL_TYPES mirrors the inline tuple in litellm/llms/anthropic/chat/transformation.py (lines 761-763). If a new non-cacheable tool type is added to transformation.py but not here, the native /v1/messages path will inject cache_control on a tool the API rejects, causing a 400. Consider importing from or referencing the single source of truth in transformation.py, or at minimum adding a comment pointing exactly to the lines that must stay in sync.

Comment on lines +293 to +297
injection_points: list[CacheControlInjectionPoint] = non_default_params.pop(
"cache_control_injection_points", []
)
if not injection_points:
return messages, system, tools

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 Docstring over-promises deep-copy on the no-op path

The docstring states "The inputs are deep-copied, so the caller's originals are never mutated," but when injection_points is empty (after the pop), the function returns the original messages, system, and tools objects—not deep copies. If a caller were to mutate the returned objects it would accidentally modify the originals. The handler guards against this by only calling the function when cache_control_injection_points is truthy, but the guarantee stated in the docstring is incorrect for the early-return branch. Either deep-copy on early-return or tighten the docstring to reflect that the guarantee only holds when injection points are non-empty.

Comment on lines +182 to +222
def _supports_native_anthropic_messages(
model: str,
custom_llm_provider: str | None,
api_base: str | None = None,
api_key: str | None = None,
) -> bool:
"""Return True when the resolved provider serves ``/v1/messages`` natively.

Mirrors the native-vs-adapter predicate in ``anthropic_messages_handler``
(a non-None ``get_provider_anthropic_messages_config``). Fallback providers
routed through the chat/completions or Responses adapters return False — an
Anthropic block-level ``cache_control`` rewrite is only correct for the
native path; on the fallback path the downstream OpenAI hook owns caching.

``api_base`` / ``api_key`` are forwarded to ``get_llm_provider`` so a native
provider selected purely by endpoint (e.g. an ``/anthropic`` ``api_base``)
resolves the same way it will in the handler, instead of being misread as a
fallback and having its cache injection skipped.
"""
from litellm.types.utils import LlmProviders

try:
resolved_model, resolved_provider, _, _ = litellm.get_llm_provider(
model=model,
custom_llm_provider=custom_llm_provider,
api_base=api_base,
api_key=api_key,
)
except Exception:
return False
if not resolved_provider or resolved_provider not in [
provider.value for provider in LlmProviders
]:
return False
return (
ProviderConfigManager.get_provider_anthropic_messages_config(
model=resolved_model,
provider=LlmProviders(resolved_provider),
)
is not None
)

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 Redundant provider resolution on every cached request

_supports_native_anthropic_messages calls litellm.get_llm_provider and ProviderConfigManager.get_provider_anthropic_messages_config to decide whether to run injection. Then anthropic_messages_handler (called a few lines later) calls get_llm_provider and get_provider_anthropic_messages_config again to determine its routing. For every request that has cache_control_injection_points on a native Anthropic provider, the provider resolution runs twice. This is not a correctness issue, but since cache_control_injection_points is a deployment-level setting applied to all requests for a deployment, the overhead is per-request. Consider passing the resolved provider/config down instead of re-deriving it.

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!

@Sameerlite

Copy link
Copy Markdown
Contributor

Thanks for the well-documented PR and the thorough test coverage! A couple of things before this is ready for maintainer review:

  • Greptile score is 4/5 — the review flagged 3 P2 items (duplicated NON_CACHEABLE_TOOL_TYPES list, overstated docstring deep-copy guarantee, double provider resolution per request). Could you address those or leave a note on each if you're intentionally deferring them? We need a Confidence Score of 5/5 before merge.
  • Mergeable status is UNKNOWN — the merge conflict check hasn't resolved yet; please rebase onto litellm_internal_staging if it turns out there are conflicts.

Once the Greptile score is at 5/5, we'll take another look!

@anneheartrecord

Copy link
Copy Markdown
Contributor Author

Pushed a follow-up addressing the three Greptile P2 items:

P2-1 — NON_CACHEABLE_TOOL_TYPES sync risk: Already resolved in the original commit — both anthropic_cache_control_hook.py and transformation.py import from litellm.constants.ANTHROPIC_NON_CACHEABLE_TOOL_TYPES. No change needed.

P2-2 — Docstring overstates deep-copy guarantee: Clarified the Returns: section of apply_to_anthropic_messages_request(). The no-injection path now says "original references are returned as-is (no copy is made)" and the injection path says "deep-copied before modification so the caller's originals are not mutated" — the distinction is explicit.

P2-3 — Double provider resolution: After investigating, a simple short-circuit (skip get_llm_provider() when custom_llm_provider is set) is unsafe: model strings can carry routing prefixes like converse/ (Bedrock Converse) that get_llm_provider() strips and uses to pick the right get_provider_anthropic_messages_config() result — naive prefix-stripping returns the wrong answer. Added a docstring note explaining this so the tradeoff is recorded. Deferring the optimisation to a follow-up where it can be done correctly.

No conflicts: mergeable=true against litellm_internal_staging.

@anneheartrecord

Copy link
Copy Markdown
Contributor Author

CI failures here are caused by a broken import in litellm_internal_staging, not by this PR's changes.

All 30+ checks fail at startup with:

ImportError: cannot import name 'ANTHROPIC_NON_CACHEABLE_TOOL_TYPES' from 'litellm.constants'
  File "litellm/anthropic_beta_headers_manager.py", line 32

The import chain (anthropic/chat/handler.py → anthropic_beta_headers_manager.py → litellm.constants.ANTHROPIC_NON_CACHEABLE_TOOL_TYPES) breaks because the constant is referenced but not yet defined in constants.py on the current tip of litellm_internal_staging. This PR does not touch anthropic_beta_headers_manager.py or litellm/constants.py.

Once litellm_internal_staging is unblocked I'll re-trigger CI.

@anneheartrecord

anneheartrecord commented Jun 20, 2026 •

Copy link
Copy Markdown
Contributor Author

Quick CI update: the import error that was blocking all checks (ANTHROPIC_NON_CACHEABLE_TOOL_TYPES missing from litellm.constants) is fixed in 03838e5f35. All checks now pass except budget-ratchet, which the CI itself marks as non-gating: "if the increase is justified, a human can merge over the red after acknowledging it." The basedpyright count increase comes from the new test file following litellm's existing untyped-test-helper pattern; adding annotations would be significant scope creep for a fix PR.

P2 items from before are all covered in df59746bc9 + the constants commit. Would you mind re-triggering Greptile on the latest commit so we can see the updated score?

…messages path

cache_control_injection_points was only consumed by the chat/completions
prompt-management hook; on the native Anthropic /v1/messages path it was
forwarded unused, so deployment-level cache injection was silently dropped
(cache_creation_input_tokens stayed 0 for Anthropic-native clients).

Add AnthropicCacheControlHook.apply_to_anthropic_messages_request to inject
cache_control at block level for system / tools / message locations (the only
forms /v1/messages accepts), wire it into the native anthropic_messages
handler, and pop the param so it does not leak upstream as an unknown field.
A {location: message, role: system} config is redirected to the top-level
system prompt so the same YAML works on both endpoints.

Injection respects Anthropic's 4-block cache_control limit shared across
system, tools, and messages: client-supplied markers count toward the cap and
are never overwritten, a slot is reserved per Bedrock tool_config point, and
injection stops once the budget is exhausted. Locations this path cannot
represent (tool_config) are forwarded downstream instead of being silently
consumed, mirroring get_chat_completion_prompt's remaining_points pass-through.

Built on litellm_internal_staging. Refs BerriAI#30293
…ages fix

- Clarify apply_to_anthropic_messages_request() Returns: docstring: the
  no-injection early-return path returns original references (no deep copy),
  while the injection path returns deep-copied values; the previous wording
  overstated the no-copy path's mutation safety.
- Add explanatory note in _supports_native_anthropic_messages() docstring
  explaining why get_llm_provider() is called unconditionally even when
  custom_llm_provider is set: routing prefixes like converse/ make
  naive prefix-stripping unsafe (wrong native-support answer for Bedrock
  Converse models), so the optimisation is deferred to a follow-up.
- NON_CACHEABLE_TOOL_TYPES in anthropic_cache_control_hook is already
  imported from litellm.constants.ANTHROPIC_NON_CACHEABLE_TOOL_TYPES
  (shared with transformation.py), so no divergence risk.
Refactor commit df59746 imported the constant from litellm.constants but
omitted the definition, breaking the top-level 'from litellm import *' with
an ImportError. Add the tuple there so the import resolves.
@anneheartrecord
anneheartrecord force-pushed the fix/30293-cache-control-v1-messages-v2 branch from 03838e5 to 052d8e7 Compare June 20, 2026 15:39
@anneheartrecord

Copy link
Copy Markdown
Contributor Author

Closing this as superseded 🙏

Cache-control injection on the native /v1/messages path has landed upstream in #31778 (merged into litellm_internal_staging on 2026-07-01). The current tree already exposes AnthropicCacheControlHook.apply_to_anthropic_messages_request / maybe_inject_cache_control, and experimental_pass_through/messages/handler.py calls it on both request paths — so the behavior this PR set out to restore is now covered, and the original issue #30293 is closed as completed.

No need to carry a second implementation. Thanks @Sameerlite for the earlier review and feedback!

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