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(rust): merge main into litellm_gcs_native_cache

Yujong Lee9f4448f42fa2
diff --cc litellm-rust/crates/python-bridge/src/cache/config.rs
index 66f493dd760,5fe36f6c1fa..96564b364c3
--- a/litellm-rust/crates/python-bridge/src/cache/config.rs
+++ b/litellm-rust/crates/python-bridge/src/cache/config.rs
@@@ -73,13 -75,17 +75,24 @@@ pub(super) struct RedisCacheConfig
pub(super) connection: RedisConnectionConfig,
}
+#[derive(Debug, PartialEq)]
+pub(super) struct GcsCacheConfig {
+ pub(super) bucket_name: String,
+ pub(super) key_prefix: String,
+ pub(super) path_service_account: Option<String>,
+}
+
+ struct RedisClientProjection<'py> {
+ topology: RedisTopology,
+ host: String,
+ port: u16,
+ pool_size: usize,
+ resolved: Bound<'py, PyDict>,
+ tls: Option<RedisTlsConfig>,
+ }
+
+ const REDIS_PY_DEFAULT_MAX_CONNECTIONS: usize = 1 << 31;
+
pub(super) enum CacheBackendConfig {
Memory(MemoryCacheConfig),
Redis(Box<RedisCacheConfig>),
@@@ -525,9 -601,11 +659,11 @@@ mod tests
use pyo3::{prelude::*, types::PyDict};
+ use litellm_cache_redis::{RedisNode, RedisTopology};
+
use super::{
- CacheBackendConfig, CacheConfigProjection, CertificateRequirement, NativeCacheConfig,
- RedisProtocol,
+ CacheBackendConfig, CacheConfigProjection, CertificateRequirement, GcsCacheConfig,
+ NativeCacheConfig, RedisProtocol, UnsupportedCacheConfig,
};
use crate::cache::native::NativeResponseCache;
diff --cc litellm-rust/crates/python-bridge/src/cache/facade.rs
index 6aa94754e2d,a9ce2ae7756..7d55ebb20cd
--- a/litellm-rust/crates/python-bridge/src/cache/facade.rs
+++ b/litellm-rust/crates/python-bridge/src/cache/facade.rs
@@@ -189,10 -218,15 +218,16 @@@ impl FacadeGuard
"only exact built-in Cache facades can be registered",
));
}
- let (module, name, cache_kind) = match kind {
- "memory" => ("litellm.caching.in_memory_cache", "InMemoryCache", "local"),
- "redis" => ("litellm.caching.redis_cache", "RedisCache", "redis"),
- "gcs" => ("litellm.caching.gcs_cache", "GCSCache", "gcs"),
+ let cluster = matches!(service.topology(), Some(RedisTopology::Cluster { .. }));
+ let (module, name, cache_kind) = match (kind, cluster) {
+ ("memory", _) => ("litellm.caching.in_memory_cache", "InMemoryCache", "local"),
+ ("redis", false) => ("litellm.caching.redis_cache", "RedisCache", "redis"),
+ ("redis", true) => (
+ "litellm.caching.redis_cluster_cache",
+ "RedisClusterCache",
+ "redis",
+ ),
++ ("gcs", _) => ("litellm.caching.gcs_cache", "GCSCache", "gcs"),
_ => unreachable!(),
};
let backend = facade.getattr("cache")?;
@@@ -236,14 -270,13 +271,16 @@@
"max_size_per_item",
"redis_kwargs",
"redis_flush_size",
+ "bucket_name",
+ "key_prefix",
+ "path_service_account",
],
)?,
- redis_pool: (kind == "redis")
- .then(|| RedisPoolGuard::capture(&backend))
- .transpose()?,
+ redis_pool: match (kind, cluster) {
+ ("redis", false) => Some(RedisPoolGuard::capture(&backend, STANDALONE_POOL)?),
+ ("redis", true) => Some(RedisPoolGuard::capture(&backend, CLUSTER_POOL)?),
+ _ => None,
+ },
})
}
diff --cc litellm-rust/crates/python-bridge/src/cache/handle.rs
index 87d9300b08b,2ee2b0c2c8c..f754c5037fd
--- a/litellm-rust/crates/python-bridge/src/cache/handle.rs
+++ b/litellm-rust/crates/python-bridge/src/cache/handle.rs
@@@ -42,35 -41,22 +43,47 @@@ impl CacheTestHandle
url: String,
ttl_seconds: f64,
namespace: Option<String>,
+ startup_nodes: Option<Vec<(String, u16)>>,
) -> PyResult<Self> {
let ttl = Some(duration(ttl_seconds)?);
- let service = release_gil(py, move || NativeResponseCache::redis(&url, ttl, namespace))
- .map_err(cache_error)?;
+ let topology = match startup_nodes {
+ None => RedisTopology::Standalone,
+ Some(nodes) => RedisTopology::Cluster {
+ startup_nodes: nodes
+ .into_iter()
+ .map(|(host, port)| RedisNode { host, port })
+ .collect(),
+ },
+ };
+ let service = release_gil(py, move || {
+ NativeResponseCache::redis(&url, &topology, ttl, namespace)
+ })
+ .map_err(cache_error)?;
+ Ok(Self {
+ service,
+ guard: None,
+ pid: std::process::id(),
+ })
+ }
+
+ #[staticmethod]
+ #[pyo3(signature = (bucket_name, *, gcs_path=None, path_service_account=None, endpoint=None, token=None))]
+ fn gcs(
+ py: Python<'_>,
+ bucket_name: String,
+ gcs_path: Option<String>,
+ path_service_account: Option<String>,
+ endpoint: Option<String>,
+ token: Option<String>,
+ ) -> PyResult<Self> {
+ let config = GcsConfig {
+ bucket_name,
+ gcs_path,
+ path_service_account,
+ endpoint: endpoint.unwrap_or_else(|| DEFAULT_ENDPOINT.to_string()),
+ };
+ let service = release_gil(py, move || NativeResponseCache::gcs(config, token))
+ .map_err(cache_error)?;
Ok(Self {
service,
guard: None,
diff --cc litellm-rust/crates/python-bridge/src/cache/native.rs
index 9a030ac0434,b23038dee65..3f087f1b476
--- a/litellm-rust/crates/python-bridge/src/cache/native.rs
+++ b/litellm-rust/crates/python-bridge/src/cache/native.rs
@@@ -1,9 -1,8 +1,9 @@@
use std::{sync::Arc, time::Duration};
use litellm_cache::{CacheCodec, CacheConnectionResult, Error};
+use litellm_cache_gcs::{GcsCache, GcsConfig, StaticTokenSource};
use litellm_cache_memory::InMemoryCache;
- use litellm_cache_redis::RedisCache;
+ use litellm_cache_redis::{RedisCache, RedisTopology};
use litellm_cache_response::{
CacheEntry, PartialHits, ResponseCache, ResponseCacheCodec, ResponseCacheRequest, WriteBuffer,
};
@@@ -84,6 -69,13 +86,13 @@@ impl NativeResponseCache
}
}
+ pub fn topology(&self) -> Option<&RedisTopology> {
+ match self {
- Self::Memory(_) => None,
++ Self::Memory(_) | Self::Gcs(_) => None,
+ Self::Redis { cache, .. } => Some(cache.backend().topology()),
+ }
+ }
+
pub fn capacity(&self) -> Option<usize> {
match self {
Self::Memory(cache) => Some(cache.backend().max_size_in_memory()),
diff --cc tests/test_litellm_rust/test_cache.py
index cc409ebe49c,3903ef65daa..8a436e8cd0b
--- a/tests/test_litellm_rust/test_cache.py
+++ b/tests/test_litellm_rust/test_cache.py
@@@ -16,11 -17,10 +17,12 @@@ import redi
import litellm
from litellm.caching.caching import Cache, disable_cache, enable_cache, update_cache
+from litellm.caching.gcs_cache import GCSCache
from litellm.caching.in_memory_cache import InMemoryCache
+ from litellm.caching.redis_cluster_cache import RedisClusterCache
from litellm.rust_bridge import _native
from litellm.types.caching import LiteLLMCacheType
+from tests.test_litellm_rust.support.fake_gcs import FakeGcs
from tests.test_litellm_rust.support.isolation import rebound
pytestmark: Final = pytest.mark.requires_rust_extension
@@@ -48,15 -47,14 +50,23 @@@ def redis_url() -> Generator[str]
worker.join(timeout=5)
+def fake_gcs() -> Generator[FakeGcs]:
+ server: Final = FakeGcs()
+ try:
+ yield server
+ finally:
+ server.close()
+
+
+ @pytest.fixture
+ def cluster_nodes() -> tuple[tuple[str, int], ...]:
+ configured: Final = os.environ.get("LITELLM_TEST_REDIS_CLUSTER_NODES")
+ if not configured:
+ pytest.skip("LITELLM_TEST_REDIS_CLUSTER_NODES is not set")
+ return tuple((host, int(port)) for host, _, port in (node.partition(":") for node in configured.split(",")))
+
+
def test_existing_constructor_and_global_are_unchanged() -> None:
facade: Final = Cache(type=LiteLLMCacheType.LOCAL)
assert type(facade.cache) is InMemoryCache
@@@ -407,217 -405,62 +417,278 @@@ async def test_redis_facade_buffers_nat
client.close()
+async def test_gcs_reads_python_entries_and_writes_python_compatible_objects(
+ fake_gcs: FakeGcs, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ monkeypatch.delenv("GCS_PATH_SERVICE_ACCOUNT", raising=False)
+ monkeypatch.delenv("GCS_BUCKET_NAME", raising=False)
+ response: Final = {"choices": [{"text": "cached"}], "usage": {"total_tokens": 3}, "flag": True, "empty": None}
+ fake_gcs.put(
+ "bucket",
+ "cache/sync",
+ json.dumps({"timestamp": time.time(), "response": json.dumps(response)}).encode(),
+ )
+ fake_gcs.put("bucket", "cache/async", json.dumps({"timestamp": time.time(), "response": response}).encode())
+ fake_gcs.put("bucket", "cache/raw", json.dumps(response).encode())
+ fake_gcs.put("bucket", "cache/invalid", b"not a cache entry")
+ binding: Final = _native._CacheTestResolver(
+ SimpleNamespace(
+ cache=_native._CacheTestHandle.gcs(
+ "bucket",
+ gcs_path="cache",
+ endpoint=fake_gcs.url,
+ token=fake_gcs.token,
+ )
+ )
+ ).resolve()
+
+ assert binding.lookup(request("sync")) == response
+ assert await binding.async_lookup(request("async")) == response
+ assert binding.lookup(request("raw")) == response
+ assert await binding.async_lookup(request("invalid")) is None
+ assert binding.lookup(request("missing")) is None
+
+ await binding.async_store({**request("native"), "ttl_seconds": 12.0}, response)
+ stored: Final = fake_gcs.objects[("bucket", "cache/native")]
+ stored_value: Final = cast(dict[str, object], json.loads(stored))
+ assert stored_value["response"] == response
+ assert isinstance(stored_value["timestamp"], float)
+ upload: Final = next(item for item in fake_gcs.requests if item.method == "POST")
+ assert upload.path == "/upload/storage/v1/b/bucket/o"
+ assert upload.query == "uploadType=media&name=cache%2Fnative"
+ assert upload.headers["Authorization"] == f"Bearer {fake_gcs.token}"
+ assert upload.headers["Content-Type"] == "application/json"
+ upload_text: Final = f"{upload.path}?{upload.query}{upload.headers}"
+ assert "ttl" not in upload_text.lower()
+ assert "expiry" not in upload_text.lower()
+ download: Final = next(item for item in fake_gcs.requests if item.path.endswith("/cache%2Fsync"))
+ assert download.path == "/storage/v1/b/bucket/o/cache%2Fsync"
+ assert download.query == "alt=media"
+
+ binding.store(request("sync2"), response)
+ assert binding.lookup(request("sync2")) == response
+ assert GCSCache(bucket_name="bucket", gcs_path="cache").key_prefix == "cache/"
+ assert GCSCache(bucket_name="bucket", gcs_path="cache/").key_prefix == "cache/"
+ assert GCSCache(bucket_name="bucket").key_prefix == ""
+
+
+async def test_gcs_batch_lookup_preserves_order_and_treats_malformed_entries_as_misses(fake_gcs: FakeGcs) -> None:
+ fake_gcs.put("bucket", "cache/hit", json.dumps({"timestamp": time.time(), "response": {"value": 1}}).encode())
+ fake_gcs.put("bucket", "cache/invalid", b"not a cache entry")
+ binding: Final = _native._CacheTestResolver(
+ SimpleNamespace(
+ cache=_native._CacheTestHandle.gcs(
+ "bucket",
+ gcs_path="cache",
+ endpoint=fake_gcs.url,
+ token=fake_gcs.token,
+ )
+ )
+ ).resolve()
+ requests: Final = [request("hit"), request("missing"), request("invalid")]
+ expected: Final = {"values": [{"value": 1}, None, None], "missing_indices": [1, 2]}
+
+ assert await binding.async_lookup_batch(requests) == expected
+ assert binding.lookup_batch(requests) == expected
+ await binding.async_store_batch([request("first"), request("second")], [{"value": 1}, {"value": 2}])
+ assert ("bucket", "cache/first") in fake_gcs.objects
+ assert ("bucket", "cache/second") in fake_gcs.objects
+
+
+async def test_gcs_facade_binds_only_exact_matching_configuration(
+ fake_gcs: FakeGcs, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ monkeypatch.delenv("GCS_PATH_SERVICE_ACCOUNT", raising=False)
+ monkeypatch.delenv("GCS_BUCKET_NAME", raising=False)
+ monkeypatch.setenv("GOOGLE_APPLICATION_CREDENTIALS", "/nonexistent")
+ facade: Final = Cache(type=LiteLLMCacheType.GCS, gcs_bucket_name="bucket", gcs_path="cache/")
+ assert type(facade.cache) is GCSCache
+
+ mismatched_bucket: Final = _native._CacheTestHandle.gcs(
+ "other",
+ gcs_path="cache",
+ endpoint=fake_gcs.url,
+ token=fake_gcs.token,
+ )
+ with pytest.raises(TypeError, match="buckets must match"):
+ mismatched_bucket._bind_facade(facade)
+ mismatched_prefix: Final = _native._CacheTestHandle.gcs(
+ "bucket",
+ gcs_path="x",
+ endpoint=fake_gcs.url,
+ token=fake_gcs.token,
+ )
+ with pytest.raises(TypeError, match="key prefixes must match"):
+ mismatched_prefix._bind_facade(facade)
+ mismatched_credentials: Final = _native._CacheTestHandle.gcs(
+ "bucket",
+ gcs_path="cache",
+ path_service_account="sa.json",
+ endpoint=fake_gcs.url,
+ token=fake_gcs.token,
+ )
+ with pytest.raises(TypeError, match="credentials must match"):
+ mismatched_credentials._bind_facade(facade)
+ with pytest.raises(TypeError, match="types must match"):
+ _native._CacheTestHandle.memory()._bind_facade(facade)
+
+ matching: Final = _native._CacheTestHandle.gcs(
+ "bucket",
+ gcs_path="cache",
+ endpoint=fake_gcs.url,
+ token=fake_gcs.token,
+ )
+ matching._bind_facade(facade)
+ resolver: Final = _native._CacheTestResolver(SimpleNamespace(cache=facade))
+ binding: Final = resolver.resolve()
+ assert binding.kind == "native"
+ await binding.async_store(request("native"), {"value": "native"})
+ assert await binding.async_lookup(request("native")) == {"value": "native"}
+ assert cast(CacheLookup, facade).get_cache(cache_key="native") is None
+
+ with rebound(facade.cache, "bucket_name", "other"):
+ assert resolver.resolve().kind == "python_callback"
+ with rebound(facade.cache, "key_prefix", "x/"):
+ assert resolver.resolve().kind == "python_callback"
+ with rebound(facade.cache, "path_service_account", "sa.json"):
+ assert resolver.resolve().kind == "python_callback"
+ def no_get_cache(*args: object, **kwargs: object) -> None:
+ return None
+
+ with rebound(facade.cache, "get_cache", no_get_cache):
+ assert resolver.resolve().kind == "python_callback"
+ with rebound(facade, "ttl", 12):
+ assert resolver.resolve().kind == "python_callback"
+
+ class CustomGcs(GCSCache):
+ pass
+
+ with rebound(facade, "cache", CustomGcs(bucket_name="bucket", gcs_path="cache/")):
+ assert resolver.resolve().kind == "python_callback"
+ custom_facade: Final = Cache(type=LiteLLMCacheType.GCS, gcs_bucket_name="bucket", gcs_path="cache/")
+ with rebound(custom_facade, "cache", CustomGcs(bucket_name="bucket", gcs_path="cache/")):
+ with pytest.raises(TypeError, match="types must match"):
+ matching._bind_facade(custom_facade)
+
+ missing_bucket: Final = Cache(type=LiteLLMCacheType.GCS)
+ with pytest.raises(TypeError, match="requires a configured bucket name"):
+ matching._bind_facade(missing_bucket)
+
+
+async def test_gcs_flush_is_a_no_op_and_ping_is_not_implemented(
+ fake_gcs: FakeGcs, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ monkeypatch.delenv("GCS_PATH_SERVICE_ACCOUNT", raising=False)
+ monkeypatch.delenv("GCS_BUCKET_NAME", raising=False)
+ binding: Final = _native._CacheTestResolver(
+ SimpleNamespace(
+ cache=_native._CacheTestHandle.gcs(
+ "bucket",
+ gcs_path="cache",
+ endpoint=fake_gcs.url,
+ token=fake_gcs.token,
+ )
+ )
+ ).resolve()
+ await binding.async_store(request("key"), {"value": "stored"})
+ await binding.async_flush()
+ assert ("bucket", "cache/key") in fake_gcs.objects
+ assert await binding.async_lookup(request("key")) == {"value": "stored"}
+ with pytest.raises(NotImplementedError):
+ await binding.ping()
+
+ facade: Final = Cache(type=LiteLLMCacheType.GCS, gcs_bucket_name="bucket", gcs_path="cache/")
+ with pytest.raises(AttributeError):
+ await facade.ping()
+ assert cast(CacheLookup, facade.cache).flush_cache() is None
+
+
+async def test_gcs_unauthorized_and_server_errors_surface_as_runtime_errors(fake_gcs: FakeGcs) -> None:
+ wrong_token: Final = _native._CacheTestResolver(
+ SimpleNamespace(
+ cache=_native._CacheTestHandle.gcs(
+ "bucket",
+ gcs_path="cache",
+ endpoint=fake_gcs.url,
+ token="wrong-token",
+ )
+ )
+ ).resolve()
+ with pytest.raises(RuntimeError):
+ wrong_token.lookup(request("missing"))
+ assert not fake_gcs.objects
+
+ binding: Final = _native._CacheTestResolver(
+ SimpleNamespace(
+ cache=_native._CacheTestHandle.gcs(
+ "bucket",
+ gcs_path="cache",
+ endpoint=fake_gcs.url,
+ token=fake_gcs.token,
+ )
+ )
+ ).resolve()
+ with pytest.raises(RuntimeError):
+ binding.lookup(request("server-error"))
+ assert binding.lookup(request("missing")) is None
++
++
+ async def test_redis_cluster_facade_serves_multi_slot_batches_and_scoped_flush_natively(
+ cluster_nodes: tuple[tuple[str, int], ...],
+ ) -> None:
+ startup_nodes: Final = [{"host": host, "port": port} for host, port in cluster_nodes]
+ url: Final = f"redis://{cluster_nodes[0][0]}:{cluster_nodes[0][1]}"
+ with rebound(litellm, "default_redis_ttl", 60):
+ facade: Final = Cache(type=LiteLLMCacheType.REDIS, redis_startup_nodes=startup_nodes, namespace="parity")
+ assert type(facade.cache) is RedisClusterCache
+ with pytest.raises(TypeError, match="types must match"):
+ _native._CacheTestHandle.redis(url, namespace="parity")._bind_facade(facade)
+ _native._CacheTestHandle.redis(url, namespace="parity", startup_nodes=list(cluster_nodes))._bind_facade(facade)
+ resolver: Final = _native._CacheTestResolver(SimpleNamespace(cache=facade))
+ assert resolver.resolve().kind == "native"
+
+ manager: Final = facade.cache.redis_client.nodes_manager
+ with rebound(manager, "connection_kwargs", {**manager.connection_kwargs, "db": 1}):
+ assert resolver.resolve().kind == "python_callback"
+ with rebound(facade.cache, "redis_kwargs", {**facade.cache.redis_kwargs, "startup_nodes": startup_nodes[:1]}):
+ assert resolver.resolve().kind == "python_callback"
+ binding: Final = resolver.resolve()
+ assert binding.kind == "native"
+
+ client: Final = redis.RedisCluster(startup_nodes=[redis.cluster.ClusterNode(*node) for node in cluster_nodes])
+ keys: Final = tuple(f"slot-{index}" for index in range(12))
+ slots: Final = {client.keyslot(f"parity:{key}") for key in keys}
+ assert len(slots) > 1, slots
+ requests: Final = [request(key) for key in keys]
+ values: Final = [{"index": index} for index in range(len(keys))]
+ await binding.async_store_batch(requests, values)
+ client.set("parity:slot-3", "not a cache entry")
+ client.set("parity:slot-7", json.dumps({"timestamp": time.time(), "response": {"index": 7, "python": True}}))
+
+ batch: Final = await binding.async_lookup_batch(requests)
+ assert batch == {
+ "values": [
+ None if index == 3 else {"index": 7, "python": True} if index == 7 else value
+ for index, value in enumerate(values)
+ ],
+ "missing_indices": [3],
+ }
+ assert facade.cache.get_cache("parity:slot-0")["response"] == {"index": 0}
+ assert (await facade.cache.async_get_cache("parity:slot-11"))["response"] == {"index": 11}
+ assert facade.cache.redis_client.mget_nonatomic([f"parity:{key}" for key in keys[:2]]) == [
+ client.get("parity:slot-0"),
+ client.get("parity:slot-1"),
+ ]
+
+ await binding.async_store({**request("pinned"), "ttl_seconds": 12.0}, {"pinned": True})
+ assert 0 < client.ttl("parity:pinned") <= 12
+ client.set("unscoped", "stays")
+
+ await binding.async_flush()
+
+ remaining: Final = tuple(sorted(key for node in client.get_primaries() for key in client.keys("parity:*", target_nodes=node)))
+ assert remaining == (), remaining
+ assert client.get("unscoped") == b"stays"
+ client.delete("unscoped")
+ client.close()
+ facade.cache.redis_client.close()