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]

chore(caching): isolate semantic cache entries

user7bda5c7cac56
diff --git a/litellm/caching/qdrant_semantic_cache.py b/litellm/caching/qdrant_semantic_cache.py
index 5e3713e5a15..b856423cbb3 100644
--- a/litellm/caching/qdrant_semantic_cache.py
+++ b/litellm/caching/qdrant_semantic_cache.py
@@ -16,12 +16,17 @@ from typing import Any, cast
import litellm
from litellm._logging import print_verbose
from litellm.constants import QDRANT_SCALAR_QUANTILE, QDRANT_VECTOR_SIZE
+from litellm.litellm_core_utils.prompt_templates.common_utils import (
+ get_str_from_messages,
+)
from litellm.types.utils import EmbeddingResponse
from .base_cache import BaseCache
class QdrantSemanticCache(BaseCache):
+ CACHE_KEY_FIELD_NAME = "litellm_cache_key"
+
def __init__( # noqa: PLR0915
self,
qdrant_api_base=None,
@@ -170,15 +175,66 @@ class QdrantSemanticCache(BaseCache):
cached_response = ast.literal_eval(cached_response)
return cached_response
+ def _get_qdrant_cache_key_filter(self, key: str) -> dict:
+ return {
+ "must": [
+ {
+ "key": self.CACHE_KEY_FIELD_NAME,
+ "match": {"value": str(key)},
+ }
+ ]
+ }
+
+ def _payload_matches_cache_key(self, payload: dict, key: str) -> bool:
+ cached_key = payload.get(self.CACHE_KEY_FIELD_NAME)
+ return cached_key is not None and str(cached_key) == str(key)
+
+ async def _get_async_embedding(self, prompt: str, **kwargs) -> Any:
+ llm_model_list = None
+ llm_router = None
+
+ try:
+ from litellm.proxy.proxy_server import (
+ llm_model_list as proxy_llm_model_list,
+ llm_router as proxy_llm_router,
+ )
+
+ llm_model_list = proxy_llm_model_list
+ llm_router = proxy_llm_router
+ except ImportError:
+ pass
+
+ router_model_names = (
+ [m["model_name"] for m in llm_model_list]
+ if llm_model_list is not None
+ else []
+ )
+ if llm_router is not None and self.embedding_model in router_model_names:
+ user_api_key = kwargs.get("metadata", {}).get("user_api_key", "")
+ return await llm_router.aembedding(
+ model=self.embedding_model,
+ input=prompt,
+ cache={"no-store": True, "no-cache": True},
+ metadata={
+ "user_api_key": user_api_key,
+ "semantic-cache-embedding": True,
+ "trace_id": kwargs.get("metadata", {}).get("trace_id", None),
+ },
+ )
+
+ return await litellm.aembedding(
+ model=self.embedding_model,
+ input=prompt,
+ cache={"no-store": True, "no-cache": True},
+ )
+
def set_cache(self, key, value, **kwargs):
print_verbose(f"qdrant semantic-cache set_cache, kwargs: {kwargs}")
from litellm._uuid import uuid
# get the prompt
messages = kwargs["messages"]
- prompt = ""
- for message in messages:
- prompt += message["content"]
+ prompt = get_str_from_messages(messages)
# create an embedding for prompt
embedding_response = cast(
@@ -202,6 +258,7 @@ class QdrantSemanticCache(BaseCache):
"id": str(uuid.uuid4()),
"vector": embedding,
"payload": {
+ self.CACHE_KEY_FIELD_NAME: str(key),
"text": prompt,
"response": value,
},
@@ -220,9 +277,7 @@ class QdrantSemanticCache(BaseCache):
# get the messages
messages = kwargs["messages"]
- prompt = ""
- for message in messages:
- prompt += message["content"]
+ prompt = get_str_from_messages(messages)
# convert to embedding
embedding_response = cast(
@@ -248,6 +303,7 @@ class QdrantSemanticCache(BaseCache):
},
"limit": 1,
"with_payload": True,
+ "filter": self._get_qdrant_cache_key_filter(key),
}
search_response = self.sync_client.post(
@@ -264,7 +320,12 @@ class QdrantSemanticCache(BaseCache):
return None
similarity = results[0]["score"]
- cached_prompt = results[0]["payload"]["text"]
+ payload = results[0]["payload"]
+ if not self._payload_matches_cache_key(payload=payload, key=key):
+ print_verbose("Qdrant semantic-cache hit did not match cache key scope")
+ return None
+
+ cached_prompt = payload["text"]
# check similarity, if more than self.similarity_threshold, return results
print_verbose(
@@ -272,7 +333,7 @@ class QdrantSemanticCache(BaseCache):
)
if similarity >= self.similarity_threshold:
# cache hit !
- cached_value = results[0]["payload"]["response"]
+ cached_value = payload["response"]
print_verbose(
f"got a cache hit, similarity: {similarity}, Current prompt: {prompt}, cached_prompt: {cached_prompt}"
)
@@ -285,40 +346,12 @@ class QdrantSemanticCache(BaseCache):
async def async_set_cache(self, key, value, **kwargs):
from litellm._uuid import uuid
- from litellm.proxy.proxy_server import llm_model_list, llm_router
-
print_verbose(f"async qdrant semantic-cache set_cache, kwargs: {kwargs}")
# get the prompt
messages = kwargs["messages"]
- prompt = ""
- for message in messages:
- prompt += message["content"]
- # create an embedding for prompt
- router_model_names = (
- [m["model_name"] for m in llm_model_list]
- if llm_model_list is not None
- else []
- )
- if llm_router is not None and self.embedding_model in router_model_names:
- user_api_key = kwargs.get("metadata", {}).get("user_api_key", "")
- embedding_response = await llm_router.aembedding(
- model=self.embedding_model,
- input=prompt,
- cache={"no-store": True, "no-cache": True},
- metadata={
- "user_api_key": user_api_key,
- "semantic-cache-embedding": True,
- "trace_id": kwargs.get("metadata", {}).get("trace_id", None),
- },
- )
- else:
- # convert to embedding
- embedding_response = await litellm.aembedding(
- model=self.embedding_model,
- input=prompt,
- cache={"no-store": True, "no-cache": True},
- )
+ prompt = get_str_from_messages(messages)
+ embedding_response = await self._get_async_embedding(prompt, **kwargs)
# get the embedding
embedding = embedding_response["data"][0]["embedding"]
@@ -332,6 +365,7 @@ class QdrantSemanticCache(BaseCache):
"id": str(uuid.uuid4()),
"vector": embedding,
"payload": {
+ self.CACHE_KEY_FIELD_NAME: str(key),
"text": prompt,
"response": value,
},
@@ -348,38 +382,12 @@ class QdrantSemanticCache(BaseCache):
async def async_get_cache(self, key, **kwargs):
print_verbose(f"async qdrant semantic-cache get_cache, kwargs: {kwargs}")
- from litellm.proxy.proxy_server import llm_model_list, llm_router
# get the messages
messages = kwargs["messages"]
- prompt = ""
- for message in messages:
- prompt += message["content"]
+ prompt = get_str_from_messages(messages)
- router_model_names = (
- [m["model_name"] for m in llm_model_list]
- if llm_model_list is not None
- else []
- )
- if llm_router is not None and self.embedding_model in router_model_names:
- user_api_key = kwargs.get("metadata", {}).get("user_api_key", "")
- embedding_response = await llm_router.aembedding(
- model=self.embedding_model,
- input=prompt,
- cache={"no-store": True, "no-cache": True},
- metadata={
- "user_api_key": user_api_key,
- "semantic-cache-embedding": True,
- "trace_id": kwargs.get("metadata", {}).get("trace_id", None),
- },
- )
- else:
- # convert to embedding
- embedding_response = await litellm.aembedding(
- model=self.embedding_model,
- input=prompt,
- cache={"no-store": True, "no-cache": True},
- )
+ embedding_response = await self._get_async_embedding(prompt, **kwargs)
# get the embedding
embedding = embedding_response["data"][0]["embedding"]
@@ -395,6 +403,7 @@ class QdrantSemanticCache(BaseCache):
},
"limit": 1,
"with_payload": True,
+ "filter": self._get_qdrant_cache_key_filter(key),
}
search_response = await self.async_client.post(
@@ -414,7 +423,13 @@ class QdrantSemanticCache(BaseCache):
return None
similarity = results[0]["score"]
- cached_prompt = results[0]["payload"]["text"]
+ payload = results[0]["payload"]
+ if not self._payload_matches_cache_key(payload=payload, key=key):
+ print_verbose("Qdrant semantic-cache hit did not match cache key scope")
+ kwargs.setdefault("metadata", {})["semantic-similarity"] = 0.0
+ return None
+
+ cached_prompt = payload["text"]
# check similarity, if more than self.similarity_threshold, return results
print_verbose(
@@ -426,7 +441,7 @@ class QdrantSemanticCache(BaseCache):
if similarity >= self.similarity_threshold:
# cache hit !
- cached_value = results[0]["payload"]["response"]
+ cached_value = payload["response"]
print_verbose(
f"got a cache hit, similarity: {similarity}, Current prompt: {prompt}, cached_prompt: {cached_prompt}"
)
diff --git a/litellm/caching/redis_semantic_cache.py b/litellm/caching/redis_semantic_cache.py
index c76f27377d8..06e9b4d0fa9 100644
--- a/litellm/caching/redis_semantic_cache.py
+++ b/litellm/caching/redis_semantic_cache.py
@@ -35,6 +35,11 @@ class RedisSemanticCache(BaseCache):
"""
DEFAULT_REDIS_INDEX_NAME: str = "litellm_semantic_cache_index"
+ CACHE_KEY_FIELD_NAME: str = "litellm_cache_key"
+ CACHE_KEY_FILTERABLE_FIELD: Dict[str, str] = {
+ "name": CACHE_KEY_FIELD_NAME,
+ "type": "tag",
+ }
def __init__(
self,
@@ -66,8 +71,8 @@ class RedisSemanticCache(BaseCache):
Exception: If similarity_threshold is not provided or required Redis
connection information is missing
"""
- from redisvl.extensions.llmcache import SemanticCache
- from redisvl.utils.vectorize import CustomTextVectorizer
+ from redisvl.extensions.llmcache import SemanticCache # type: ignore[import-not-found, import-untyped]
+ from redisvl.utils.vectorize import CustomTextVectorizer # type: ignore[import-not-found, import-untyped]
if index_name is None:
index_name = self.DEFAULT_REDIS_INDEX_NAME
@@ -109,14 +114,61 @@ class RedisSemanticCache(BaseCache):
# Initialize the Redis vectorizer and cache
cache_vectorizer = CustomTextVectorizer(self._get_embedding)
- self.llmcache = SemanticCache(
- name=index_name,
+ self.llmcache = self._init_semantic_cache(
+ semantic_cache_cls=SemanticCache,
+ index_name=index_name,
redis_url=redis_url,
- vectorizer=cache_vectorizer,
- distance_threshold=self.distance_threshold,
- overwrite=False,
+ cache_vectorizer=cache_vectorizer,
)
+ def _init_semantic_cache(
+ self,
+ semantic_cache_cls: Any,
+ index_name: str,
+ redis_url: str,
+ cache_vectorizer: Any,
+ ) -> Any:
+ try:
+ return semantic_cache_cls(
+ name=index_name,
+ redis_url=redis_url,
+ vectorizer=cache_vectorizer,
+ distance_threshold=self.distance_threshold,
+ filterable_fields=[self.CACHE_KEY_FILTERABLE_FIELD],
+ overwrite=False,
+ )
+ except ValueError as exc:
+ if "schema does not match" not in str(exc):
+ raise
+
+ isolated_index_name = f"{index_name}_isolated"
+ print_verbose(
+ "Redis semantic-cache existing index schema is not isolated; "
+ f"using isolated index - {isolated_index_name}"
+ )
+ return semantic_cache_cls(
+ name=isolated_index_name,
+ redis_url=redis_url,
+ vectorizer=cache_vectorizer,
+ distance_threshold=self.distance_threshold,
+ filterable_fields=[self.CACHE_KEY_FILTERABLE_FIELD],
+ overwrite=False,
+ )
+
+ def _get_cache_filters(self, key: str) -> Dict[str, str]:
+ return {self.CACHE_KEY_FIELD_NAME: str(key)}
+
+ def _get_cache_key_filter_expression(self, key: str) -> Any:
+ from redisvl.query.filter import Tag # type: ignore[import-not-found, import-untyped]
+
+ return Tag(self.CACHE_KEY_FIELD_NAME) == str(key)
+
+ def _cache_hit_matches_key(self, cache_hit: Dict[str, Any], key: str) -> bool:
+ cached_key = cache_hit.get(self.CACHE_KEY_FIELD_NAME)
+ if isinstance(cached_key, bytes):
+ cached_key = cached_key.decode("utf-8")
+ return cached_key is not None and str(cached_key) == str(key)
+
def _get_ttl(self, **kwargs) -> Optional[int]:
"""
Get the TTL (time-to-live) value for cache entries.
@@ -188,7 +240,7 @@ class RedisSemanticCache(BaseCache):
Store a value in the semantic cache.
Args:
- key: The cache key (not directly used in semantic caching)
+ key: The cache key used to isolate semantic cache entries
value: The response value to cache
**kwargs: Additional arguments including 'messages' for the prompt
and optional 'ttl' for time-to-live
@@ -206,12 +258,15 @@ class RedisSemanticCache(BaseCache):
prompt = get_str_from_messages(messages)
value_str = str(value)
+ store_kwargs: Dict[str, Any] = {"filters": self._get_cache_filters(key)}
+
# Get TTL and store in Redis semantic cache
ttl = self._get_ttl(**kwargs)
if ttl is not None:
- self.llmcache.store(prompt, value_str, ttl=int(ttl))
+ store_kwargs["ttl"] = int(ttl)
+ self.llmcache.store(prompt, value_str, **store_kwargs)
else:
- self.llmcache.store(prompt, value_str)
+ self.llmcache.store(prompt, value_str, **store_kwargs)
except Exception as e:
print_verbose(
f"Error setting {value_str or value} in the Redis semantic cache: {str(e)}"
@@ -222,7 +277,7 @@ class RedisSemanticCache(BaseCache):
Retrieve a semantically similar cached response.
Args:
- key: The cache key (not directly used in semantic caching)
+ key: The cache key used to isolate semantic cache entries
**kwargs: Additional arguments including 'messages' for the prompt
Returns:
@@ -238,8 +293,12 @@ class RedisSemanticCache(BaseCache):
return None
prompt = get_str_from_messages(messages)
- # Check the cache for semantically similar prompts
- results = self.llmcache.check(prompt=prompt)
+ # Check the cache for semantically similar prompts in this exact
+ # LiteLLM cache-key scope.
+ results = self.llmcache.check(
+ prompt=prompt,
+ filter_expression=self._get_cache_key_filter_expression(key),
+ )
# Return None if no similar prompts found
if not results:
@@ -247,6 +306,9 @@ class RedisSemanticCache(BaseCache):
# Process the best matching result
cache_hit = results[0]
+ if not self._cache_hit_matches_key(cache_hit=cache_hit, key=key):
+ print_verbose("Redis semantic-cache hit did not match cache key scope")
+ return None
vector_distance = float(cache_hit["vector_distance"])
# Convert vector distance back to similarity score
@@ -321,7 +383,7 @@ class RedisSemanticCache(BaseCache):
Asynchronously store a value in the semantic cache.
Args:
- key: The cache key (not directly used in semantic caching)
+ key: The cache key used to isolate semantic cache entries
value: The response value to cache
**kwargs: Additional arguments including 'messages' for the prompt
and optional 'ttl' for time-to-live
@@ -341,20 +403,25 @@ class RedisSemanticCache(BaseCache):
# Generate embedding for the value (response) to cache
prompt_embedding = await self._get_async_embedding(prompt, **kwargs)
+ store_kwargs: Dict[str, Any] = {
+ "vector": prompt_embedding,
+ "filters": self._get_cache_filters(key),
+ }
+
# Get TTL and store in Redis semantic cache
ttl = self._get_ttl(**kwargs)
if ttl is not None:
+ store_kwargs["ttl"] = ttl
await self.llmcache.astore(
prompt,
value_str,
- vector=prompt_embedding, # Pass through custom embedding
- ttl=ttl,
+ **store_kwargs,
)
else:
await self.llmcache.astore(
prompt,
value_str,
- vector=prompt_embedding, # Pass through custom embedding
+ **store_kwargs,
)
except Exception as e:
print_verbose(f"Error in async_set_cache: {str(e)}")
@@ -364,7 +431,7 @@ class RedisSemanticCache(BaseCache):
Asynchronously retrieve a semantically similar cached response.
Args:
- key: The cache key (not directly used in semantic caching)
+ key: The cache key used to isolate semantic cache entries
**kwargs: Additional arguments including 'messages' for the prompt
Returns:
@@ -385,8 +452,13 @@ class RedisSemanticCache(BaseCache):
# Generate embedding for the prompt
prompt_embedding = await self._get_async_embedding(prompt, **kwargs)
- # Check the cache for semantically similar prompts
- results = await self.llmcache.acheck(prompt=prompt, vector=prompt_embedding)
+ # Check the cache for semantically similar prompts in this exact
+ # LiteLLM cache-key scope.
+ results = await self.llmcache.acheck(
+ prompt=prompt,
+ vector=prompt_embedding,
+ filter_expression=self._get_cache_key_filter_expression(key),
+ )
# handle results / cache hit
if not results:
@@ -396,6 +468,10 @@ class RedisSemanticCache(BaseCache):
return None
cache_hit = results[0]
+ if not self._cache_hit_matches_key(cache_hit=cache_hit, key=key):
+ print_verbose("Redis semantic-cache hit did not match cache key scope")
+ kwargs.setdefault("metadata", {})["semantic-similarity"] = 0.0
+ return None
vector_distance = float(cache_hit["vector_distance"])
# Convert vector distance back to similarity
diff --git a/tests/test_litellm/caching/test_qdrant_semantic_cache.py b/tests/test_litellm/caching/test_qdrant_semantic_cache.py
index 13dc4b5812c..f357d97341f 100644
--- a/tests/test_litellm/caching/test_qdrant_semantic_cache.py
+++ b/tests/test_litellm/caching/test_qdrant_semantic_cache.py
@@ -19,9 +19,7 @@ def test_qdrant_semantic_cache_initialization(monkeypatch):
patch(
"litellm.llms.custom_httpx.http_handler._get_httpx_client"
) as mock_sync_client,
- patch(
- "litellm.llms.custom_httpx.http_handler.get_async_httpx_client"
- ) as mock_async_client,
+ patch("litellm.llms.custom_httpx.http_handler.get_async_httpx_client"),
):
# Mock the collection exists check
@@ -67,9 +65,7 @@ def test_qdrant_semantic_cache_get_cache_hit():
patch(
"litellm.llms.custom_httpx.http_handler._get_httpx_client"
) as mock_sync_client,
- patch(
- "litellm.llms.custom_httpx.http_handler.get_async_httpx_client"
- ) as mock_async_client,
+ patch("litellm.llms.custom_httpx.http_handler.get_async_httpx_client"),
):
# Mock the collection exists check
@@ -98,6 +94,7 @@ def test_qdrant_semantic_cache_get_cache_hit():
"result": [
{
"payload": {
+ QdrantSemanticCache.CACHE_KEY_FIELD_NAME: "test_key",
"text": "What is the capital of France?", # Original prompt
"response": '{"id": "test-123", "choices": [{"message": {"content": "Paris is the capital of France."}}]}',
},
@@ -127,6 +124,67 @@ def test_qdrant_semantic_cache_get_cache_hit():
# Verify search was called
qdrant_cache.sync_client.post.assert_called()
+ assert qdrant_cache.sync_client.post.call_args.kwargs["json"]["filter"] == {
+ "must": [
+ {
+ "key": QdrantSemanticCache.CACHE_KEY_FIELD_NAME,
+ "match": {"value": "test_key"},
+ }
+ ]
+ }
+
+
+def test_qdrant_semantic_cache_rejects_unscoped_cache_hit():
+ """
+ Test QDRANT semantic cache rejects old or unscoped cache hits.
+ """
+ with (
+ patch(
+ "litellm.llms.custom_httpx.http_handler._get_httpx_client"
+ ) as mock_sync_client,
+ patch("litellm.llms.custom_httpx.http_handler.get_async_httpx_client"),
+ ):
+
+ mock_response = MagicMock()
+ mock_response.status_code = 200
+ mock_response.json.return_value = {"result": {"exists": True}}
+
+ mock_sync_client_instance = MagicMock()
+ mock_sync_client_instance.get.return_value = mock_response
+ mock_sync_client.return_value = mock_sync_client_instance
+
+ from litellm.caching.qdrant_semantic_cache import QdrantSemanticCache
+
+ qdrant_cache = QdrantSemanticCache(
+ collection_name="test_collection",
+ qdrant_api_base="http://test.qdrant.local",
+ qdrant_api_key="test_key",
+ similarity_threshold=0.8,
+ )
+
+ mock_search_response = MagicMock()
+ mock_search_response.status_code = 200
+ mock_search_response.json.return_value = {
+ "result": [
+ {
+ "payload": {
+ "text": "What is the capital of France?",
+ "response": '{"id": "test-123"}',
+ },
+ "score": 0.9,
+ }
+ ]
+ }
+ qdrant_cache.sync_client.post = MagicMock(return_value=mock_search_response)
+
+ with patch(
+ "litellm.embedding", return_value={"data": [{"embedding": [0.1, 0.2, 0.3]}]}
+ ):
+ result = qdrant_cache.get_cache(
+ key="test_key", messages=[{"content": "What is the capital of France?"}]
+ )
+
+ assert result is None
def test_qdrant_semantic_cache_get_cache_miss():
@@ -138,9 +196,7 @@ def test_qdrant_semantic_cache_get_cache_miss():
patch(
"litellm.llms.custom_httpx.http_handler._get_httpx_client"
) as mock_sync_client,
- patch(
- "litellm.llms.custom_httpx.http_handler.get_async_httpx_client"
- ) as mock_async_client,
+ patch("litellm.llms.custom_httpx.http_handler.get_async_httpx_client"),
):
# Mock the collection exists check
@@ -230,6 +286,7 @@ async def test_qdrant_semantic_cache_async_get_cache_hit():
"result": [
{
"payload": {
+ QdrantSemanticCache.CACHE_KEY_FIELD_NAME: "test_key",
"text": "What is the capital of Spain?", # Original prompt
"response": '{"id": "test-456", "choices": [{"message": {"content": "Madrid is the capital of Spain."}}]}',
},
@@ -262,6 +319,16 @@ async def test_qdrant_semantic_cache_async_get_cache_hit():
# Verify async search was called
qdrant_cache.async_client.post.assert_called()
+ assert qdrant_cache.async_client.post.call_args.kwargs["json"][
+ "filter"
+ ] == {
+ "must": [
+ {
+ "key": QdrantSemanticCache.CACHE_KEY_FIELD_NAME,
+ "match": {"value": "test_key"},
+ }
+ ]
+ }
@pytest.mark.asyncio
@@ -336,9 +403,7 @@ def test_qdrant_semantic_cache_set_cache():
patch(
"litellm.llms.custom_httpx.http_handler._get_httpx_client"
) as mock_sync_client,
- patch(
- "litellm.llms.custom_httpx.http_handler.get_async_httpx_client"
- ) as mock_async_client,
+ patch("litellm.llms.custom_httpx.http_handler.get_async_httpx_client"),
):
# Mock the collection exists check
@@ -384,6 +449,12 @@ def test_qdrant_semantic_cache_set_cache():
# Verify upsert was called
qdrant_cache.sync_client.put.assert_called()
+ upsert_payload = qdrant_cache.sync_client.put.call_args.kwargs["json"][
+ "points"
+ ][0]["payload"]
+ assert (
+ upsert_payload[QdrantSemanticCache.CACHE_KEY_FIELD_NAME] == "test_key"
+ )
@pytest.mark.asyncio
@@ -450,6 +521,12 @@ async def test_qdrant_semantic_cache_async_set_cache():
# Verify async upsert was called
qdrant_cache.async_client.put.assert_called()
+ upsert_payload = qdrant_cache.async_client.put.call_args.kwargs["json"][
+ "points"
+ ][0]["payload"]
+ assert (
+ upsert_payload[QdrantSemanticCache.CACHE_KEY_FIELD_NAME] == "test_key"
+ )
def test_qdrant_semantic_cache_custom_vector_size():
@@ -462,9 +539,7 @@ def test_qdrant_semantic_cache_custom_vector_size():
patch(
"litellm.llms.custom_httpx.http_handler._get_httpx_client"
) as mock_sync_client,
- patch(
- "litellm.llms.custom_httpx.http_handler.get_async_httpx_client"
- ) as mock_async_client,
+ patch("litellm.llms.custom_httpx.http_handler.get_async_httpx_client"),
):
# Mock the collection does NOT exist (so it will be created)
@@ -521,9 +596,7 @@ def test_qdrant_semantic_cache_default_vector_size():
patch(
"litellm.llms.custom_httpx.http_handler._get_httpx_client"
) as mock_sync_client,
- patch(
- "litellm.llms.custom_httpx.http_handler.get_async_httpx_client"
- ) as mock_async_client,
+ patch("litellm.llms.custom_httpx.http_handler.get_async_httpx_client"),
):
# Mock the collection exists check
@@ -559,9 +632,7 @@ def test_qdrant_semantic_cache_large_vector_size():
patch(
"litellm.llms.custom_httpx.http_handler._get_httpx_client"
) as mock_sync_client,
- patch(
- "litellm.llms.custom_httpx.http_handler.get_async_httpx_client"
- ) as mock_async_client,
+ patch("litellm.llms.custom_httpx.http_handler.get_async_httpx_client"),
):
# Mock the collection does NOT exist (so it will be created)
diff --git a/tests/test_litellm/caching/test_redis_semantic_cache.py b/tests/test_litellm/caching/test_redis_semantic_cache.py
index f9946e266fe..9f2f390f4e2 100644
--- a/tests/test_litellm/caching/test_redis_semantic_cache.py
+++ b/tests/test_litellm/caching/test_redis_semantic_cache.py
@@ -72,13 +72,22 @@ def test_redis_semantic_cache_get_cache(monkeypatch):
"prompt": "What is the capital of France?",
"response": '{"content": "Paris is the capital of France."}',
"vector_distance": 0.1, # Distance of 0.1 means similarity of 0.9
+ RedisSemanticCache.CACHE_KEY_FIELD_NAME: "test_key",
}
]
redis_semantic_cache.llmcache.check = MagicMock(return_value=mock_result)
# Mock the embedding function
- with patch(
- "litellm.embedding", return_value={"data": [{"embedding": [0.1, 0.2, 0.3]}]}
+ with (
+ patch(
+ "litellm.embedding",
+ return_value={"data": [{"embedding": [0.1, 0.2, 0.3]}]},
+ ),
+ patch.object(
+ redis_semantic_cache,
+ "_get_cache_key_filter_expression",
+ return_value="cache-key-filter",
+ ),
):
# Test get_cache with a message
result = redis_semantic_cache.get_cache(
@@ -89,7 +98,131 @@ def test_redis_semantic_cache_get_cache(monkeypatch):
assert result == {"content": "Paris is the capital of France."}
# Verify llmcache.check was called
- redis_semantic_cache.llmcache.check.assert_called_once()
+ redis_semantic_cache.llmcache.check.assert_called_once_with(
+ prompt="What is the capital of France?",
+ filter_expression="cache-key-filter",
+ )
+
+
+def test_redis_semantic_cache_rejects_unscoped_cache_hit(monkeypatch):
+ semantic_cache_mock = MagicMock()
+ custom_vectorizer_mock = MagicMock()
+
+ with patch.dict(
+ "sys.modules",
+ {
+ "redisvl.extensions.llmcache": MagicMock(SemanticCache=semantic_cache_mock),
+ "redisvl.utils.vectorize": MagicMock(
+ CustomTextVectorizer=custom_vectorizer_mock
+ ),
+ },
+ ):
+ from litellm.caching.redis_semantic_cache import RedisSemanticCache
+
+ monkeypatch.setenv("REDIS_HOST", "localhost")
+ monkeypatch.setenv("REDIS_PORT", "6379")
+ monkeypatch.setenv("REDIS_PASSWORD", "test_password")
+
+ redis_semantic_cache = RedisSemanticCache(similarity_threshold=0.8)
+ redis_semantic_cache.llmcache.check = MagicMock(
+ return_value=[
+ {
+ "prompt": "What is the capital of France?",
+ "response": '{"content": "Paris"}',
+ "vector_distance": 0.1,
+ }
+ ]
+ )
+
+ with patch.object(
+ redis_semantic_cache,
+ "_get_cache_key_filter_expression",
+ return_value="cache-key-filter",
+ ):
+ result = redis_semantic_cache.get_cache(
+ key="test_key",
+ messages=[{"content": "What is the capital of France?"}],
+ )
+
+ assert result is None
+
+
+def test_redis_semantic_cache_set_cache_stores_cache_key_filter(monkeypatch):
+ semantic_cache_mock = MagicMock()
+ custom_vectorizer_mock = MagicMock()
+
+ with patch.dict(
+ "sys.modules",
+ {
+ "redisvl.extensions.llmcache": MagicMock(SemanticCache=semantic_cache_mock),
+ "redisvl.utils.vectorize": MagicMock(
+ CustomTextVectorizer=custom_vectorizer_mock
+ ),
+ },
+ ):
+ from litellm.caching.redis_semantic_cache import RedisSemanticCache
+
+ monkeypatch.setenv("REDIS_HOST", "localhost")
+ monkeypatch.setenv("REDIS_PORT", "6379")
+ monkeypatch.setenv("REDIS_PASSWORD", "test_password")
+
+ redis_semantic_cache = RedisSemanticCache(similarity_threshold=0.8)
+ redis_semantic_cache.llmcache.store = MagicMock()
+
+ redis_semantic_cache.set_cache(
+ key="test_key",
+ value={"content": "Paris"},
+ messages=[{"content": "What is the capital of France?"}],
+ ttl=60,
+ )
+
+ redis_semantic_cache.llmcache.store.assert_called_once_with(
+ "What is the capital of France?",
+ "{'content': 'Paris'}",
+ filters={RedisSemanticCache.CACHE_KEY_FIELD_NAME: "test_key"},
+ ttl=60,
+ )
+
+
+def test_redis_semantic_cache_uses_isolated_index_for_old_schema(monkeypatch):
+ fallback_cache_mock = MagicMock()
+ semantic_cache_mock = MagicMock(
+ side_effect=[
+ ValueError("Existing index schema does not match"),
+ fallback_cache_mock,
+ ]
+ )
+ custom_vectorizer_mock = MagicMock()
+
+ with patch.dict(
+ "sys.modules",
+ {
+ "redisvl.extensions.llmcache": MagicMock(SemanticCache=semantic_cache_mock),
+ "redisvl.utils.vectorize": MagicMock(
+ CustomTextVectorizer=custom_vectorizer_mock
+ ),
+ },
+ ):
+ from litellm.caching.redis_semantic_cache import RedisSemanticCache
+
+ monkeypatch.setenv("REDIS_HOST", "localhost")
+ monkeypatch.setenv("REDIS_PORT", "6379")
+ monkeypatch.setenv("REDIS_PASSWORD", "test_password")
+
+ redis_semantic_cache = RedisSemanticCache(
+ similarity_threshold=0.8,
+ index_name="existing_index",
+ )
+
+ assert redis_semantic_cache.llmcache is fallback_cache_mock
+ assert semantic_cache_mock.call_args_list[0].kwargs["name"] == "existing_index"
+ assert (
+ semantic_cache_mock.call_args_list[1].kwargs["name"]
+ == "existing_index_isolated"
+ )
+ assert semantic_cache_mock.call_args_list[1].kwargs["filterable_fields"] == [
+ RedisSemanticCache.CACHE_KEY_FILTERABLE_FIELD
+ ]
@pytest.mark.asyncio
@@ -123,6 +256,7 @@ async def test_redis_semantic_cache_async_get_cache(monkeypatch):
"prompt": "What is the capital of France?",
"response": '{"content": "Paris is the capital of France."}',
"vector_distance": 0.1, # Distance of 0.1 means similarity of 0.9
+ RedisSemanticCache.CACHE_KEY_FIELD_NAME: "test_key",
}
]
@@ -131,16 +265,69 @@ async def test_redis_semantic_cache_async_get_cache(monkeypatch):
return_value=[0.1, 0.2, 0.3]
)
- # Test async_get_cache with a message
- result = await redis_semantic_cache.async_get_cache(
- key="test_key",
- messages=[{"content": "What is the capital of France?"}],
- metadata={},
- )
+ with patch.object(
+ redis_semantic_cache,
+ "_get_cache_key_filter_expression",
+ return_value="cache-key-filter",
+ ):
+ # Test async_get_cache with a message
+ result = await redis_semantic_cache.async_get_cache(
+ key="test_key",
+ messages=[{"content": "What is the capital of France?"}],
+ metadata={},
+ )
# Verify result is properly parsed
assert result == {"content": "Paris is the capital of France."}
# Verify methods were called
redis_semantic_cache._get_async_embedding.assert_called_once()
- redis_semantic_cache.llmcache.acheck.assert_called_once()
+ redis_semantic_cache.llmcache.acheck.assert_called_once_with(
+ prompt="What is the capital of France?",
+ vector=[0.1, 0.2, 0.3],
+ filter_expression="cache-key-filter",
+ )
+
+
+async def test_redis_semantic_cache_async_set_cache_stores_cache_key_filter(
+ monkeypatch,
+):
+ semantic_cache_mock = MagicMock()
+ custom_vectorizer_mock = MagicMock()
+
+ with patch.dict(
+ "sys.modules",
+ {
+ "redisvl.extensions.llmcache": MagicMock(SemanticCache=semantic_cache_mock),
+ "redisvl.utils.vectorize": MagicMock(
+ CustomTextVectorizer=custom_vectorizer_mock
+ ),
+ },
+ ):
+ from litellm.caching.redis_semantic_cache import RedisSemanticCache
+
+ monkeypatch.setenv("REDIS_HOST", "localhost")
+ monkeypatch.setenv("REDIS_PORT", "6379")
+ monkeypatch.setenv("REDIS_PASSWORD", "test_password")
+
+ redis_semantic_cache = RedisSemanticCache(similarity_threshold=0.8)
+ redis_semantic_cache.llmcache.astore = AsyncMock()
+ redis_semantic_cache._get_async_embedding = AsyncMock(
+ return_value=[0.1, 0.2, 0.3]
+ )
+
+ await redis_semantic_cache.async_set_cache(
+ key="test_key",
+ value={"content": "Paris"},
+ messages=[{"content": "What is the capital of France?"}],
+ ttl=60,
+ )
+
+ redis_semantic_cache.llmcache.astore.assert_called_once_with(
+ "What is the capital of France?",
+ "{'content': 'Paris'}",
+ vector=[0.1, 0.2, 0.3],
+ filters={RedisSemanticCache.CACHE_KEY_FIELD_NAME: "test_key"},
+ ttl=60,
+ )