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]
Python ai-gatewayanthropicazure-openaibedrockgatewaylangchainlitellmllmllm-gatewayllmopsmcp-gatewayopenaiopenai-proxyrustrust-aivertex-ai
[Feature]: Redis Caching - Allow setting a namespace for redis cache (#8624)
Ishaan Jaffd1ba04d9d96a
diff --git a/docs/my-website/docs/proxy/caching.md b/docs/my-website/docs/proxy/caching.mdindex 3f5342c7e60..b60b9966ba2 100644--- a/docs/my-website/docs/proxy/caching.md+++ b/docs/my-website/docs/proxy/caching.md@@ -2,7 +2,6 @@ import Tabs from '@theme/Tabs';import TabItem from '@theme/TabItem';# Caching-Cache LLM Responses:::note@@ -10,14 +9,19 @@ For OpenAI/Anthropic Prompt Caching, go [here](../completion/prompt_caching.md):::-LiteLLM supports:+Cache LLM Responses. LiteLLM's caching system stores and reuses LLM responses to save costs and reduce latency. When you make the same request twice, the cached response is returned instead of calling the LLM API again.++++### Supported Caches+- In Memory Cache- Redis Cache- Qdrant Semantic Cache- Redis Semantic Cache- s3 Bucket Cache-## Quick Start - Redis, s3 Cache, Semantic Cache+## Quick Start<Tabs><TabItem value="redis" label="redis cache">@@ -369,9 +373,9 @@ $ litellm --config /path/to/config.yaml</Tabs>+## Usage--## Using Caching - /chat/completions+### Basic<Tabs><TabItem value="chat_completions" label="/chat/completions">@@ -416,131 +420,84 @@ curl --location 'http://0.0.0.0:4000/embeddings' \</TabItem></Tabs>-## Set cache for proxy, but not on the actual llm api call+### Dynamic Cache Controls-Use this if you just want to enable features like rate limiting, and loadbalancing across multiple instances.+| Parameter | Type | Description |+|-----------|------|-------------|+| `ttl` | *Optional(int)* | Will cache the response for the user-defined amount of time (in seconds) |+| `s-maxage` | *Optional(int)* | Will only accept cached responses that are within user-defined range (in seconds) |+| `no-cache` | *Optional(bool)* | Will not store the response in cache. |+| `no-store` | *Optional(bool)* | Will not cache the response |+| `namespace` | *Optional(str)* | Will cache the response under a user-defined namespace |-Set `supported_call_types: []` to disable caching on the actual api call.+Each cache parameter can be controlled on a per-request basis. Here are examples for each parameter:+### `ttl`-```yaml-litellm_settings:- cache: True- cache_params:- type: redis- supported_call_types: []-```+Set how long (in seconds) to cache a response.+<Tabs>+<TabItem value="openai" label="OpenAI Python SDK">-## Debugging Caching - `/cache/ping`-LiteLLM Proxy exposes a `/cache/ping` endpoint to test if the cache is working as expected+```python+from openai import OpenAI-**Usage**-```shell-curl --location 'http://0.0.0.0:4000/cache/ping' -H "Authorization: Bearer sk-1234"-```+client = OpenAI(+ api_key="your-api-key",+ base_url="http://0.0.0.0:4000"+)-**Expected Response - when cache healthy**-```shell-{- "status": "healthy",- "cache_type": "redis",- "ping_response": true,- "set_cache_response": "success",- "litellm_cache_params": {- "supported_call_types": "['completion', 'acompletion', 'embedding', 'aembedding', 'atranscription', 'transcription']",- "type": "redis",- "namespace": "None"- },- "redis_cache_params": {- "redis_client": "Redis<ConnectionPool<Connection<host=redis-16337.c322.us-east-1-2.ec2.cloud.redislabs.com,port=16337,db=0>>>",- "redis_kwargs": "{'url': 'redis://:******@redis-16337.c322.us-east-1-2.ec2.cloud.redislabs.com:16337'}",- "async_redis_conn_pool": "BlockingConnectionPool<Connection<host=redis-16337.c322.us-east-1-2.ec2.cloud.redislabs.com,port=16337,db=0>>",- "redis_version": "7.2.0"+chat_completion = client.chat.completions.create(+ messages=[{"role": "user", "content": "Hello"}],+ model="gpt-3.5-turbo",+ extra_body={+ "cache": {+ "ttl": 300 # Cache response for 5 minutes+ }}-}+)```+</TabItem>-## Advanced--### Control Call Types Caching is on for - (`/chat/completion`, `/embeddings`, etc.)--By default, caching is on for all call types. You can control which call types caching is on for by setting `supported_call_types` in `cache_params`--**Cache will only be on for the call types specified in `supported_call_types`**--```yaml-litellm_settings:- cache: True- cache_params:- type: redis- supported_call_types: ["acompletion", "atext_completion", "aembedding", "atranscription"]- # /chat/completions, /completions, /embeddings, /audio/transcriptions-```-### Set Cache Params on config.yaml-```yaml-model_list:- - model_name: gpt-3.5-turbo- litellm_params:- model: gpt-3.5-turbo- - model_name: text-embedding-ada-002- litellm_params:- model: text-embedding-ada-002+<TabItem value="curl" label="curl">-litellm_settings:- set_verbose: True- cache: True # set cache responses to True, litellm defaults to using a redis cache- cache_params: # cache_params are optional- type: "redis" # The type of cache to initialize. Can be "local" or "redis". Defaults to "local".- host: "localhost" # The host address for the Redis cache. Required if type is "redis".- port: 6379 # The port number for the Redis cache. Required if type is "redis".- password: "your_password" # The password for the Redis cache. Required if type is "redis".-- # Optional configurations- supported_call_types: ["acompletion", "atext_completion", "aembedding", "atranscription"]- # /chat/completions, /completions, /embeddings, /audio/transcriptions+```shell+curl http://localhost:4000/v1/chat/completions \+ -H "Content-Type: application/json" \+ -H "Authorization: Bearer sk-1234" \+ -d '{+ "model": "gpt-3.5-turbo",+ "cache": {"ttl": 300},+ "messages": [+ {"role": "user", "content": "Hello"}+ ]+ }'```+</TabItem>+</Tabs>-### **Turn on / off caching per request. **--The proxy support 4 cache-controls:--- `ttl`: *Optional(int)* - Will cache the response for the user-defined amount of time (in seconds).-- `s-maxage`: *Optional(int)* Will only accept cached responses that are within user-defined range (in seconds).-- `no-cache`: *Optional(bool)* Will not return a cached response, but instead call the actual endpoint.-- `no-store`: *Optional(bool)* Will not cache the response.--[Let us know if you need more](https://github.com/BerriAI/litellm/issues/1218)--**Turn off caching**+### `s-maxage`-Set `no-cache=True`, this will not return a cached response+Only accept cached responses that are within the specified age (in seconds).<Tabs><TabItem value="openai" label="OpenAI Python SDK">```python-import osfrom openai import OpenAIclient = OpenAI(- # This is the default and can be omitted- api_key=os.environ.get("OPENAI_API_KEY"),- base_url="http://0.0.0.0:4000"+ api_key="your-api-key",+ base_url="http://0.0.0.0:4000")chat_completion = client.chat.completions.create(- messages=[- {- "role": "user",- "content": "Say this is a test",- }- ],+ messages=[{"role": "user", "content": "Hello"}],model="gpt-3.5-turbo",- extra_body = { # OpenAI python accepts extra args in extra_body- cache: {- "no-cache": True # will not return a cached response- }+ extra_body={+ "cache": {+ "s-maxage": 600 # Only use cache if less than 10 minutes old+ }})```@@ -554,47 +511,42 @@ curl http://localhost:4000/v1/chat/completions \-H "Authorization: Bearer sk-1234" \-d '{"model": "gpt-3.5-turbo",- "cache": {"no-cache": True},+ "cache": {"s-maxage": 600},"messages": [- {"role": "user", "content": "Say this is a test"}+ {"role": "user", "content": "Hello"}]}'```-</TabItem>-</Tabs>-**Turn on caching**--By default cache is always on+### `no-cache`+Force a fresh response, bypassing the cache.<Tabs><TabItem value="openai" label="OpenAI Python SDK">```python-import osfrom openai import OpenAIclient = OpenAI(- # This is the default and can be omitted- api_key=os.environ.get("OPENAI_API_KEY"),- base_url="http://0.0.0.0:4000"+ api_key="your-api-key",+ base_url="http://0.0.0.0:4000")chat_completion = client.chat.completions.create(- messages=[- {- "role": "user",- "content": "Say this is a test",+ messages=[{"role": "user", "content": "Hello"}],+ model="gpt-3.5-turbo",+ extra_body={+ "cache": {+ "no-cache": True # Skip cache check, get fresh response}- ],- model="gpt-3.5-turbo"+ })```</TabItem>-<TabItem value="curl on" label="curl">+<TabItem value="curl" label="curl">```shellcurl http://localhost:4000/v1/chat/completions \@@ -602,51 +554,44 @@ curl http://localhost:4000/v1/chat/completions \-H "Authorization: Bearer sk-1234" \-d '{"model": "gpt-3.5-turbo",+ "cache": {"no-cache": true},"messages": [- {"role": "user", "content": "Say this is a test"}+ {"role": "user", "content": "Hello"}]}'```-</TabItem>-</Tabs>-**Set `ttl`**+### `no-store`++Will not store the response in cache.-Set `ttl=600`, this will caches response for 10 minutes (600 seconds)<Tabs><TabItem value="openai" label="OpenAI Python SDK">```python-import osfrom openai import OpenAIclient = OpenAI(- # This is the default and can be omitted- api_key=os.environ.get("OPENAI_API_KEY"),- base_url="http://0.0.0.0:4000"+ api_key="your-api-key",+ base_url="http://0.0.0.0:4000")chat_completion = client.chat.completions.create(- messages=[- {- "role": "user",- "content": "Say this is a test",- }- ],+ messages=[{"role": "user", "content": "Hello"}],model="gpt-3.5-turbo",- extra_body = { # OpenAI python accepts extra args in extra_body- cache: {- "ttl": 600 # caches response for 10 minutes- }+ extra_body={+ "cache": {+ "no-store": True # Don't cache this response+ }})```</TabItem>-<TabItem value="curl on" label="curl">+<TabItem value="curl" label="curl">```shellcurl http://localhost:4000/v1/chat/completions \@@ -654,54 +599,42 @@ curl http://localhost:4000/v1/chat/completions \-H "Authorization: Bearer sk-1234" \-d '{"model": "gpt-3.5-turbo",- "cache": {"ttl": 600},+ "cache": {"no-store": true},"messages": [- {"role": "user", "content": "Say this is a test"}+ {"role": "user", "content": "Hello"}]}'```-</TabItem>-</Tabs>---**Set `s-maxage`**--Set `s-maxage`, this will only get responses cached within last 10 minutes+### `namespace`+Store the response under a specific cache namespace.<Tabs><TabItem value="openai" label="OpenAI Python SDK">```python-import osfrom openai import OpenAIclient = OpenAI(- # This is the default and can be omitted- api_key=os.environ.get("OPENAI_API_KEY"),- base_url="http://0.0.0.0:4000"+ api_key="your-api-key",+ base_url="http://0.0.0.0:4000")chat_completion = client.chat.completions.create(- messages=[- {- "role": "user",- "content": "Say this is a test",- }- ],+ messages=[{"role": "user", "content": "Hello"}],model="gpt-3.5-turbo",- extra_body = { # OpenAI python accepts extra args in extra_body- cache: {- "s-maxage": 600 # only get responses cached within last 10 minutes- }+ extra_body={+ "cache": {+ "namespace": "my-custom-namespace" # Store in custom namespace+ }})```</TabItem>-<TabItem value="curl on" label="curl">+<TabItem value="curl" label="curl">```shellcurl http://localhost:4000/v1/chat/completions \@@ -709,43 +642,100 @@ curl http://localhost:4000/v1/chat/completions \-H "Authorization: Bearer sk-1234" \-d '{"model": "gpt-3.5-turbo",- "cache": {"s-maxage": 600},+ "cache": {"namespace": "my-custom-namespace"},"messages": [- {"role": "user", "content": "Say this is a test"}+ {"role": "user", "content": "Hello"}]}'```-</TabItem>-</Tabs>-### Turn on / off caching per Key.-1. Add cache params when creating a key [full list](#turn-on--off-caching-per-key)+## Set cache for proxy, but not on the actual llm api call-```bash-curl -X POST 'http://0.0.0.0:4000/key/generate' \--H 'Authorization: Bearer sk-1234' \--H 'Content-Type: application/json' \--d '{- "user_id": "222",- "metadata": {- "cache": {- "no-cache": true- }+Use this if you just want to enable features like rate limiting, and loadbalancing across multiple instances.++Set `supported_call_types: []` to disable caching on the actual api call.+++```yaml+litellm_settings:+ cache: True+ cache_params:+ type: redis+ supported_call_types: []+```+++## Debugging Caching - `/cache/ping`+LiteLLM Proxy exposes a `/cache/ping` endpoint to test if the cache is working as expected++**Usage**+```shell+curl --location 'http://0.0.0.0:4000/cache/ping' -H "Authorization: Bearer sk-1234"+```++**Expected Response - when cache healthy**+```shell+{+ "status": "healthy",+ "cache_type": "redis",+ "ping_response": true,+ "set_cache_response": "success",+ "litellm_cache_params": {+ "supported_call_types": "['completion', 'acompletion', 'embedding', 'aembedding', 'atranscription', 'transcription']",+ "type": "redis",+ "namespace": "None"+ },+ "redis_cache_params": {+ "redis_client": "Redis<ConnectionPool<Connection<host=redis-16337.c322.us-east-1-2.ec2.cloud.redislabs.com,port=16337,db=0>>>",+ "redis_kwargs": "{'url': 'redis://:******@redis-16337.c322.us-east-1-2.ec2.cloud.redislabs.com:16337'}",+ "async_redis_conn_pool": "BlockingConnectionPool<Connection<host=redis-16337.c322.us-east-1-2.ec2.cloud.redislabs.com,port=16337,db=0>>",+ "redis_version": "7.2.0"}-}'+}```-2. Test it!+## Advanced++### Control Call Types Caching is on for - (`/chat/completion`, `/embeddings`, etc.)++By default, caching is on for all call types. You can control which call types caching is on for by setting `supported_call_types` in `cache_params`++**Cache will only be on for the call types specified in `supported_call_types`**-```bash-curl -X POST 'http://localhost:4000/chat/completions' \--H 'Content-Type: application/json' \--H 'Authorization: Bearer <YOUR_NEW_KEY>' \--d '{"model": "gpt-3.5-turbo", "messages": [{"role": "user", "content": "bom dia"}]}'+```yaml+litellm_settings:+ cache: True+ cache_params:+ type: redis+ supported_call_types: ["acompletion", "atext_completion", "aembedding", "atranscription"]+ # /chat/completions, /completions, /embeddings, /audio/transcriptions+```+### Set Cache Params on config.yaml+```yaml+model_list:+ - model_name: gpt-3.5-turbo+ litellm_params:+ model: gpt-3.5-turbo+ - model_name: text-embedding-ada-002+ litellm_params:+ model: text-embedding-ada-002++litellm_settings:+ set_verbose: True+ cache: True # set cache responses to True, litellm defaults to using a redis cache+ cache_params: # cache_params are optional+ type: "redis" # The type of cache to initialize. Can be "local" or "redis". Defaults to "local".+ host: "localhost" # The host address for the Redis cache. Required if type is "redis".+ port: 6379 # The port number for the Redis cache. Required if type is "redis".+ password: "your_password" # The password for the Redis cache. Required if type is "redis".++ # Optional configurations+ supported_call_types: ["acompletion", "atext_completion", "aembedding", "atranscription"]+ # /chat/completions, /completions, /embeddings, /audio/transcriptions```### Deleting Cache Keys - `/cache/delete`diff --git a/litellm/caching/caching.py b/litellm/caching/caching.pyindex 90e37b07db6..26f94a94c29 100644--- a/litellm/caching/caching.py+++ b/litellm/caching/caching.py@@ -277,9 +277,7 @@ class Cache:verbose_logger.debug("\nCreated cache key: %s", cache_key)hashed_cache_key = Cache._get_hashed_cache_key(cache_key)- hashed_cache_key = self._add_redis_namespace_to_cache_key(- hashed_cache_key, **kwargs- )+ hashed_cache_key = self._add_namespace_to_cache_key(hashed_cache_key, **kwargs)self._set_preset_cache_key_in_kwargs(preset_cache_key=hashed_cache_key, **kwargs)@@ -455,7 +453,7 @@ class Cache:verbose_logger.debug("Hashed cache key (SHA-256): %s", hash_hex)return hash_hex- def _add_redis_namespace_to_cache_key(self, hash_hex: str, **kwargs) -> str:+ def _add_namespace_to_cache_key(self, hash_hex: str, **kwargs) -> str:"""If a redis namespace is provided, add it to the cache key@@ -466,7 +464,12 @@ class Cache:Returns:str: The final hashed cache key with the redis namespace."""- namespace = kwargs.get("metadata", {}).get("redis_namespace") or self.namespace+ dynamic_cache_control: DynamicCacheControl = kwargs.get("cache", {})+ namespace = (+ dynamic_cache_control.get("namespace")+ or kwargs.get("metadata", {}).get("redis_namespace")+ or self.namespace+ )if namespace:hash_hex = f"{namespace}:{hash_hex}"verbose_logger.debug("Final hashed key: %s", hash_hex)@@ -546,11 +549,14 @@ class Cache:else:cache_key = self.get_cache_key(**kwargs)if cache_key is not None:- cache_control_args = kwargs.get("cache", {})- max_age = cache_control_args.get(- "s-max-age", cache_control_args.get("s-maxage", float("inf"))+ cache_control_args: DynamicCacheControl = kwargs.get("cache", {})+ max_age = (+ cache_control_args.get("s-maxage")+ or cache_control_args.get("s-max-age")+ or float("inf"))cached_result = self.cache.get_cache(cache_key, messages=messages)+ cached_result = self.cache.get_cache(cache_key, messages=messages)return self._get_cache_logic(cached_result=cached_result, max_age=max_age)diff --git a/litellm/types/caching.py b/litellm/types/caching.pyindex a6f9de3084e..bc05f1bd8d0 100644--- a/litellm/types/caching.py+++ b/litellm/types/caching.py@@ -33,3 +33,21 @@ class RedisPipelineIncrementOperation(TypedDict):key: strincrement_value: floatttl: Optional[int]+++DynamicCacheControl = TypedDict(+ "DynamicCacheControl",+ {+ # Will cache the response for the user-defined amount of time (in seconds).+ "ttl": Optional[int],+ # Namespace to use for caching+ "namespace": Optional[str],+ # Max Age to use for caching+ "s-maxage": Optional[int],+ "s-max-age": Optional[int],+ # Will not return a cached response, but instead call the actual endpoint.+ "no-cache": Optional[bool],+ # Will not store the response in the cache.+ "no-store": Optional[bool],+ },+)diff --git a/tests/local_testing/test_caching.py b/tests/local_testing/test_caching.pyindex 04110dae4e2..ae1e4d38c32 100644--- a/tests/local_testing/test_caching.py+++ b/tests/local_testing/test_caching.py@@ -2478,3 +2478,47 @@ async def test_redis_get_ttl():except Exception as e:print(f"Error occurred: {str(e)}")raise e+++def test_redis_caching_multiple_namespaces():+ """+ Test that redis caching works with multiple namespaces++ If client side request specifies a namespace, it should be used for caching++ The same request with different namespaces should not be cached under the same key+ """+ import uuid++ messages = [{"role": "user", "content": f"what is litellm? {uuid.uuid4()}"}]+ litellm.cache = Cache(type="redis")+ namespace_1 = "org-id1"+ namespace_2 = "org-id2"++ response_1 = completion(+ model="gpt-3.5-turbo", messages=messages, cache={"namespace": namespace_1}+ )++ response_2 = completion(+ model="gpt-3.5-turbo", messages=messages, cache={"namespace": namespace_2}+ )++ response_3 = completion(+ model="gpt-3.5-turbo", messages=messages, cache={"namespace": namespace_1}+ )++ response_4 = completion(model="gpt-3.5-turbo", messages=messages)++ print("response 1: ", response_1.model_dump_json(indent=4))+ print("response 2: ", response_2.model_dump_json(indent=4))+ print("response 3: ", response_3.model_dump_json(indent=4))+ print("response 4: ", response_4.model_dump_json(indent=4))++ # request 1 & 3 used under the same namespace+ assert response_1.id == response_3.id++ # request 2 used under a different namespace+ assert response_2.id != response_1.id++ # request 4 without a namespace should not be cached under the same key as request 3+ assert response_4.id != response_3.iddiff --git a/tests/local_testing/test_unit_test_caching.py b/tests/local_testing/test_unit_test_caching.pyindex 52007698eef..b1e8d4fe61e 100644--- a/tests/local_testing/test_unit_test_caching.py+++ b/tests/local_testing/test_unit_test_caching.py@@ -137,19 +137,28 @@ def test_get_hashed_cache_key():assert len(hashed_key) == 64 # SHA-256 produces a 64-character hex string-def test_add_redis_namespace_to_cache_key():+def test_add_namespace_to_cache_key():cache = Cache(namespace="test_namespace")hashed_key = "abcdef1234567890"# Test with class-level namespace- result = cache._add_redis_namespace_to_cache_key(hashed_key)+ result = cache._add_namespace_to_cache_key(hashed_key)assert result == "test_namespace:abcdef1234567890"# Test with metadata namespacekwargs = {"metadata": {"redis_namespace": "custom_namespace"}}- result = cache._add_redis_namespace_to_cache_key(hashed_key, **kwargs)+ result = cache._add_namespace_to_cache_key(hashed_key, **kwargs)assert result == "custom_namespace:abcdef1234567890"+ # Test with cache control namespace+ kwargs = {"cache": {"namespace": "cache_control_namespace"}}+ result = cache._add_namespace_to_cache_key(hashed_key, **kwargs)+ assert result == "cache_control_namespace:abcdef1234567890"++ kwargs = {"cache": {"namespace": "cache_control_namespace-2"}}+ result = cache._add_namespace_to_cache_key(hashed_key, **kwargs)+ assert result == "cache_control_namespace-2:abcdef1234567890"+def test_get_model_param_value():cache = Cache()