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]

Merge branch 'main' into litellm_oss_staging_03_04_2026

Sameer Kankute3dab62023ca8
diff --cc tests/test_litellm/integrations/test_anthropic_cache_control_hook.py
index 4f0459d5eca,afeeb4a1ba6..26f9a6ee941
--- a/tests/test_litellm/integrations/test_anthropic_cache_control_hook.py
+++ b/tests/test_litellm/integrations/test_anthropic_cache_control_hook.py
@@@ -905,101 -905,73 +905,171 @@@ async def test_anthropic_cache_control_
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():
+ """
+ Test that cache_control_injection_points work for Gemini models.
+
+ Verifies the full flow:
+ 1. The hook injects cache_control markers on string-content messages
+ 2. is_cached_message() detects the injected markers (message-level cache_control)
+ 3. separate_cached_messages() correctly separates the messages
+
+ Fixes GitHub issue #18519.
+ """
+ from litellm.llms.vertex_ai.context_caching.transformation import (
+ separate_cached_messages,
+ )
+ from litellm.utils import is_cached_message
+
+ hook = AnthropicCacheControlHook()
+
+ # Simulate messages as they would appear for a Gemini call with string content
+ messages: List[AllMessageValues] = [
+ {
+ "role": "system",
+ "content": "You are a helpful assistant that analyzes legal documents.",
+ },
+ {
+ "role": "user",
+ "content": "What are the key terms?",
+ },
+ ]
+
+ # Simulate what the hook does: inject cache_control on the system message
+ injection_points = [{"location": "message", "role": "system"}]
+
+ # Manually apply the hook's logic for the system message (string content case)
+ # The hook sets message["cache_control"] = {"type": "ephemeral"} for string content
+ hook._safe_insert_cache_control_in_message(
+ message=messages[0],
+ control={"type": "ephemeral"},
+ )
+
+ # Verify the hook injected message-level cache_control (string content path)
+ assert messages[0].get("cache_control") == {"type": "ephemeral"}
+
+ # Verify is_cached_message detects message-level cache_control
+ assert is_cached_message(messages[0]) is True
+ assert is_cached_message(messages[1]) is False
+
+ # Verify separate_cached_messages correctly separates them
+ cached, non_cached = separate_cached_messages(messages)
+ assert len(cached) == 1
+ assert cached[0]["role"] == "system"
+ assert len(non_cached) == 1
+ assert non_cached[0]["role"] == "user"
+
+
+def test_gemini_cache_control_injection_list_content_detected():
+ """
+ Test that cache_control_injection_points work for Gemini models
+ when the message content is a list (not string).
+ """
+ from litellm.llms.vertex_ai.context_caching.transformation import (
+ separate_cached_messages,
+ )
+ from litellm.utils import is_cached_message
+
+ hook = AnthropicCacheControlHook()
+
+ messages: List[AllMessageValues] = [
+ {
+ "role": "system",
+ "content": [
+ {"type": "text", "text": "You are a helpful assistant."},
+ {"type": "text", "text": "Analyze legal documents carefully."},
+ ],
+ },
+ {
+ "role": "user",
+ "content": "What are the key terms?",
+ },
+ ]
+
+ # Apply the hook's logic for list content - sets cache_control on last item
+ hook._safe_insert_cache_control_in_message(
+ message=messages[0],
+ control={"type": "ephemeral"},
+ )
+
+ # Verify cache_control was set on the last content item
+ assert messages[0]["content"][-1]["cache_control"] == {"type": "ephemeral"}
+
+ # Verify is_cached_message detects content-item-level cache_control
+ assert is_cached_message(messages[0]) is True
+ assert is_cached_message(messages[1]) is False
+
+ # Verify separate_cached_messages correctly separates them
+ cached, non_cached = separate_cached_messages(messages)
+ assert len(cached) == 1
+ assert len(non_cached) == 1
+ @pytest.mark.asyncio
+ async def test_anthropic_cache_control_hook_string_negative_index():
+ """
+ Test that string negative indices like "-1" are handled correctly.
+
+ When cache_control_injection_points are stored in DB/config as JSON, indices
+ like -1 become the string "-1". Previously, str.isdigit() returned False for
+ "-1" so the cache control was silently skipped. This tests the fix.
+ """
+ with patch.dict(
+ os.environ,
+ {
+ "AWS_ACCESS_KEY_ID": "fake_access_key_id",
+ "AWS_SECRET_ACCESS_KEY": "fake_secret_access_key",
+ "AWS_REGION_NAME": "us-west-2",
+ },
+ ):
+ anthropic_cache_control_hook = AnthropicCacheControlHook()
+ litellm.callbacks = [anthropic_cache_control_hook]
+
+ mock_response = MagicMock()
+ mock_response.json.return_value = {
+ "output": {
+ "message": {
+ "role": "assistant",
+ "content": "Response",
+ }
+ },
+ "stopReason": "end_turn",
+ "usage": {
+ "inputTokens": 100,
+ "outputTokens": 50,
+ "totalTokens": 150,
+ },
+ }
+ mock_response.status_code = 200
+
+ client = AsyncHTTPHandler()
+ with patch.object(client, "post", return_value=mock_response) as mock_post:
+ await litellm.acompletion(
+ model="bedrock/us.anthropic.claude-3-7-sonnet-20250219-v1:0",
+ messages=[
+ {"role": "user", "content": "First message"},
+ {"role": "assistant", "content": "First response"},
+ {"role": "user", "content": "Second message"},
+ ],
+ # index is a string "-1" (as stored in DB/config JSON)
+ cache_control_injection_points=[
+ {"location": "message", "index": "-1"},
+ ],
+ client=client,
+ )
+
+ mock_post.assert_called_once()
+ request_body = json.loads(mock_post.call_args.kwargs["data"])
+
+ # 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 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)."
+ )