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
Merge origin/main into litellm_native_disk_cache
Yujong Lee98e9e8c60212
diff --cc litellm-rust/crates/python-bridge/src/cache/config.rsindex 17c4cb40903,5fe36f6c1fa..745edc978d3--- a/litellm-rust/crates/python-bridge/src/cache/config.rs+++ b/litellm-rust/crates/python-bridge/src/cache/config.rs@@@ -1,6 -1,7 +1,7 @@@-use std::time::Duration;+use std::{path::PathBuf, time::Duration};use litellm_cache::CacheType;+ use litellm_cache_redis::{RedisNode, RedisTopology};use pyo3::{exceptions::{PyTypeError, PyValueError},prelude::*,@@@ -506,9 -601,11 +640,11 @@@ mod testsuse pyo3::{prelude::*, types::PyDict};+ use litellm_cache_redis::{RedisNode, RedisTopology};+use super::{- CacheBackendConfig, CacheConfigProjection, CertificateRequirement, NativeCacheConfig,- RedisProtocol,+ CacheBackendConfig, CacheConfigProjection, CachePolicy, CertificateRequirement,+ DiskCacheConfig, NativeCacheConfig, RedisProtocol,};use crate::cache::native::NativeResponseCache;@@@ -630,84 -740,87 +779,166 @@@assert_eq!(reason.message(), "native Redis credentials require Python");});}-+ #[test]+ fn projects_builtin_disk_configuration_and_rejects_custom_stores() {+ Python::initialize();+ Python::attach(|py| {+ let root =+ std::env::temp_dir().join(format!("litellm-disk-config-{}", std::process::id()));+ let directory = root.to_string_lossy();+ let disk_facade = facade(+ py,+ &format!(+ "Cache = type('Cache', (), {{'__module__': 'diskcache.core'}})\n\+ Disk = type('Disk', (), {{'__module__': 'diskcache.core'}})\n\+ store = Cache()\n\+ store._disk = Disk()\n\+ store.directory = {directory:?}\n\+ backend = SimpleNamespace(disk_cache=store)\n\+ facade = SimpleNamespace(type='disk', mode='default-on', ttl=None, namespace=None, supported_call_types=None, redis_flush_size=None, semantic_cache_scope='key', cache=backend)"+ ),+ );+ let CacheConfigProjection::Native(config) =+ NativeCacheConfig::project(&disk_facade).unwrap()+ else {+ panic!("disk cache should be supported");+ };+ let CacheBackendConfig::Disk(disk) = config.backend else {+ panic!("expected disk configuration");+ };+ assert_eq!(disk.directory, root);+ let matching = NativeResponseCache::disk(&directory).unwrap();+ assert_eq!(+ (NativeCacheConfig {+ policy: config.policy,+ backend: CacheBackendConfig::Disk(disk),+ })+ .service_mismatch(&matching),+ None+ );+ let other = NativeResponseCache::disk(&root.join("other").to_string_lossy()).unwrap();+ let mismatch = NativeCacheConfig {+ policy: CachePolicy {+ mode: "default-on".into(),+ ttl: None,+ namespace: None,+ supported_call_types: None,+ redis_flush_size: None,+ semantic_cache_scope: "key".into(),+ },+ backend: CacheBackendConfig::Disk(DiskCacheConfig {+ directory: root.clone(),+ }),+ };+ assert_eq!(+ mismatch.service_mismatch(&other),+ Some("facade and native backend directories must match")+ );++ let custom = facade(+ py,+ &format!(+ "CustomCache = type('CustomCache', (), {{'__module__': 'mypkg'}})\n\+ CustomDisk = type('CustomDisk', (), {{'__module__': 'mypkg'}})\n\+ store = CustomCache()\n\+ store._disk = CustomDisk()\n\+ store.directory = {directory:?}\n\+ backend = SimpleNamespace(disk_cache=store)\n\+ facade = SimpleNamespace(type='disk', mode='default-on', ttl=None, namespace=None, supported_call_types=None, redis_flush_size=None, semantic_cache_scope='key', cache=backend)"+ ),+ );+ let CacheConfigProjection::Unsupported(reason) =+ NativeCacheConfig::project(&custom).unwrap()+ else {+ panic!("custom disk store must stay on Python");+ };+ assert_eq!(+ reason.message(),+ "native disk cache requires the built-in diskcache store"+ );+ });+ }++ #[test]+ fn projects_cluster_startup_nodes_as_redis_topology() {+ Python::initialize();+ Python::attach(|py| {+ let facade = cluster_facade(+ py,+ "[{'host': 'node-a', 'port': 7000}, {'host': 'node-b', 'port': 7001}]",+ "client.on_connect",+ );+ let CacheConfigProjection::Native(config) =+ NativeCacheConfig::project(&facade).unwrap()+ else {+ panic!("cluster startup nodes should project natively");+ };+ let CacheBackendConfig::Redis(redis) = &config.backend else {+ panic!("expected Redis configuration");+ };+ let expected = RedisTopology::Cluster {+ startup_nodes: vec![+ RedisNode {+ host: "node-a".into(),+ port: 7000,+ },+ RedisNode {+ host: "node-b".into(),+ port: 7001,+ },+ ],+ };+ assert_eq!(redis.topology, expected);+ assert_eq!(redis.connection.host, "node-a");+ assert_eq!(redis.connection.port, 7000);+ assert_eq!(redis.connection.password.as_deref(), Some("secret"));+ assert_eq!(redis.connection.protocol, RedisProtocol::Resp3);+ assert_eq!(+ redis+ .connection+ .tls+ .as_ref()+ .unwrap()+ .certificate_requirement,+ CertificateRequirement::None+ );+ });+ }++ #[test]+ fn malformed_startup_nodes_and_foreign_connect_hooks_stay_on_python() {+ Python::initialize();+ Python::attach(|py| {+ for (startup_nodes, hook, message) in [+ (+ "[{'host': 'node-a', 'port': 7000, 'server_type': 'primary'}]",+ "client.on_connect",+ "native Redis topology is not implemented",+ ),+ (+ "[{'host': 'node-a', 'port': 'seven'}]",+ "client.on_connect",+ "native Redis topology is not implemented",+ ),+ (+ "[]",+ "client.on_connect",+ "native Redis topology is not implemented",+ ),+ (+ "[{'host': 'node-a', 'port': 7000}]",+ "lambda connection: None",+ "native Redis credentials require Python",+ ),+ ] {+ let facade = cluster_facade(py, startup_nodes, hook);+ let CacheConfigProjection::Unsupported(reason) =+ NativeCacheConfig::project(&facade).unwrap()+ else {+ panic!("{startup_nodes} with {hook} must stay on Python");+ };+ assert_eq!(reason.message(), message, "{startup_nodes} with {hook}");+ }+ });+ }}diff --cc litellm-rust/crates/python-bridge/src/cache/facade.rsindex a22a1754169,a9ce2ae7756..0bb5c7571a4--- a/litellm-rust/crates/python-bridge/src/cache/facade.rs+++ b/litellm-rust/crates/python-bridge/src/cache/facade.rs@@@ -29,14 -30,28 +30,33 @@@ struct RedisPoolGuardreference: Py<PyAny>,connection_class: Py<PyAny>,connection_kwargs: Py<PyAny>,- max_connections: usize,+ max_connections: Option<usize>,+ attributes: RedisPoolAttributes,}+struct DiskStoreGuard {+ reference: Py<PyAny>,+ directory: String,+}++ struct RedisPoolAttributes {+ pool: &'static str,+ connection_class: &'static str,+ max_connections: Option<&'static str>,+ }++ const STANDALONE_POOL: RedisPoolAttributes = RedisPoolAttributes {+ pool: "connection_pool",+ connection_class: "connection_class",+ max_connections: Some("max_connections"),+ };++ const CLUSTER_POOL: RedisPoolAttributes = RedisPoolAttributes {+ pool: "nodes_manager",+ connection_class: "connection_pool_class",+ max_connections: None,+ };+pub(super) struct FacadeGuard {outer: ObjectGuard,backend: ObjectGuard,@@@ -215,10 -218,15 +244,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"),- "disk" => ("litellm.caching.disk_cache", "DiskCache", "disk"),+ 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",+ ),++ ("disk", _) => ("litellm.caching.disk_cache", "DiskCache", "disk"),_ => unreachable!(),};let backend = facade.getattr("cache")?;@@@ -264,12 -272,11 +299,14 @@@"redis_flush_size",],)?,- 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,+ },+ disk_store: (kind == "disk")+ .then(|| DiskStoreGuard::capture(&backend))+ .transpose()?,})}diff --cc litellm-rust/crates/python-bridge/src/cache/handle.rsindex 2cb2045577c,2ee2b0c2c8c..ba058ab0d77--- a/litellm-rust/crates/python-bridge/src/cache/handle.rs+++ b/litellm-rust/crates/python-bridge/src/cache/handle.rs@@@ -40,22 -41,22 +41,34 @@@ impl CacheTestHandleurl: 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 = (directory))]+ fn disk(py: Python<'_>, directory: String) -> PyResult<Self> {+ let service =+ release_gil(py, move || NativeResponseCache::disk(&directory)).map_err(cache_error)?;Ok(Self {service,guard: None,diff --cc litellm-rust/crates/python-bridge/src/cache/native.rsindex 14993a6e8e3,b23038dee65..e764fde8b39--- 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 std::{path::Path, sync::Arc, time::Duration};use litellm_cache::{CacheCodec, CacheConnectionResult, Error};+use litellm_cache_disk::DiskCache;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,};diff --cc tests/test_litellm_rust/test_cache.pyindex 13f5f686464,3903ef65daa..bb022c26a3a--- a/tests/test_litellm_rust/test_cache.py+++ b/tests/test_litellm_rust/test_cache.py@@@ -18,8 -17,8 +19,9 @@@ import rediimport litellmfrom litellm.caching.caching import Cache, disable_cache, enable_cache, update_cache+from litellm.caching.disk_cache import DiskCachefrom litellm.caching.in_memory_cache import InMemoryCache+ from litellm.caching.redis_cluster_cache import RedisClusterCachefrom litellm.rust_bridge import _nativefrom litellm.types.caching import LiteLLMCacheTypefrom tests.test_litellm_rust.support.isolation import rebound@@@ -396,111 -403,64 +406,170 @@@ async def test_redis_facade_buffers_natassert client.get("second") is not Noneawait facade.cache.disconnect()client.close()--+async def test_disk_reads_python_entries_and_python_reads_native_entries(tmp_path: Path) -> None:+ disk_cache: Final = DiskCache(disk_cache_dir=str(tmp_path))+ response: Final = {"choices": [{"text": "cached"}], "usage": {"total_tokens": 3}}+ disk_cache.disk_cache.set(+ "sync",+ {"timestamp": time.time(), "response": json.dumps(response)},+ )+ disk_cache.disk_cache.set("async", json.dumps({"timestamp": time.time(), "response": response}))+ disk_cache.disk_cache.set("raw", json.dumps(response))+ disk_cache.disk_cache.set("invalid", "not a cache entry")+ disk_cache.disk_cache.set(+ "large",+ {"timestamp": time.time(), "response": {"text": "x" * 70_000}},+ )+ binding: Final = _native._CacheTestResolver(+ SimpleNamespace(cache=_native._CacheTestHandle.disk(str(tmp_path)))+ ).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("large")) == {"text": "x" * 70_000}++ await binding.async_store({**request("native"), "ttl_seconds": 12.0}, response)+ stored_response: Final = disk_cache.get_cache("native")+ assert isinstance(stored_response, dict)+ assert stored_response["response"] == response+ stored, expire_time = disk_cache.disk_cache.get("native", expire_time=True)+ assert stored is not None+ assert time.time() < expire_time <= time.time() + 12.0+ await binding.async_store(request("no-ttl"), response)+ _, no_expiry = disk_cache.disk_cache.get("no-ttl", expire_time=True)+ assert no_expiry is None+++async def test_disk_entries_survive_a_fresh_handle_and_expire_on_time(tmp_path: Path) -> None:+ first: Final = _native._CacheTestResolver(+ SimpleNamespace(cache=_native._CacheTestHandle.disk(str(tmp_path)))+ ).resolve()+ await first.async_store(request("persistent"), {"value": "persistent"})+ await first.async_store({**request("expiring"), "ttl_seconds": 0.3}, {"value": "expiring"})+ fresh: Final = _native._CacheTestResolver(+ SimpleNamespace(cache=_native._CacheTestHandle.disk(str(tmp_path)))+ ).resolve()+ assert fresh.lookup(request("persistent")) == {"value": "persistent"}+ assert fresh.lookup(request("expiring")) == {"value": "expiring"}+ await asyncio.sleep(0.4)+ assert fresh.lookup(request("expiring")) is None+ assert fresh.lookup(request("persistent")) == {"value": "persistent"}+++def test_disk_facade_registers_and_store_changes_fall_back(tmp_path: Path) -> None:+ facade: Final = Cache(type=LiteLLMCacheType.DISK, disk_cache_dir=str(tmp_path))+ with pytest.raises(TypeError, match="directories must match"):+ _native._CacheTestHandle.disk(str(tmp_path / "other"))._bind_facade(facade)+ handle: Final = _native._CacheTestHandle.disk(str(tmp_path))+ handle._bind_facade(facade)+ resolver: Final = _native._CacheTestResolver(SimpleNamespace(cache=facade))+ binding: Final = resolver.resolve()+ assert binding.kind == "native"+ binding.store(request("native"), {"value": "native"})+ assert facade.get_cache(cache_key="native") == {"value": "native"}++ with rebound(facade.cache, "disk_cache", diskcache.Cache(str(tmp_path))):+ assert resolver.resolve().kind == "python_callback"+ assert resolver.resolve().kind == "native"++ class CustomDiskCache(DiskCache):+ pass++ with rebound(facade, "cache", CustomDiskCache(disk_cache_dir=str(tmp_path))):+ assert resolver.resolve().kind == "python_callback"++ class CustomStore(diskcache.Cache):+ pass++ custom_facade: Final = Cache(type=LiteLLMCacheType.DISK, disk_cache_dir=str(tmp_path))+ custom_facade.cache.disk_cache = CustomStore(str(tmp_path))+ with pytest.raises(TypeError, match="built-in diskcache store"):+ _native._CacheTestHandle.disk(str(tmp_path))._bind_facade(custom_facade)+++async def test_disk_native_batch_lookup_and_store_report_partial_hits(tmp_path: Path) -> None:+ binding: Final = _native._CacheTestResolver(+ SimpleNamespace(cache=_native._CacheTestHandle.disk(str(tmp_path)))+ ).resolve()+ requests: Final = [request("hit"), request("miss"), request("disabled")]+ requests[2]["controls"] = {+ "supported_call_type": True,+ "configured": True,+ "native_backend": True,+ "default_on": True,+ "caching": False,+ "no_cache": False,+ "no_store": False,+ "use_cache": False,+ }+ await binding.async_store_batch(requests, [{"value": 1}, {"value": 2}, {"value": 3}])++ partial: Final = await binding.async_lookup_batch(requests)++ assert partial == {+ "values": [{"value": 1}, {"value": 2}, None],+ "missing_indices": [2],+ }+++ 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()