Repository navigation
fix(anthropic-messages): restore cache_control injection on messages path - #30806
anneheartrecord wants to merge 3 commits into
Conversation
Codecov Report❌ Patch coverage is
📢 Thoughts on this report? Let us know! |
Greptile SummaryThis PR fixes a silent cache injection failure on the native Anthropic
Confidence Score: 4/5Safe 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.
|
| 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
| # 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", | ||
| ) |
There was a problem hiding this comment.
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.
| injection_points: list[CacheControlInjectionPoint] = non_default_params.pop( | ||
| "cache_control_injection_points", [] | ||
| ) | ||
| if not injection_points: | ||
| return messages, system, tools |
There was a problem hiding this comment.
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.
| 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 | ||
| ) |
There was a problem hiding this comment.
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!
|
Thanks for the well-documented PR and the thorough test coverage! A couple of things before this is ready for maintainer review:
Once the Greptile score is at 5/5, we'll take another look! |
|
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 P2-2 — Docstring overstates deep-copy guarantee: Clarified the P2-3 — Double provider resolution: After investigating, a simple short-circuit (skip No conflicts: |
|
CI failures here are caused by a broken import in All 30+ checks fail at startup with: The import chain ( Once |
|
Quick CI update: the import error that was blocking all checks ( P2 items from before are all covered in |
…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.
03838e5 to
052d8e7
Compare
|
Closing this as superseded 🙏 Cache-control injection on the native No need to carry a second implementation. Thanks @Sameerlite for the earlier review and feedback! |
What this does
This is the replacement for #30341, which was merged and then reverted from
litellm_internal_stagingbecause 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_pointsare now applied on the native Anthropic/v1/messagespath instead of being forwarded unused.Compared with #30341, this branch is rebuilt on the current
litellm_internal_stagingand updates the new annotations to the repo's PEP 585/604 style so the strict budget stays clean.Verification
Refs #30293
Supersedes #30341