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]

Add GCS bucket caching support (#13122)

Pascal Broa17d483c89ea
diff --git a/docs/my-website/docs/caching/all_caches.md b/docs/my-website/docs/caching/all_caches.md
index a6be3396291..e3bf363e67d 100644
--- a/docs/my-website/docs/caching/all_caches.md
+++ b/docs/my-website/docs/caching/all_caches.md
@@ -1,7 +1,7 @@
import Tabs from '@theme/Tabs';
import TabItem from '@theme/TabItem';
-# Caching - In-Memory, Redis, s3, Redis Semantic Cache, Disk
+# Caching - In-Memory, Redis, s3, gcs, Redis Semantic Cache, Disk
[**See Code**](https://github.com/BerriAI/litellm/blob/main/litellm/caching/caching.py)
@@ -14,7 +14,7 @@ import TabItem from '@theme/TabItem';
:::
-## Initialize Cache - In Memory, Redis, s3 Bucket, Redis Semantic, Disk Cache, Qdrant Semantic
+## Initialize Cache - In Memory, Redis, s3 Bucket, gcs Bucket, Redis Semantic, Disk Cache, Qdrant Semantic
<Tabs>
@@ -50,6 +50,36 @@ response2 = completion(
</TabItem>
+<TabItem value="gcs" label="gcs-cache">
+
+Set environment variables
+
+```shell
+GCS_BUCKET_NAME="my-cache-bucket"
+GCS_PATH_SERVICE_ACCOUNT="/path/to/service_account.json"
+```
+
+```python
+import litellm
+from litellm import completion
+from litellm.caching.caching import Cache
+
+litellm.cache = Cache(type="gcs", gcs_bucket_name="my-cache-bucket", gcs_path_service_account="/path/to/service_account.json")
+
+response1 = completion(
+ model="gpt-3.5-turbo",
+ messages=[{"role": "user", "content": "Tell me a joke."}]
+)
+response2 = completion(
+ model="gpt-3.5-turbo",
+ messages=[{"role": "user", "content": "Tell me a joke."}]
+)
+
+# response1 == response2, response 1 is cached
+```
+
+</TabItem>
+
<TabItem value="s3" label="s3-cache">
@@ -405,7 +435,7 @@ Advanced Params
```python
litellm.enable_cache(
- type: Optional[Literal["local", "redis", "s3", "disk"]] = "local",
+ type: Optional[Literal["local", "redis", "s3", "gcs", "disk"]] = "local",
host: Optional[str] = None,
port: Optional[str] = None,
password: Optional[str] = None,
@@ -429,7 +459,7 @@ Update the Cache params
```python
litellm.update_cache(
- type: Optional[Literal["local", "redis", "s3", "disk"]] = "local",
+ type: Optional[Literal["local", "redis", "s3", "gcs", "disk"]] = "local",
host: Optional[str] = None,
port: Optional[str] = None,
password: Optional[str] = None,
@@ -490,7 +520,7 @@ cache.get_cache = get_cache
```python
def __init__(
self,
- type: Optional[Literal["local", "redis", "redis-semantic", "s3", "disk"]] = "local",
+ type: Optional[Literal["local", "redis", "redis-semantic", "s3", "gcs", "disk"]] = "local",
supported_call_types: Optional[
List[Literal["completion", "acompletion", "embedding", "aembedding", "atranscription", "transcription"]]
] = ["completion", "acompletion", "embedding", "aembedding", "atranscription", "transcription"],
diff --git a/litellm/caching/__init__.py b/litellm/caching/__init__.py
index badc462e09b..bbe90b04121 100644
--- a/litellm/caching/__init__.py
+++ b/litellm/caching/__init__.py
@@ -7,4 +7,5 @@ from .qdrant_semantic_cache import QdrantSemanticCache
from .redis_cache import RedisCache
from .redis_cluster_cache import RedisClusterCache
from .redis_semantic_cache import RedisSemanticCache
-from .s3_cache import S3Cache
\ No newline at end of file
+from .s3_cache import S3Cache
+from .gcs_cache import GCSCache
diff --git a/litellm/caching/caching.py b/litellm/caching/caching.py
index 6959467cddd..8416790edb1 100644
--- a/litellm/caching/caching.py
+++ b/litellm/caching/caching.py
@@ -34,6 +34,7 @@ from .redis_cache import RedisCache
from .redis_cluster_cache import RedisClusterCache
from .redis_semantic_cache import RedisSemanticCache
from .s3_cache import S3Cache
+from .gcs_cache import GCSCache
def print_verbose(print_statement):
@@ -92,6 +93,9 @@ class Cache:
s3_aws_session_token: Optional[str] = None,
s3_config: Optional[Any] = None,
s3_path: Optional[str] = None,
+ gcs_bucket_name: Optional[str] = None,
+ gcs_path_service_account: Optional[str] = None,
+ gcs_path: Optional[str] = None,
redis_semantic_cache_embedding_model: str = "text-embedding-ada-002",
redis_semantic_cache_index_name: Optional[str] = None,
redis_flush_size: Optional[int] = None,
@@ -140,6 +144,11 @@ class Cache:
s3_aws_session_token (str, optional): The aws session token for the s3 cache. Defaults to None.
s3_config (dict, optional): The config for the s3 cache. Defaults to None.
+ # GCS Cache Args
+ gcs_bucket_name (str, optional): The bucket name for the gcs cache. Defaults to None.
+ gcs_path_service_account (str, optional): Path to the service account json.
+ gcs_path (str, optional): Folder path inside the bucket to store cache files.
+
# Common Cache Args
supported_call_types (list, optional): List of call types to cache for. Defaults to cache == on for all call types.
**kwargs: Additional keyword arguments for redis.Redis() cache
@@ -204,6 +213,12 @@ class Cache:
s3_path=s3_path,
**kwargs,
)
+ elif type == LiteLLMCacheType.GCS:
+ self.cache = GCSCache(
+ bucket_name=gcs_bucket_name,
+ path_service_account=gcs_path_service_account,
+ gcs_path=gcs_path,
+ )
elif type == LiteLLMCacheType.AZURE_BLOB:
self.cache = AzureBlobCache(
account_url=azure_account_url,
diff --git a/litellm/caching/gcs_cache.py b/litellm/caching/gcs_cache.py
new file mode 100644
index 00000000000..88857ba0e70
--- /dev/null
+++ b/litellm/caching/gcs_cache.py
@@ -0,0 +1,97 @@
+"""GCS Cache implementation
+Supports syncing responses to Google Cloud Storage Buckets using HTTP requests.
+"""
+import json
+import asyncio
+from typing import Optional
+
+from litellm._logging import print_verbose, verbose_logger
+from litellm.integrations.gcs_bucket.gcs_bucket_base import GCSBucketBase
+from litellm.llms.custom_httpx.http_handler import (
+ get_async_httpx_client,
+ _get_httpx_client,
+ httpxSpecialProvider,
+)
+from .base_cache import BaseCache
+
+
+class GCSCache(BaseCache):
+ def __init__(self, bucket_name: Optional[str] = None, path_service_account: Optional[str] = None, gcs_path: Optional[str] = None) -> None:
+ super().__init__()
+ self.bucket_name = bucket_name or GCSBucketBase(bucket_name=None).BUCKET_NAME
+ self.path_service_account = path_service_account or GCSBucketBase(bucket_name=None).path_service_account_json
+ self.key_prefix = gcs_path.rstrip("/") + "/" if gcs_path else ""
+ # create httpx clients
+ self.async_client = get_async_httpx_client(llm_provider=httpxSpecialProvider.LoggingCallback)
+ self.sync_client = _get_httpx_client()
+
+ def _construct_headers(self) -> dict:
+ base = GCSBucketBase(bucket_name=self.bucket_name)
+ base.path_service_account_json = self.path_service_account
+ base.BUCKET_NAME = self.bucket_name
+ return base.sync_construct_request_headers()
+
+ def set_cache(self, key, value, **kwargs):
+ try:
+ print_verbose(f"LiteLLM SET Cache - GCS. Key={key}. Value={value}")
+ headers = self._construct_headers()
+ object_name = self.key_prefix + key
+ bucket_name = self.bucket_name
+ url = f"https://storage.googleapis.com/upload/storage/v1/b/{bucket_name}/o?uploadType=media&name={object_name}"
+ data = json.dumps(value)
+ self.sync_client.post(url=url, data=data, headers=headers)
+ except Exception as e:
+ print_verbose(f"GCS Caching: set_cache() - Got exception from GCS: {e}")
+
+ async def async_set_cache(self, key, value, **kwargs):
+ try:
+ headers = self._construct_headers()
+ object_name = self.key_prefix + key
+ bucket_name = self.bucket_name
+ url = f"https://storage.googleapis.com/upload/storage/v1/b/{bucket_name}/o?uploadType=media&name={object_name}"
+ data = json.dumps(value)
+ await self.async_client.post(url=url, data=data, headers=headers)
+ except Exception as e:
+ print_verbose(f"GCS Caching: async_set_cache() - Got exception from GCS: {e}")
+
+ def get_cache(self, key, **kwargs):
+ try:
+ headers = self._construct_headers()
+ object_name = self.key_prefix + key
+ bucket_name = self.bucket_name
+ url = f"https://storage.googleapis.com/storage/v1/b/{bucket_name}/o/{object_name}?alt=media"
+ response = self.sync_client.get(url=url, headers=headers)
+ if response.status_code == 200:
+ cached_response = json.loads(response.text)
+ verbose_logger.debug(
+ f"Got GCS Cache: key: {key}, cached_response {cached_response}. Type Response {type(cached_response)}"
+ )
+ return cached_response
+ return None
+ except Exception as e:
+ verbose_logger.error(f"GCS Caching: get_cache() - Got exception from GCS: {e}")
+
+ async def async_get_cache(self, key, **kwargs):
+ try:
+ headers = self._construct_headers()
+ object_name = self.key_prefix + key
+ bucket_name = self.bucket_name
+ url = f"https://storage.googleapis.com/storage/v1/b/{bucket_name}/o/{object_name}?alt=media"
+ response = await self.async_client.get(url=url, headers=headers)
+ if response.status_code == 200:
+ return json.loads(response.text)
+ return None
+ except Exception as e:
+ verbose_logger.error(f"GCS Caching: async_get_cache() - Got exception from GCS: {e}")
+
+ def flush_cache(self):
+ pass
+
+ async def disconnect(self):
+ pass
+
+ async def async_set_cache_pipeline(self, cache_list, **kwargs):
+ tasks = []
+ for val in cache_list:
+ tasks.append(self.async_set_cache(val[0], val[1], **kwargs))
+ await asyncio.gather(*tasks)
diff --git a/litellm/types/caching.py b/litellm/types/caching.py
index 2531444ae81..67b0238ce8a 100644
--- a/litellm/types/caching.py
+++ b/litellm/types/caching.py
@@ -12,6 +12,7 @@ class LiteLLMCacheType(str, Enum):
DISK = "disk"
QDRANT_SEMANTIC = "qdrant-semantic"
AZURE_BLOB = "azure-blob"
+ GCS = "gcs"
CachingSupportedCallTypes = Literal[
diff --git a/tests/local_testing/test_gcs_cache_unit_tests.py b/tests/local_testing/test_gcs_cache_unit_tests.py
new file mode 100644
index 00000000000..305dfd95d7d
--- /dev/null
+++ b/tests/local_testing/test_gcs_cache_unit_tests.py
@@ -0,0 +1,6 @@
+from cache_unit_tests import LLMCachingUnitTests
+from litellm.caching import LiteLLMCacheType
+
+class TestGCSCacheUnitTests(LLMCachingUnitTests):
+ def get_cache_type(self) -> LiteLLMCacheType:
+ return LiteLLMCacheType.GCS
diff --git a/tests/test_litellm/caching/test_gcs_cache.py b/tests/test_litellm/caching/test_gcs_cache.py
new file mode 100644
index 00000000000..c346570bb05
--- /dev/null
+++ b/tests/test_litellm/caching/test_gcs_cache.py
@@ -0,0 +1,36 @@
+import os
+import sys
+from unittest.mock import MagicMock, AsyncMock, patch
+
+import pytest
+
+sys.path.insert(0, os.path.abspath("../../.."))
+
+from litellm.caching.gcs_cache import GCSCache
+
+
+def mock_gcs_dependencies():
+ """Mock httpx clients and GCS auth"""
+ mock_sync_client = MagicMock()
+ mock_async_client = AsyncMock()
+
+ with patch("litellm.caching.gcs_cache._get_httpx_client", return_value=mock_sync_client), \
+ patch("litellm.caching.gcs_cache.get_async_httpx_client", return_value=mock_async_client), \
+ patch("litellm.caching.gcs_cache.GCSBucketBase.sync_construct_request_headers", return_value={}):
+ yield {
+ "sync_client": mock_sync_client,
+ "async_client": mock_async_client,
+ }
+
+
+async def test_gcs_cache_async_set_and_get(mock_gcs_dependencies):
+ cache = GCSCache(bucket_name="test-bucket")
+ await cache.async_set_cache("key", {"foo": "bar"})
+ mock_gcs_dependencies["async_client"].post.assert_called_once()
+
+ mock_gcs_dependencies["async_client"].get.return_value.status_code = 200
+ mock_gcs_dependencies["async_client"].get.return_value.text = "{\"foo\": \"bar\"}"
+ result = await cache.async_get_cache("key")
+ assert result == {"foo": "bar"}