Repository navigation
feat: add cache control injection support for v1/messages endpoint - #31778
krrish-berri-2 merged 4 commits into
Conversation
Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
🤖 Devin AI EngineerI'll be helping with this pull request! Here's what you should know: ✅ I will automatically:
Note: I can only respond to comments from users who have write access to this repository. ⚙️ Control Options:
|
Codecov Report❌ Patch coverage is
📢 Thoughts on this report? Let us know! |
Greptile SummaryThis PR extends
Confidence Score: 4/5Safe to merge with low risk; the block-budget arithmetic is correct and the feature is additive. Two edge cases in The core injection logic, limit enforcement, and handler integration are all correct. Two non-blocking issues exist:
|
| Filename | Overview |
|---|---|
| litellm/integrations/anthropic_cache_control_hook.py | Adds apply_to_anthropic_messages_request static method and two helpers. Logic for counting and enforcing the 4-block limit is correct; minor mutation-in-place concern in _insert_cache_control_in_system and an unconditional used_blocks increment that could miscount for an empty system list. |
| litellm/llms/anthropic/experimental_pass_through/messages/handler.py | Cache control injection added to both async and sync entry points. The async handler injects before pre-request hooks, then passes remaining tool_config points to the sync handler, which safely re-processes them; slightly wasteful but not incorrect. |
| tests/test_litellm/integrations/test_anthropic_cache_control_hook.py | Adds 10 new unit tests for the new apply_to_anthropic_messages_request method; all mock-only, covering string/list system injection, role/index targeting, 4-block limit, tool_config forwarding, immutability, and None system handling. |
Reviews (1): Last reviewed commit: "feat: add cache control injection suppor..." | Re-trigger Greptile
| @staticmethod | ||
| def _insert_cache_control_in_system( | ||
| system: str | list, | ||
| control: ChatCompletionCachedContent, | ||
| ) -> list: | ||
| if isinstance(system, str): | ||
| return [{"type": "text", "text": system, "cache_control": control}] | ||
| if len(system) > 0 and isinstance(system[-1], dict): | ||
| system[-1]["cache_control"] = control | ||
| return system |
There was a problem hiding this comment.
_insert_cache_control_in_system has inconsistent semantics: for a str input it returns a brand-new list, but for a list input it mutates the last element in-place and returns the same list object. Callers today always pass a copy.deepcopy, so there is no bug right now, but future callers who skip the deep-copy would silently mutate the original. Consider always working on a copy inside the helper so the function is consistently non-mutating regardless of input type.
| @staticmethod | |
| def _insert_cache_control_in_system( | |
| system: str | list, | |
| control: ChatCompletionCachedContent, | |
| ) -> list: | |
| if isinstance(system, str): | |
| return [{"type": "text", "text": system, "cache_control": control}] | |
| if len(system) > 0 and isinstance(system[-1], dict): | |
| system[-1]["cache_control"] = control | |
| return system | |
| @staticmethod | |
| def _insert_cache_control_in_system( | |
| system: str | list, | |
| control: ChatCompletionCachedContent, | |
| ) -> list: | |
| if isinstance(system, str): | |
| return [{"type": "text", "text": system, "cache_control": control}] | |
| result = list(system) | |
| if len(result) > 0 and isinstance(result[-1], dict): | |
| result[-1] = {**result[-1], "cache_control": control} | |
| return result |
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!
| for point in system_points: | ||
| if used_blocks >= max_blocks: | ||
| break | ||
| if processed_system is None: | ||
| continue | ||
| if AnthropicCacheControlHook._count_system_cache_control_blocks(processed_system) > 0: | ||
| continue | ||
| control = point.get("control") or ChatCompletionCachedContent(type="ephemeral") | ||
| processed_system = AnthropicCacheControlHook._insert_cache_control_in_system(processed_system, control) | ||
| used_blocks += 1 |
There was a problem hiding this comment.
used_blocks is incremented unconditionally after calling _insert_cache_control_in_system, but that function does nothing when system is an empty list [] (the if len(system) > 0 guard silently exits). If a caller passes system=[], the budget counter reads one slot consumed when in reality zero cache-control blocks were inserted. This makes the subsequent max_blocks - system_blocks_after budget passed to _apply_message_injections too low by 1, silently dropping a valid message injection point.
There was a problem hiding this comment.
Fixed in fecf84b. The used_blocks increment now only happens inside the branch where the insertion actually occurred (the str and non-empty list cases).
| messages, system, remaining_cc_points = AnthropicCacheControlHook.apply_to_anthropic_messages_request( | ||
| messages=messages, |
There was a problem hiding this comment.
apply_to_anthropic_messages_request returns str | list | None for the system position, but both anthropic_messages and anthropic_messages_handler declare system: Optional[str]. Re-binding system here widens its type from str | None to str | list | None for the rest of the function, which basedpyright will flag on the downstream call sites (e.g. the partial(anthropic_messages_handler, ..., system=system, ...) call where the param type is again Optional[str]). The signatures should be updated to Optional[Union[str, List[Dict]]] (or the existing str | list | None union) to reflect that the Anthropic API accepts both forms.
There was a problem hiding this comment.
Fixed in fecf84b. Both handler signatures now use system: Optional[Union[str, list]] which matches AnthropicMessagesRequestOptionalParams in litellm/types/llms/anthropic.py.
…rol injection Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
There was a problem hiding this comment.
this seems to add a ton of code. is this all needed? can it be made simpler, and better typed. (maybe check types/? )
There was a problem hiding this comment.
Simplified in fecf84b. Inlined the two helper methods, fixed the system=[] bug Greptile caught, and updated the handler's system param type to Optional[Union[str, list]]. Net -141 lines.
…ndler system type Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
|
|
| # ids like ``functions.Bash:0`` that violate Anthropic's id pattern. | ||
| messages = sanitize_tool_use_ids_in_anthropic_messages(messages) | ||
|
|
||
| cache_control_injection_points = kwargs.pop("cache_control_injection_points", None) |
There was a problem hiding this comment.
this should be a helper, why is it code in here
Can this not be be a static method in the cache control custom logger.
There was a problem hiding this comment.
Done in 9e55c19. Added AnthropicCacheControlHook.maybe_inject_cache_control(messages, system, kwargs) as a static method that handles extraction from kwargs + application + writing remaining points back. Both handler call sites are now a single line
…CacheControlHook Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Relevant issues
LIT-4122
Linear ticket
Resolves LIT-4122
Pre-Submission checklist
@greptileaiand received a Confidence Score of at least 4/5 before requesting a maintainer reviewScreenshots / Proof of Fix
Start proxy:
Send request with cache_control_injection_points:
Response (200 OK):
{ "model": "anthropic-haiku-4-5", "id": "msg_01KPkqmXbp6ASSzyVaQuJyYz", "type": "message", "role": "assistant", "content": [{"type": "text", "text": "2 + 2 = 4"}], "stop_reason": "end_turn", "usage": { "input_tokens": 25, "cache_creation_input_tokens": 0, "cache_read_input_tokens": 0, "output_tokens": 13 } }Debug log shows cache_control was injected on both system and user message in the outgoing Anthropic request:
(cache_creation_input_tokens is 0 because Anthropic requires 1024+ tokens for caching to actually activate; the important thing is the injection succeeded and Anthropic accepted the request)
Type
New Feature
Changes
Extends
cache_control_injection_pointsto the/v1/messagesendpoint (Anthropic native format). Previously only/v1/chat/completionswas supportedThe key difference from the chat completions path:
/v1/messageshassystemas a separate top-level parameter rather than a message in the array, and messages use Anthropic content-block format wherecache_controlgoes on content blocks (not the message object)Implementation:
AnthropicCacheControlHook.apply_to_anthropic_messages_request(messages, system, injection_points)splits injection points into system vs message targets, applies system injection (converting string system to content-block format with cache_control), normalizes any string message content to list format, then delegates message injection to the existing_apply_message_injections. Returns(messages, system, remaining_points)so tool_config points still flow to provider transformsanthropic_messages()(async) andanthropic_messages_handler()(sync) in the handler, after message sanitizationLink to Devin session: https://app.devin.ai/sessions/a5982e05ce1449a4a5a0a4d2c7cc9ff9
Requested by: @krrish-berri-2