Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
66 changes: 66 additions & 0 deletions litellm/caching/caching.py
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,8 @@ def __init__(
gcs_path: Optional[str] = None,
redis_semantic_cache_embedding_model: str = "text-embedding-ada-002",
redis_semantic_cache_index_name: Optional[str] = None,
valkey_semantic_cache_embedding_model: str = "text-embedding-ada-002",
valkey_semantic_cache_index_name: str | None = None,
redis_flush_size: Optional[int] = None,
redis_startup_nodes: Optional[List] = None,
disk_cache_dir: Optional[str] = None,
Expand Down Expand Up @@ -208,6 +210,21 @@ def __init__(
index_name=redis_semantic_cache_index_name,
**kwargs,
)
elif type == LiteLLMCacheType.VALKEY_SEMANTIC:
# Imported here, not at module top, so the optional redis dependency
# is only required when this backend is actually selected.
from .valkey_semantic_cache import ValkeySemanticCache

self.cache = ValkeySemanticCache(
host=host,
port=port,
password=password,
similarity_threshold=similarity_threshold,
embedding_model=valkey_semantic_cache_embedding_model,
index_name=valkey_semantic_cache_index_name,
startup_nodes=redis_startup_nodes,
**kwargs,
)
elif type == LiteLLMCacheType.QDRANT_SEMANTIC:
self.cache = QdrantSemanticCache(
qdrant_api_base=qdrant_api_base,
Expand Down Expand Up @@ -267,12 +284,50 @@ def __init__(
if (
self.type == LiteLLMCacheType.REDIS
or self.type == LiteLLMCacheType.REDIS_SEMANTIC
or self.type == LiteLLMCacheType.VALKEY_SEMANTIC
) and default_in_redis_ttl is not None:
self.ttl = default_in_redis_ttl

if self.namespace is not None and isinstance(self.cache, RedisCache):
self.cache.namespace = self.namespace

# Params whose values carry prompt content. Excluded from semantic-cache
# scope keys so differently worded prompts share a bucket and match via
# vector similarity rather than being split into per-wording buckets.
_SEMANTIC_CACHE_SCOPE_EXCLUDED_PARAMS: frozenset = frozenset(
{"messages", "prompt", "input"}
)

# Server-set identity (from proxy auth) used to isolate semantic-cache
# buckets per tenant. Required once the prompt is out of the scope key, so a
# similar prompt from another key/team/org stays in a separate bucket.
_SEMANTIC_CACHE_TENANT_SCOPE_FIELDS: tuple[str, ...] = (
"user_api_key",
"user_api_key_team_id",
"user_api_key_org_id",
)

def _is_semantic_cache(self) -> bool:
return self.type in (
LiteLLMCacheType.REDIS_SEMANTIC,
LiteLLMCacheType.QDRANT_SEMANTIC,
LiteLLMCacheType.VALKEY_SEMANTIC,
)

def _get_semantic_cache_tenant_scope(self, kwargs: dict) -> str:
metadata: dict = kwargs.get("metadata") or {}
litellm_params: dict = kwargs.get("litellm_params") or {}
metadata_in_litellm_params: dict = litellm_params.get("metadata") or {}

scope = ""
for field in self._SEMANTIC_CACHE_TENANT_SCOPE_FIELDS:
value = metadata.get(field)
if value is None:
value = metadata_in_litellm_params.get(field)
if value is not None:
scope += f"{field}: {value}"
return scope

def get_cache_key(self, **kwargs) -> str:
"""
Get the cache key for the given arguments.
Expand All @@ -293,7 +348,15 @@ def get_cache_key(self, **kwargs) -> str:

combined_kwargs = ModelParamHelper._get_all_llm_api_params()
litellm_param_kwargs = all_litellm_params
is_semantic_cache = self._is_semantic_cache()
scope_excluded_params = (
self._SEMANTIC_CACHE_SCOPE_EXCLUDED_PARAMS
if is_semantic_cache
else frozenset()
)
for param in kwargs:
if param in scope_excluded_params:
continue
if param in combined_kwargs:
param_value: Optional[str] = self._get_param_value(param, kwargs)
if param_value is not None:
Expand All @@ -309,6 +372,9 @@ def get_cache_key(self, **kwargs) -> str:
param_value = kwargs[param]
cache_key += f"{str(param)}: {str(param_value)}"

if is_semantic_cache:
cache_key += self._get_semantic_cache_tenant_scope(kwargs)
Comment on lines 294 to +376

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.

P1 Breaking scope-key change invalidates all existing redis-semantic and qdrant-semantic entries

get_cache_key() now excludes messages, prompt, and input from the hashed key for every semantic cache type — including the pre-existing redis-semantic and qdrant-semantic backends. Any instance that has been running one of those backends will find that every stored entry becomes permanently unreachable after upgrading: the SHA-256 scope tag changes for every document, so all KNN filter lookups miss indefinitely. Dropping the cache silently on upgrade violates the backwards-compatibility rule; the fix should be opt-in (e.g. litellm.semantic_cache_scope_fix = True) so operators can schedule the cold-start window. New valkey-semantic deployments are unaffected since they have no prior entries to lose.

Rule Used: What: avoid backwards-incompatible changes without... (source)

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.

Intentional, and I think a flag is the wrong call here.

The entries this invalidates were only ever reachable by a byte-identical prompt, because the prompt was baked into the scope key and the KNN filter required an exact key match, so semantic matching never actually ran. The warm cache that goes cold on upgrade therefore only held exact-prompt repeats, which is the single case where a semantic cache adds nothing over a plain exact cache. Keeping the old key format preserves nothing of value.

The impact is also self-healing and bounded. Semantic cache entries are TTL'd and best-effort: an orphaned entry sits until its TTL and expires, and a lookup miss just re-calls the provider, so there is no correctness impact and no data loss, only a one-time cold start for the remainder of the existing TTL. The new key additionally appends the authenticated tenant identity, so it is strictly more isolated than before, never less.

An opt-in flag would default every existing redis-semantic and qdrant-semantic deployment to the broken behavior, so semantic caching keeps silently not working until someone finds the flag, and it adds a second code path and config surface to preserve a cache state with no value. Defaulting to the correct behavior is the better trade. An operator who wants to reclaim the orphaned entries immediately can flush the index or shorten the TTL; otherwise it clears itself within one TTL.


hashed_cache_key = Cache._get_hashed_cache_key(cache_key)
hashed_cache_key = self._add_namespace_to_cache_key(hashed_cache_key, **kwargs)
verbose_logger.debug(
Expand Down
Loading
Loading