Skip to content

The fastest, litest AI Gateway. Rust core with Python SDK. Call 100+ LLM APIs in OpenAI (or native) format with cost tracking, guardrails, load balancing, and logging [Bedrock, Azure, OpenAI, Anthropic, OpenAI, VertexAI, vLLM, Nvidia NIM]

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

devin-ai-integration[bot]23af78465c87
diff --git a/litellm/integrations/anthropic_cache_control_hook.py b/litellm/integrations/anthropic_cache_control_hook.py
index 1314fd82255..608fdebc1d9 100644
--- a/litellm/integrations/anthropic_cache_control_hook.py
+++ b/litellm/integrations/anthropic_cache_control_hook.py
@@ -1,9 +1,12 @@
"""
-This hook is used to inject cache control directives into the messages of a chat completion.
+This hook is used to inject cache control directives into messages.
Users can define
- `cache_control_injection_points` in the completion params and litellm will inject the cache control directives into the messages at the specified injection points.
+Supported for both `v1/chat/completions` (via the prompt-management hook) and
+`v1/messages` (via `apply_to_anthropic_messages_request`).
+
"""
import copy
@@ -225,6 +228,98 @@ class AnthropicCacheControlHook(CustomPromptManagement):
message_content[-1]["cache_control"] = control # type: ignore
return message
+ @staticmethod
+ def apply_to_anthropic_messages_request(
+ messages: List[Dict],
+ system: str | list | None,
+ injection_points: List[CacheControlInjectionPoint],
+ ) -> Tuple[List[Dict], str | list | None, List[CacheControlInjectionPoint]]:
+ """Apply cache control injection for the Anthropic-native v1/messages endpoint.
+
+ Returns (messages, system, remaining_non_message_points).
+ """
+ if not injection_points:
+ return messages, system, []
+
+ processed_messages: List[Dict] = copy.deepcopy(messages)
+ processed_system = copy.deepcopy(system) if system is not None else None
+
+ message_points: List[CacheControlMessageInjectionPoint] = []
+ system_points: List[CacheControlMessageInjectionPoint] = []
+ remaining_points: List[CacheControlInjectionPoint] = []
+
+ for point in injection_points:
+ if point.get("location") == "message":
+ msg_point = cast(CacheControlMessageInjectionPoint, point)
+ if msg_point.get("role") == "system":
+ system_points.append(msg_point)
+ else:
+ message_points.append(msg_point)
+ else:
+ remaining_points.append(point)
+
+ reserved_blocks = 1 if any(p.get("location") == "tool_config" for p in remaining_points) else 0
+ max_blocks = MAX_CACHE_CONTROL_BLOCKS - reserved_blocks
+
+ used_blocks = sum(
+ AnthropicCacheControlHook._count_cache_control_blocks(cast(AllMessageValues, msg))
+ for msg in processed_messages
+ )
+ if isinstance(processed_system, list):
+ used_blocks += sum(
+ 1 for b in processed_system if isinstance(b, dict) and b.get("cache_control") is not None
+ )
+
+ if system_points and processed_system is not None and used_blocks < max_blocks:
+ system_already_has_cc = isinstance(processed_system, list) and any(
+ isinstance(b, dict) and b.get("cache_control") is not None for b in processed_system
+ )
+ if not system_already_has_cc:
+ control = system_points[0].get("control") or ChatCompletionCachedContent(type="ephemeral")
+ if isinstance(processed_system, str):
+ processed_system = [{"type": "text", "text": processed_system, "cache_control": control}]
+ used_blocks += 1
+ elif len(processed_system) > 0 and isinstance(processed_system[-1], dict):
+ processed_system[-1] = {**processed_system[-1], "cache_control": control}
+ used_blocks += 1
+
+ for i, msg in enumerate(processed_messages):
+ content = msg.get("content")
+ if isinstance(content, str):
+ processed_messages[i] = {**msg, "content": [{"type": "text", "text": content}]}
+
+ processed_messages = AnthropicCacheControlHook._apply_message_injections(
+ points=message_points,
+ messages=cast(List[AllMessageValues], processed_messages),
+ max_blocks=max_blocks - used_blocks,
+ )
+
+ return processed_messages, processed_system, remaining_points
+
+ @staticmethod
+ def maybe_inject_cache_control(
+ messages: List[Dict],
+ system: str | list | None,
+ kwargs: Dict[str, Any],
+ ) -> Tuple[List[Dict], str | list | None]:
+ """Extract cache_control_injection_points from kwargs and apply if present.
+
+ Pops the key from kwargs; if remaining (non-message) points exist they
+ are written back so downstream transforms can handle them.
+ """
+ injection_points = kwargs.pop("cache_control_injection_points", None)
+ if not injection_points:
+ return messages, system
+
+ messages, system, remaining = AnthropicCacheControlHook.apply_to_anthropic_messages_request(
+ messages=messages,
+ system=system,
+ injection_points=injection_points,
+ )
+ if remaining:
+ kwargs["cache_control_injection_points"] = remaining
+ return messages, system
+
@property
def integration_name(self) -> str:
"""Return the integration name for this hook."""
diff --git a/litellm/llms/anthropic/experimental_pass_through/messages/handler.py b/litellm/llms/anthropic/experimental_pass_through/messages/handler.py
index 547ddd9b8d3..effd7dda6a0 100644
--- a/litellm/llms/anthropic/experimental_pass_through/messages/handler.py
+++ b/litellm/llms/anthropic/experimental_pass_through/messages/handler.py
@@ -199,7 +199,7 @@ async def anthropic_messages(
metadata: Optional[Dict] = None,
stop_sequences: Optional[List[str]] = None,
stream: Optional[bool] = False,
- system: Optional[str] = None,
+ system: Optional[Union[str, list]] = None,
temperature: Optional[float] = None,
thinking: Optional[Dict] = None,
tool_choice: Optional[Dict] = None,
@@ -230,6 +230,12 @@ async def anthropic_messages(
# ids like ``functions.Bash:0`` that violate Anthropic's id pattern.
messages = sanitize_tool_use_ids_in_anthropic_messages(messages)
+ from litellm.integrations.anthropic_cache_control_hook import (
+ AnthropicCacheControlHook,
+ )
+
+ messages, system = AnthropicCacheControlHook.maybe_inject_cache_control(messages, system, kwargs)
+
original_stream = stream or kwargs.get("_websearch_interception_converted_stream", False)
# Execute pre-request hooks to allow CustomLoggers to modify request.
@@ -375,7 +381,7 @@ def anthropic_messages_handler(
metadata: Optional[Dict] = None,
stop_sequences: Optional[List[str]] = None,
stream: Optional[bool] = False,
- system: Optional[str] = None,
+ system: Optional[Union[str, list]] = None,
temperature: Optional[float] = None,
thinking: Optional[Dict] = None,
tool_choice: Optional[Dict] = None,
@@ -412,6 +418,12 @@ def anthropic_messages_handler(
messages = strip_empty_text_blocks_from_anthropic_messages(messages)
messages = sanitize_tool_use_ids_in_anthropic_messages(messages)
+ from litellm.integrations.anthropic_cache_control_hook import (
+ AnthropicCacheControlHook,
+ )
+
+ messages, system = AnthropicCacheControlHook.maybe_inject_cache_control(messages, system, kwargs)
+
metadata = validate_anthropic_api_metadata(metadata)
local_vars = locals()
diff --git a/tests/test_litellm/integrations/test_anthropic_cache_control_hook.py b/tests/test_litellm/integrations/test_anthropic_cache_control_hook.py
index 6afe5efc54d..4664cc86303 100644
--- a/tests/test_litellm/integrations/test_anthropic_cache_control_hook.py
+++ b/tests/test_litellm/integrations/test_anthropic_cache_control_hook.py
@@ -1,3 +1,4 @@
+import copy
import datetime
import json
import os
@@ -9,9 +10,7 @@ from unittest.mock import ANY, MagicMock, Mock, patch
import httpx
import pytest
-sys.path.insert(
- 0, os.path.abspath("../..")
-) # Adds the parent directory to the system-path
+sys.path.insert(0, os.path.abspath("../..")) # Adds the parent directory to the system-path
import litellm
from litellm.integrations.anthropic_cache_control_hook import AnthropicCacheControlHook
from litellm.llms.custom_httpx.http_handler import AsyncHTTPHandler
@@ -93,13 +92,9 @@ async def test_anthropic_cache_control_hook_system_message():
# Verify that cache control was applied (Bedrock transforms it to a separate item)
cache_control_count = sum(
- 1
- for item in request_body["system"]
- if isinstance(item, dict) and "cachePoint" in item
+ 1 for item in request_body["system"] if isinstance(item, dict) and "cachePoint" in item
)
- assert (
- cache_control_count == 1
- ), f"Expected exactly 1 cache control point, found {cache_control_count}"
+ assert cache_control_count == 1, f"Expected exactly 1 cache control point, found {cache_control_count}"
@pytest.mark.asyncio
@@ -171,9 +166,7 @@ async def test_anthropic_cache_control_hook_user_message():
print("request_body: ", json.dumps(request_body, indent=4))
# Verify the request body
- assert request_body["messages"][1]["content"][1]["cachePoint"] == {
- "type": "default"
- }
+ assert request_body["messages"][1]["content"][1]["cachePoint"] == {"type": "default"}
@pytest.mark.asyncio
@@ -262,14 +255,10 @@ async def test_anthropic_cache_control_hook_negative_indices():
# Verify the last message (input index -1 -> request index 2) has cache control
last_message_content = request_body["messages"][2]["content"]
- assert isinstance(
- last_message_content, list
- ), "Last message content should be a list"
- assert any(
- "cachePoint" in item
- for item in last_message_content
- if isinstance(item, dict)
- ), "CachePoint missing in last message"
+ assert isinstance(last_message_content, list), "Last message content should be a list"
+ assert any("cachePoint" in item for item in last_message_content if isinstance(item, dict)), (
+ "CachePoint missing in last message"
+ )
# Note: Based on debug output, the hook correctly applies cache control to both messages,
# but the Bedrock API transformation appears to only preserve cache control for user messages,
@@ -278,30 +267,20 @@ async def test_anthropic_cache_control_hook_negative_indices():
# The second-to-last message (assistant) gets cache_control from the hook but loses it
# during API transformation. This test documents this behavior.
second_last_message_content = request_body["messages"][1]["content"]
- assert isinstance(
- second_last_message_content, list
- ), "Second-to-last message content should be a list"
+ assert isinstance(second_last_message_content, list), "Second-to-last message content should be a list"
# Check if assistant message cache control is preserved (currently it's not)
assistant_has_cache_control = any(
- "cachePoint" in item
- for item in second_last_message_content
- if isinstance(item, dict)
- )
- print(
- f"Assistant message has cache control in final request: {assistant_has_cache_control}"
+ "cachePoint" in item for item in second_last_message_content if isinstance(item, dict)
)
+ print(f"Assistant message has cache control in final request: {assistant_has_cache_control}")
# Verify the first user message (request index 0) was NOT modified
first_user_message_content = request_body["messages"][0]["content"]
- assert isinstance(
- first_user_message_content, list
- ), "First user message content should be a list"
- assert not any(
- "cachePoint" in item
- for item in first_user_message_content
- if isinstance(item, dict)
- ), "CachePoint unexpectedly found in first user message"
+ assert isinstance(first_user_message_content, list), "First user message content should be a list"
+ assert not any("cachePoint" in item for item in first_user_message_content if isinstance(item, dict)), (
+ "CachePoint unexpectedly found in first user message"
+ )
@pytest.mark.asyncio
@@ -342,9 +321,7 @@ async def test_anthropic_cache_control_hook_out_of_bounds_logging():
client = AsyncHTTPHandler()
# Mock the verbose_logger to capture warning calls
- with patch(
- "litellm.integrations.anthropic_cache_control_hook.verbose_logger"
- ) as mock_logger:
+ with patch("litellm.integrations.anthropic_cache_control_hook.verbose_logger") as mock_logger:
with patch.object(client, "post", return_value=mock_response) as mock_post:
messages = [
{"role": "user", "content": "Message 1"},
@@ -354,9 +331,7 @@ async def test_anthropic_cache_control_hook_out_of_bounds_logging():
await litellm.acompletion(
model="bedrock/us.anthropic.claude-sonnet-4-5-20250929-v1:0",
messages=messages,
- cache_control_injection_points=[
- {"location": "message", "index": 10}
- ], # Out of bounds index
+ cache_control_injection_points=[{"location": "message", "index": 10}], # Out of bounds index
client=client,
)
@@ -365,10 +340,7 @@ async def test_anthropic_cache_control_hook_out_of_bounds_logging():
warning_call = mock_logger.warning.call_args[0][0]
# Check that the warning message contains the expected information
- assert (
- "AnthropicCacheControlHook: Provided index 10 is out of bounds"
- in warning_call
- )
+ assert "AnthropicCacheControlHook: Provided index 10 is out of bounds" in warning_call
assert "message list of length 2" in warning_call
assert "Targeted index was 10" in warning_call
assert "Skipping cache control injection for this point" in warning_call
@@ -411,9 +383,7 @@ async def test_anthropic_cache_control_hook_negative_out_of_bounds_logging():
client = AsyncHTTPHandler()
# Mock the verbose_logger to capture warning calls
- with patch(
- "litellm.integrations.anthropic_cache_control_hook.verbose_logger"
- ) as mock_logger:
+ with patch("litellm.integrations.anthropic_cache_control_hook.verbose_logger") as mock_logger:
with patch.object(client, "post", return_value=mock_response) as mock_post:
messages = [
{"role": "user", "content": "Single message"},
@@ -436,14 +406,9 @@ async def test_anthropic_cache_control_hook_negative_out_of_bounds_logging():
warning_call = mock_logger.warning.call_args[0][0]
# Check that the warning message contains the original negative index
- assert (
- "AnthropicCacheControlHook: Provided index -5 is out of bounds"
- in warning_call
- )
+ assert "AnthropicCacheControlHook: Provided index -5 is out of bounds" in warning_call
assert "message list of length 1" in warning_call
- assert (
- "Targeted index was -4" in warning_call
- ) # -5 + 1 = -4 (converted index)
+ assert "Targeted index was -4" in warning_call # -5 + 1 = -4 (converted index)
assert "Skipping cache control injection for this point" in warning_call
@@ -531,15 +496,11 @@ async def test_anthropic_cache_control_hook_multiple_user_messages():
# Count cache control points - should have 2 since both injection points were applied
cache_control_count = sum(
- 1
- for item in combined_message_content
- if isinstance(item, dict) and "cachePoint" in item
+ 1 for item in combined_message_content if isinstance(item, dict) and "cachePoint" in item
)
assert cache_control_count == 2
- print(
- f"Found {cache_control_count} cache control points in the combined message"
- )
+ print(f"Found {cache_control_count} cache control points in the combined message")
@pytest.mark.asyncio
@@ -588,9 +549,7 @@ async def test_anthropic_cache_control_hook_out_of_bounds(bad_index):
await litellm.acompletion(
model="bedrock/us.anthropic.claude-sonnet-4-5-20250929-v1:0",
messages=messages,
- cache_control_injection_points=[
- {"location": "message", "index": bad_index}
- ],
+ cache_control_injection_points=[{"location": "message", "index": bad_index}],
client=client,
)
@@ -601,19 +560,13 @@ async def test_anthropic_cache_control_hook_out_of_bounds(bad_index):
for msg in request_body["messages"]:
content = msg.get("content", [])
if isinstance(content, list):
- assert not any(
- "cachePoint" in item
- for item in content
- if isinstance(item, dict)
- )
+ assert not any("cachePoint" in item for item in content if isinstance(item, dict))
@pytest.mark.asyncio
@pytest.mark.parametrize(
"message_list",
- [
- [{"role": "user", "content": "Single message"}]
- ], # Single message only - empty list will fail at API level
+ [[{"role": "user", "content": "Single message"}]], # Single message only - empty list will fail at API level
)
async def test_anthropic_cache_control_hook_single_message(message_list):
"""
@@ -662,9 +615,7 @@ async def test_anthropic_cache_control_hook_single_message(message_list):
# For the single message, verify cache control was applied
content = request_body["messages"][0]["content"]
assert isinstance(content, list)
- assert any(
- "cachePoint" in item for item in content if isinstance(item, dict)
- )
+ assert any("cachePoint" in item for item in content if isinstance(item, dict))
@pytest.mark.asyncio
@@ -693,9 +644,7 @@ async def test_anthropic_cache_control_hook_empty_message_list():
await litellm.acompletion(
model="bedrock/us.anthropic.claude-sonnet-4-5-20250929-v1:0",
messages=[],
- cache_control_injection_points=[
- {"location": "message", "index": -1}
- ],
+ cache_control_injection_points=[{"location": "message", "index": -1}],
client=client,
)
@@ -755,11 +704,7 @@ async def test_anthropic_cache_control_hook_no_op():
for msg in request_body["messages"]:
content = msg.get("content", [])
if isinstance(content, list):
- assert not any(
- "cachePoint" in item
- for item in content
- if isinstance(item, dict)
- )
+ assert not any("cachePoint" in item for item in content if isinstance(item, dict))
@pytest.mark.asyncio
@@ -827,14 +772,10 @@ async def test_anthropic_cache_control_hook_multiple_content_items_last_only():
message_content = request_body["messages"][0]["content"]
assert isinstance(message_content, list)
- cache_control_count = sum(
- 1
- for item in message_content
- if isinstance(item, dict) and "cachePoint" in item
+ cache_control_count = sum(1 for item in message_content if isinstance(item, dict) and "cachePoint" in item)
+ assert cache_control_count == 1, (
+ f"Expected exactly 1 cache control point, found {cache_control_count}. This test verifies the fix for issue 15696 where cache_control was incorrectly applied to ALL content items."
)
- assert (
- cache_control_count == 1
- ), f"Expected exactly 1 cache control point, found {cache_control_count}. This test verifies the fix for issue 15696 where cache_control was incorrectly applied to ALL content items."
@pytest.mark.asyncio
@@ -891,30 +832,22 @@ async def test_anthropic_cache_control_hook_document_analysis_multiple_pages():
],
}
],
- cache_control_injection_points=[
- {"location": "message", "role": "user"}
- ],
+ cache_control_injection_points=[{"location": "message", "role": "user"}],
client=client,
)
mock_post.assert_called_once()
request_body = json.loads(mock_post.call_args.kwargs["data"])
- print(
- "Document analysis request_body: ", json.dumps(request_body, indent=4)
- )
+ print("Document analysis request_body: ", json.dumps(request_body, indent=4))
message_content = request_body["messages"][0]["content"]
assert isinstance(message_content, list)
- cache_control_count = sum(
- 1
- for item in message_content
- if isinstance(item, dict) and "cachePoint" in item
+ cache_control_count = sum(1 for item in message_content if isinstance(item, dict) and "cachePoint" in item)
+ assert cache_control_count == 1, (
+ f"Expected exactly 1 cache control point (last item only), found {cache_control_count}. Before fix, this would be 6 (one for each content item)."
)
- assert (
- cache_control_count == 1
- ), f"Expected exactly 1 cache control point (last item only), found {cache_control_count}. Before fix, this would be 6 (one for each content item)."
def test_gemini_cache_control_injection_points_detected():
@@ -1076,13 +1009,8 @@ async def test_anthropic_cache_control_hook_string_negative_index():
# The last user message should have cache control applied
last_message = request_body["messages"][-1]
last_message_content = last_message["content"]
- assert isinstance(
- last_message_content, list
- ), f"Expected list content, got {type(last_message_content)}"
- has_cache_point = any(
- isinstance(item, dict) and "cachePoint" in item
- for item in last_message_content
- )
+ assert isinstance(last_message_content, list), f"Expected list content, got {type(last_message_content)}"
+ has_cache_point = any(isinstance(item, dict) and "cachePoint" in item for item in last_message_content)
assert has_cache_point, (
f"Expected cachePoint in last message content, got: {last_message_content}. "
"String index '-1' was not parsed correctly (str.isdigit() returns False for negative strings)."
@@ -1146,17 +1074,13 @@ def test_cache_control_hook_caps_at_four_blocks_with_client_cache_control():
_, processed, _ = hook.get_chat_completion_prompt(
model="bedrock/us.anthropic.claude-opus-4-6-v1:0",
messages=messages,
- non_default_params={
- "cache_control_injection_points": _build_injection_points()
- },
+ non_default_params={"cache_control_injection_points": _build_injection_points()},
prompt_id=None,
prompt_variables=None,
dynamic_callback_params={},
)
- assert (
- _count_cache_control(processed) == 4
- ), "Hook must cap cache_control at Anthropic's limit of 4 blocks"
+ assert _count_cache_control(processed) == 4, "Hook must cap cache_control at Anthropic's limit of 4 blocks"
# Client TTL on system blocks must be preserved (not overwritten by config).
for i in range(4):
@@ -1170,11 +1094,7 @@ def test_cache_control_hook_caps_at_four_blocks_with_client_cache_control():
assert user_message.get("cache_control") is None
user_content = user_message.get("content")
if isinstance(user_content, list):
- assert all(
- block.get("cache_control") is None
- for block in user_content
- if isinstance(block, dict)
- )
+ assert all(block.get("cache_control") is None for block in user_content if isinstance(block, dict))
def test_cache_control_hook_caps_at_four_blocks_without_client_cache_control():
@@ -1184,17 +1104,13 @@ def test_cache_control_hook_caps_at_four_blocks_without_client_cache_control():
"""
hook = AnthropicCacheControlHook()
- messages: List[AllMessageValues] = [
- {"role": "system", "content": f"System {i}"} for i in range(4)
- ]
+ messages: List[AllMessageValues] = [{"role": "system", "content": f"System {i}"} for i in range(4)]
messages.append({"role": "user", "content": "hello"})
_, processed, _ = hook.get_chat_completion_prompt(
model="bedrock/us.anthropic.claude-opus-4-6-v1:0",
messages=messages,
- non_default_params={
- "cache_control_injection_points": _build_injection_points()
- },
+ non_default_params={"cache_control_injection_points": _build_injection_points()},
prompt_id=None,
prompt_variables=None,
dynamic_callback_params={},
@@ -1303,18 +1219,12 @@ async def test_cache_control_hook_bedrock_payload_caps_cachepoints_at_four():
request_body = json.loads(mock_post.call_args.kwargs["data"])
cache_points = sum(
- 1
- for block in request_body.get("system", [])
- if isinstance(block, dict) and "cachePoint" in block
+ 1 for block in request_body.get("system", []) if isinstance(block, dict) and "cachePoint" in block
)
for msg in request_body.get("messages", []):
content = msg.get("content", [])
if isinstance(content, list):
- cache_points += sum(
- 1
- for block in content
- if isinstance(block, dict) and "cachePoint" in block
- )
+ cache_points += sum(1 for block in content if isinstance(block, dict) and "cachePoint" in block)
assert cache_points <= 4, (
f"Bedrock payload exceeded Anthropic's 4 cache_control block limit: "
@@ -1331,9 +1241,7 @@ def test_cache_control_hook_reserves_slot_for_tool_config_point():
"""
hook = AnthropicCacheControlHook()
- messages: List[AllMessageValues] = [
- {"role": "system", "content": f"System {i}"} for i in range(4)
- ]
+ messages: List[AllMessageValues] = [{"role": "system", "content": f"System {i}"} for i in range(4)]
messages.append({"role": "user", "content": "hello"})
_, processed, non_default_params = hook.get_chat_completion_prompt(
@@ -1356,9 +1264,7 @@ def test_cache_control_hook_reserves_slot_for_tool_config_point():
assert _count_cache_control(processed) == 3
# The tool_config point is passed through for the provider transform.
- assert non_default_params["cache_control_injection_points"] == [
- {"location": "tool_config"}
- ]
+ assert non_default_params["cache_control_injection_points"] == [{"location": "tool_config"}]
@pytest.mark.asyncio
@@ -1384,9 +1290,7 @@ async def test_cache_control_hook_bedrock_payload_caps_with_tool_config_point():
client = AsyncHTTPHandler()
with patch.object(client, "post", return_value=mock_response) as mock_post:
- messages = [
- {"role": "system", "content": f"System block {i}"} for i in range(4)
- ]
+ messages = [{"role": "system", "content": f"System block {i}"} for i in range(4)]
messages.append({"role": "user", "content": "What is the weather?"})
await litellm.acompletion(
@@ -1421,18 +1325,12 @@ async def test_cache_control_hook_bedrock_payload_caps_with_tool_config_point():
request_body = json.loads(mock_post.call_args.kwargs["data"])
cache_points = sum(
- 1
- for block in request_body.get("system", [])
- if isinstance(block, dict) and "cachePoint" in block
+ 1 for block in request_body.get("system", []) if isinstance(block, dict) and "cachePoint" in block
)
for msg in request_body.get("messages", []):
content = msg.get("content", [])
if isinstance(content, list):
- cache_points += sum(
- 1
- for block in content
- if isinstance(block, dict) and "cachePoint" in block
- )
+ cache_points += sum(1 for block in content if isinstance(block, dict) and "cachePoint" in block)
for tool in request_body.get("toolConfig", {}).get("tools", []):
if isinstance(tool, dict) and "cachePoint" in tool:
cache_points += 1
@@ -1441,3 +1339,197 @@ async def test_cache_control_hook_bedrock_payload_caps_with_tool_config_point():
f"Bedrock payload exceeded Anthropic's 4 cache_control block limit "
f"when mixing message and tool_config injection: found {cache_points}"
)
+
+
+class TestApplyToAnthropicMessagesRequest:
+ """Tests for apply_to_anthropic_messages_request (v1/messages cache control)."""
+
+ def test_system_string_injection(self):
+ messages = [{"role": "user", "content": [{"type": "text", "text": "Hello"}]}]
+ system = "You are helpful"
+ injection_points = [{"location": "message", "role": "system"}]
+
+ result_msgs, result_sys, remaining = AnthropicCacheControlHook.apply_to_anthropic_messages_request(
+ messages=messages,
+ system=system,
+ injection_points=injection_points,
+ )
+
+ assert result_sys == [{"type": "text", "text": "You are helpful", "cache_control": {"type": "ephemeral"}}]
+ assert result_msgs == messages
+ assert remaining == []
+
+ def test_system_list_injection(self):
+ messages = [{"role": "user", "content": [{"type": "text", "text": "Hello"}]}]
+ system = [
+ {"type": "text", "text": "Part 1"},
+ {"type": "text", "text": "Part 2"},
+ ]
+ injection_points = [{"location": "message", "role": "system"}]
+
+ _, result_sys, _ = AnthropicCacheControlHook.apply_to_anthropic_messages_request(
+ messages=messages,
+ system=system,
+ injection_points=injection_points,
+ )
+
+ assert result_sys[0] == {"type": "text", "text": "Part 1"}
+ assert result_sys[1] == {"type": "text", "text": "Part 2", "cache_control": {"type": "ephemeral"}}
+
+ def test_user_message_injection_by_role(self):
+ messages = [
+ {"role": "user", "content": [{"type": "text", "text": "First"}]},
+ {"role": "assistant", "content": [{"type": "text", "text": "Response"}]},
+ {"role": "user", "content": [{"type": "text", "text": "Second"}]},
+ ]
+ injection_points = [{"location": "message", "role": "user"}]
+
+ result_msgs, _, _ = AnthropicCacheControlHook.apply_to_anthropic_messages_request(
+ messages=messages,
+ system=None,
+ injection_points=injection_points,
+ )
+
+ assert result_msgs[0]["content"][-1].get("cache_control") == {"type": "ephemeral"}
+ assert result_msgs[2]["content"][-1].get("cache_control") == {"type": "ephemeral"}
+ assert result_msgs[1]["content"][-1].get("cache_control") is None
+
+ def test_message_injection_by_index(self):
+ messages = [
+ {"role": "user", "content": [{"type": "text", "text": "First"}]},
+ {"role": "assistant", "content": [{"type": "text", "text": "Response"}]},
+ {"role": "user", "content": [{"type": "text", "text": "Second"}]},
+ ]
+ injection_points = [{"location": "message", "index": -1}]
+
+ result_msgs, _, _ = AnthropicCacheControlHook.apply_to_anthropic_messages_request(
+ messages=messages,
+ system=None,
+ injection_points=injection_points,
+ )
+
+ assert result_msgs[2]["content"][-1].get("cache_control") == {"type": "ephemeral"}
+ assert result_msgs[0]["content"][-1].get("cache_control") is None
+ assert result_msgs[1]["content"][-1].get("cache_control") is None
+
+ def test_mixed_system_and_message_injection(self):
+ messages = [
+ {"role": "user", "content": [{"type": "text", "text": "Hello"}]},
+ {"role": "assistant", "content": [{"type": "text", "text": "Hi"}]},
+ {"role": "user", "content": [{"type": "text", "text": "Question"}]},
+ ]
+ system = "System prompt"
+ injection_points = [
+ {"location": "message", "role": "system"},
+ {"location": "message", "index": -1},
+ ]
+
+ result_msgs, result_sys, _ = AnthropicCacheControlHook.apply_to_anthropic_messages_request(
+ messages=messages,
+ system=system,
+ injection_points=injection_points,
+ )
+
+ assert result_sys[0]["cache_control"] == {"type": "ephemeral"}
+ assert result_msgs[2]["content"][-1].get("cache_control") == {"type": "ephemeral"}
+
+ def test_respects_max_4_blocks(self):
+ messages = [{"role": "user", "content": [{"type": "text", "text": f"Msg {i}"}]} for i in range(6)]
+ system = "System"
+ injection_points = [
+ {"location": "message", "role": "system"},
+ {"location": "message", "role": "user"},
+ ]
+
+ result_msgs, result_sys, _ = AnthropicCacheControlHook.apply_to_anthropic_messages_request(
+ messages=messages,
+ system=system,
+ injection_points=injection_points,
+ )
+
+ sys_blocks = sum(1 for b in (result_sys or []) if isinstance(b, dict) and b.get("cache_control") is not None)
+ total_blocks = sys_blocks + sum(AnthropicCacheControlHook._count_cache_control_blocks(m) for m in result_msgs)
+ assert total_blocks <= 4
+
+ def test_tool_config_points_forwarded_as_remaining(self):
+ messages = [{"role": "user", "content": [{"type": "text", "text": "Hello"}]}]
+ injection_points = [
+ {"location": "message", "role": "user"},
+ {"location": "tool_config"},
+ ]
+
+ _, _, remaining = AnthropicCacheControlHook.apply_to_anthropic_messages_request(
+ messages=messages,
+ system=None,
+ injection_points=injection_points,
+ )
+
+ assert remaining == [{"location": "tool_config"}]
+
+ def test_no_injection_points_returns_unchanged(self):
+ messages = [{"role": "user", "content": [{"type": "text", "text": "Hello"}]}]
+ system = "System"
+
+ result_msgs, result_sys, remaining = AnthropicCacheControlHook.apply_to_anthropic_messages_request(
+ messages=messages,
+ system=system,
+ injection_points=[],
+ )
+
+ assert result_msgs == messages
+ assert result_sys == system
+ assert remaining == []
+
+ def test_does_not_mutate_input(self):
+ messages = [{"role": "user", "content": [{"type": "text", "text": "Hello"}]}]
+ system = [{"type": "text", "text": "System"}]
+ injection_points = [{"location": "message", "role": "system"}]
+
+ original_system = copy.deepcopy(system)
+ original_messages = copy.deepcopy(messages)
+
+ AnthropicCacheControlHook.apply_to_anthropic_messages_request(
+ messages=messages,
+ system=system,
+ injection_points=injection_points,
+ )
+
+ assert messages == original_messages
+ assert system == original_system
+
+ def test_system_none_with_system_point_skipped(self):
+ messages = [{"role": "user", "content": [{"type": "text", "text": "Hello"}]}]
+ injection_points = [{"location": "message", "role": "system"}]
+
+ result_msgs, result_sys, _ = AnthropicCacheControlHook.apply_to_anthropic_messages_request(
+ messages=messages,
+ system=None,
+ injection_points=injection_points,
+ )
+
+ assert result_sys is None
+
+ def test_existing_cache_control_counted_toward_limit(self):
+ messages = [
+ {"role": "user", "content": [{"type": "text", "text": "A", "cache_control": {"type": "ephemeral"}}]},
+ {"role": "assistant", "content": [{"type": "text", "text": "B", "cache_control": {"type": "ephemeral"}}]},
+ {"role": "user", "content": [{"type": "text", "text": "C", "cache_control": {"type": "ephemeral"}}]},
+ {"role": "user", "content": [{"type": "text", "text": "D"}]},
+ {"role": "user", "content": [{"type": "text", "text": "E"}]},
+ ]
+ system = "System"
+ injection_points = [
+ {"location": "message", "role": "system"},
+ {"location": "message", "index": 3},
+ {"location": "message", "index": 4},
+ ]
+
+ result_msgs, result_sys, _ = AnthropicCacheControlHook.apply_to_anthropic_messages_request(
+ messages=messages,
+ system=system,
+ injection_points=injection_points,
+ )
+
+ sys_blocks = sum(1 for b in (result_sys or []) if isinstance(b, dict) and b.get("cache_control") is not None)
+ total_blocks = sys_blocks + sum(AnthropicCacheControlHook._count_cache_control_blocks(m) for m in result_msgs)
+ assert total_blocks <= 4