Skip to content

feat: add cache control injection support for v1/messages endpoint - #31778

Merged
krrish-berri-2 merged 4 commits into
litellm_internal_stagingfrom
litellm_cache_control_v1_messages_1782869152
Jul 1, 2026
Merged

krrish-berri-2 merged 4 commits into
litellm_internal_stagingfrom
litellm_cache_control_v1_messages_1782869152

Conversation

@devin-ai-integration

@devin-ai-integration devin-ai-integration Bot commented Jul 1, 2026 •

Copy link
Copy Markdown
Contributor

Relevant issues

LIT-4122

Linear ticket

Resolves LIT-4122

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 requested a Greptile review by commenting @greptileai and received a Confidence Score of at least 4/5 before requesting a maintainer review

Screenshots / Proof of Fix

Start proxy:

python litellm/proxy/proxy_cli.py --config litellm/proxy/dev_config.yaml --detailed_debug --port 4000

Send request with cache_control_injection_points:

curl -s -X POST http://localhost:4000/v1/messages \
  -H "Content-Type: application/json" \
  -H "x-api-key: sk-1234" \
  -d '{
    "model": "anthropic-haiku-4-5",
    "max_tokens": 100,
    "system": "You are a helpful assistant that answers concisely.",
    "messages": [
      {"role": "user", "content": "What is 2+2?"}
    ],
    "cache_control_injection_points": [
      {"location": "message", "role": "system"},
      {"location": "message", "index": -1}
    ]
  }'

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:

-d '{'messages': [{'role': 'user', 'content': [{'type': 'text', 'text': 'What is 2+2?', 'cache_control': {'type': 'ephemeral'}}]}],
'max_tokens': 100, 'model': 'claude-haiku-4-5', 'stream': False,
'system': [{'type': 'text', 'text': 'You are a helpful assistant that answers concisely.', 'cache_control': {'type': 'ephemeral'}}]}'

(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_points to the /v1/messages endpoint (Anthropic native format). Previously only /v1/chat/completions was supported

The key difference from the chat completions path: /v1/messages has system as a separate top-level parameter rather than a message in the array, and messages use Anthropic content-block format where cache_control goes 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 transforms
  • Called from both anthropic_messages() (async) and anthropic_messages_handler() (sync) in the handler, after message sanitization
  • Respects the 4-block Anthropic limit, counting pre-existing cache_control blocks on both system and messages before injecting

Link to Devin session: https://app.devin.ai/sessions/a5982e05ce1449a4a5a0a4d2c7cc9ff9
Requested by: @krrish-berri-2

Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
@krrish-berri-2 krrish-berri-2 self-assigned this Jul 1, 2026
@devin-ai-integration

Copy link
Copy Markdown
Contributor Author

🤖 Devin AI Engineer

I'll be helping with this pull request! Here's what you should know:

✅ I will automatically:

  • Address comments on this PR. Add '(aside)' to your comment to have me ignore it.
  • Look at CI failures and help fix them

Note: I can only respond to comments from users who have write access to this repository.

⚙️ Control Options:

  • Disable automatic comment, CI, and merge conflict monitoring

@codecov

codecov Bot commented Jul 1, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 90.00000% with 5 lines in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
...tellm/integrations/anthropic_cache_control_hook.py 89.13% 5 Missing ⚠️

📢 Thoughts on this report? Let us know!

@greptile-apps

greptile-apps Bot commented Jul 1, 2026

Copy link
Copy Markdown
Contributor

Greptile Summary

This PR extends cache_control_injection_points support from /v1/chat/completions to the /v1/messages (Anthropic native-format) endpoint. A new static method apply_to_anthropic_messages_request on AnthropicCacheControlHook splits injection points into system vs. message targets, converts a string system to a content-block list with cache_control, delegates message injection to the existing _apply_message_injections helper, and returns remaining tool_config points for downstream provider transforms.

  • Core logic: The block-budget arithmetic is correct — system blocks are counted separately, max_blocks - system_blocks_after is passed to _apply_message_injections, and the total never exceeds MAX_CACHE_CONTROL_BLOCKS.
  • Handler integration: Both the async and sync entry points pop and apply injection points; the async path handles message/system points first, then forwards tool_config remainders to the sync path, which processes them safely without double-injecting.
  • Tests: 10 new unit tests cover string/list system, role/index targeting, the 4-block cap, tool_config forwarding, immutability, and the system=None skip case — all mock-only with no network calls.

Confidence Score: 4/5

Safe to merge with low risk; the block-budget arithmetic is correct and the feature is additive. Two edge cases in _insert_cache_control_in_system and the used_blocks counter are worth cleaning up but do not affect normal usage.

The core injection logic, limit enforcement, and handler integration are all correct. Two non-blocking issues exist: _insert_cache_control_in_system mutates its list argument in place (safe only because callers always pass a deep copy, but a footgun for future callers), and used_blocks is incremented even when injection into an empty system list silently no-ops, which could drop one valid message injection slot. Neither issue affects real requests where system is a non-empty string or list.

litellm/integrations/anthropic_cache_control_hook.py — the new _insert_cache_control_in_system helper and the system injection loop in apply_to_anthropic_messages_request.

Important Files Changed

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

Comment on lines +243 to +252
@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

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 _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.

Suggested change
@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!

Comment on lines +295 to +304
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

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 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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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).

Comment on lines +239 to +240
messages, system, remaining_cc_points = AnthropicCacheControlHook.apply_to_anthropic_messages_request(
messages=messages,

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 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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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>

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.

this seems to add a ton of code. is this all needed? can it be made simpler, and better typed. (maybe check types/? )

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

# 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)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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>
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.

3 participants