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]

[Fix] - Router's Cache: Fix routing for requests with same cacheable prefix but different user messages (#16951)

Alexsander Hamir6e70c279f84e
diff --git a/litellm/router_utils/prompt_caching_cache.py b/litellm/router_utils/prompt_caching_cache.py
index e9637f28605..dbf8b8fcba8 100644
--- a/litellm/router_utils/prompt_caching_cache.py
+++ b/litellm/router_utils/prompt_caching_cache.py
@@ -4,7 +4,7 @@ Wrapper around router cache. Meant to store model id when prompt caching support
import hashlib
import json
-from typing import TYPE_CHECKING, Any, List, Optional, Union
+from typing import TYPE_CHECKING, Any, List, Optional, Union, cast
from typing_extensions import TypedDict
@@ -52,6 +52,74 @@ class PromptCachingCache:
return obj # Keep primitive types as-is
return str(obj)
+ @staticmethod
+ def extract_cacheable_prefix(messages: List[AllMessageValues]) -> List[AllMessageValues]:
+ """
+ Extract the cacheable prefix from messages.
+
+ The cacheable prefix is everything UP TO AND INCLUDING the LAST content block
+ (across all messages) that has cache_control. This includes ALL blocks before
+ the last cacheable block (even if they don't have cache_control).
+
+ Args:
+ messages: List of messages to extract cacheable prefix from
+
+ Returns:
+ List of messages containing only the cacheable prefix
+ """
+ if not messages:
+ return messages
+
+ # Find the last content block (across all messages) that has cache_control
+ last_cacheable_message_idx = None
+ last_cacheable_content_idx = None
+
+ for msg_idx, message in enumerate(messages):
+ content = message.get("content")
+ if not isinstance(content, list):
+ continue
+
+ for content_idx, content_block in enumerate(content):
+ if isinstance(content_block, dict):
+ cache_control = content_block.get("cache_control")
+ if (
+ cache_control is not None
+ and isinstance(cache_control, dict)
+ and cache_control.get("type") == "ephemeral"
+ ):
+ last_cacheable_message_idx = msg_idx
+ last_cacheable_content_idx = content_idx
+
+ # If no cacheable block found, return empty list (no cacheable prefix)
+ if last_cacheable_message_idx is None:
+ return []
+
+ # Build the cacheable prefix: all messages up to and including the last cacheable message
+ cacheable_prefix = []
+
+ for msg_idx, message in enumerate(messages):
+ if msg_idx < last_cacheable_message_idx:
+ # Include entire message (comes before last cacheable block)
+ cacheable_prefix.append(message)
+ elif msg_idx == last_cacheable_message_idx:
+ # Include message but only up to and including the last cacheable content block
+ content = message.get("content")
+ if isinstance(content, list) and last_cacheable_content_idx is not None:
+ # Create a copy of the message with only cacheable content blocks
+ message_copy = cast(
+ AllMessageValues,
+ {**message, "content": content[: last_cacheable_content_idx + 1]},
+ )
+ cacheable_prefix.append(message_copy)
+ else:
+ # Content is not a list or cacheable content idx is None, include full message
+ cacheable_prefix.append(message)
+ else:
+ # Message comes after last cacheable block, don't include
+ break
+
+ return cacheable_prefix
+
@staticmethod
def get_prompt_caching_cache_key(
messages: Optional[List[AllMessageValues]],
@@ -59,10 +127,19 @@ class PromptCachingCache:
) -> Optional[str]:
if messages is None and tools is None:
return None
+
+ # Extract cacheable prefix from messages (only include up to last cache_control block)
+ cacheable_messages = None
+ if messages is not None:
+ cacheable_messages = PromptCachingCache.extract_cacheable_prefix(messages)
+ # If no cacheable prefix found, return None (can't cache)
+ if not cacheable_messages:
+ return None
+
# Use serialize_object for consistent and stable serialization
data_to_hash = {}
- if messages is not None:
- serialized_messages = PromptCachingCache.serialize_object(messages)
+ if cacheable_messages is not None:
+ serialized_messages = PromptCachingCache.serialize_object(cacheable_messages)
data_to_hash["messages"] = serialized_messages
if tools is not None:
serialized_tools = PromptCachingCache.serialize_object(tools)
@@ -89,6 +166,10 @@ class PromptCachingCache:
return None
cache_key = PromptCachingCache.get_prompt_caching_cache_key(messages, tools)
+ # If no cacheable prefix found, don't cache (can't generate cache key)
+ if cache_key is None:
+ return None
+
self.cache.set_cache(
cache_key, PromptCachingCacheValue(model_id=model_id), ttl=300
)
@@ -104,6 +185,10 @@ class PromptCachingCache:
return None
cache_key = PromptCachingCache.get_prompt_caching_cache_key(messages, tools)
+ # If no cacheable prefix found, don't cache (can't generate cache key)
+ if cache_key is None:
+ return None
+
await self.cache.async_set_cache(
cache_key,
PromptCachingCacheValue(model_id=model_id),
@@ -117,49 +202,23 @@ class PromptCachingCache:
tools: Optional[List[ChatCompletionToolParam]],
) -> Optional[PromptCachingCacheValue]:
"""
- if messages is not none
- - check full messages
- - check messages[:-1]
- - check messages[:-2]
- - check messages[:-3]
-
- use self.cache.async_batch_get_cache(keys=potential_cache_keys])
+ Get model ID from cache using the cacheable prefix.
+
+ The cache key is based on the cacheable prefix (everything up to and including
+ the last cache_control block), so requests with the same cacheable prefix but
+ different user messages will have the same cache key.
"""
if messages is None and tools is None:
return None
- # Generate potential cache keys by slicing messages
-
- potential_cache_keys = []
-
- if messages is not None:
- full_cache_key = PromptCachingCache.get_prompt_caching_cache_key(
- messages, tools
- )
- potential_cache_keys.append(full_cache_key)
-
- # Check progressively shorter message slices
- for i in range(1, min(4, len(messages))):
- partial_messages = messages[:-i]
- partial_cache_key = PromptCachingCache.get_prompt_caching_cache_key(
- partial_messages, tools
- )
- potential_cache_keys.append(partial_cache_key)
-
- # Perform batch cache lookup
- cache_results = await self.cache.async_batch_get_cache(
- keys=potential_cache_keys
- )
-
- if cache_results is None:
+ # Generate cache key using cacheable prefix
+ cache_key = PromptCachingCache.get_prompt_caching_cache_key(messages, tools)
+ if cache_key is None:
return None
- # Return the first non-None cache result
- for result in cache_results:
- if result is not None:
- return result
-
- return None
+ # Perform cache lookup
+ cache_result = await self.cache.async_get_cache(key=cache_key)
+ return cache_result
def get_model_id(
self,
@@ -170,4 +229,8 @@ class PromptCachingCache:
return None
cache_key = PromptCachingCache.get_prompt_caching_cache_key(messages, tools)
+ # If no cacheable prefix found, return None (can't cache)
+ if cache_key is None:
+ return None
+
return self.cache.get_cache(cache_key)
diff --git a/tests/router_unit_tests/test_router_prompt_caching.py b/tests/router_unit_tests/test_router_prompt_caching.py
index ca62f1e80d2..73469b8fe3b 100644
--- a/tests/router_unit_tests/test_router_prompt_caching.py
+++ b/tests/router_unit_tests/test_router_prompt_caching.py
@@ -1,6 +1,7 @@
import sys
import os
import traceback
+import asyncio
from dotenv import load_dotenv
from fastapi import Request
from datetime import datetime
@@ -64,3 +65,123 @@ def test_serialize_non_serializable():
obj = CustomClass()
serialized = PromptCachingCache.serialize_object(obj)
assert serialized == "custom_object" # Fallback to string conversion
+
+
+async def test_router_prompt_caching_same_cacheable_prefix_routes_to_same_deployment():
+ """
+ End-to-end test to validate prompt caching routing through LiteLLM Router.
+
+ Tests that requests with same cacheable content but different user messages
+ route to the same deployment (for prompt caching).
+
+ This reproduces the issue where requests with same cacheable prefix but different
+ user messages should route to the same deployment, but previously didn't because
+ the cache key included the entire messages array instead of just the cacheable prefix.
+ """
+ from litellm.types.llms.openai import AllMessageValues
+
+ def create_messages(user_content: str) -> list[AllMessageValues]:
+ """
+ Create messages matching the user's exact scenario.
+
+ Message structure:
+ - BLOCK 1: System message, first content block (no cache_control)
+ → INCLUDED (comes before the last cacheable block)
+ - BLOCK 2: System message, second content block (WITH cache_control)
+ → INCLUDED (this IS the last cacheable block)
+ - USER MESSAGE: User message (no cache_control)
+ → NOT included (comes after last cacheable block)
+ """
+ return [
+ {
+ "role": "system",
+ "content": [
+ # BLOCK 1: No cache_control → INCLUDED (all blocks up to last cacheable are included)
+ {"type": "text", "text": "You are an AI assistant tasked with analyzing legal documents."},
+ # BLOCK 2: Has cache_control → INCLUDED (this is the last cacheable block)
+ {
+ "type": "text",
+ "text": "Here 3 is the full text of a complex legal agreement" * 400,
+ "cache_control": {"type": "ephemeral"},
+ },
+ ],
+ },
+ {
+ "role": "user",
+ # USER MESSAGE: No cache_control → NOT included (comes after last cacheable block)
+ "content": user_content,
+ },
+ ]
+
+ # Create router with multiple deployments
+ router = Router(
+ model_list=[
+ {
+ "model_name": "test-model",
+ "litellm_params": {
+ "model": "gpt-3.5-turbo",
+ "api_base": "https://exampleopenaiendpoint-production-0ee2.up.railway.app/v1",
+ "api_key": f"test-key-{i}",
+ },
+ "model_info": {"id": f"deployment-{i}"},
+ }
+ for i in range(1, 4)
+ ],
+ routing_strategy="simple-shuffle",
+ optional_pre_call_checks=["prompt_caching"],
+ )
+
+ # Create test messages matching user's exact scenario
+ # Same cacheable prefix (system blocks 1+2) but different user messages
+ messages1 = create_messages("what are the key terms and conditions in this agreement?")
+ messages2 = create_messages("how many words are there?")
+ messages3 = create_messages("how many sentences are there?")
+
+ cache = PromptCachingCache(cache=router.cache)
+
+ # Test 1: Cache keys should be same (same cacheable prefix, different user messages)
+ key1 = PromptCachingCache.get_prompt_caching_cache_key(messages1, None)
+ key2 = PromptCachingCache.get_prompt_caching_cache_key(messages2, None)
+ key3 = PromptCachingCache.get_prompt_caching_cache_key(messages3, None)
+
+ assert key1 is not None, "Cache key should not be None"
+ assert key1 == key2 == key3, "Cache keys should be the same for same cacheable prefix"
+
+ # Make first request
+ try:
+ response1 = await router.acompletion(model="test-model", messages=messages1)
+ model_id_1 = response1._hidden_params.get("model_id", "unknown")
+ except Exception:
+ # If API call fails, we can still test the cache key logic
+ model_id_1 = "unknown"
+
+ await asyncio.sleep(1) # Wait for cache write
+
+ # Test 2: Cache lookup should work for messages2 (same cacheable prefix)
+ cached_2 = await cache.async_get_model_id(messages2, None)
+ # Cache should be found if first request succeeded
+ if model_id_1 != "unknown":
+ assert cached_2 is not None, "Cache lookup should work for same cacheable prefix"
+
+ # Make second request
+ try:
+ response2 = await router.acompletion(model="test-model", messages=messages2)
+ model_id_2 = response2._hidden_params.get("model_id", "unknown")
+ except Exception:
+ model_id_2 = "unknown"
+
+ await asyncio.sleep(1) # Wait for cache write
+
+ # Make third request
+ try:
+ response3 = await router.acompletion(model="test-model", messages=messages3)
+ model_id_3 = response3._hidden_params.get("model_id", "unknown")
+ except Exception:
+ model_id_3 = "unknown"
+
+ # Test 3: All requests should route to same deployment (if API calls succeeded)
+ if model_id_1 != "unknown" and model_id_2 != "unknown" and model_id_3 != "unknown":
+ assert (
+ model_id_1 == model_id_2 == model_id_3
+ ), f"All requests should route to same deployment, but got: {model_id_1}, {model_id_2}, {model_id_3}"