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 Leef7b96c9cedc4
diff --cc litellm-rust/Cargo.lockindex 4698746fa1f,b37202dce1b..1a4eb51af08--- a/litellm-rust/Cargo.lock+++ b/litellm-rust/Cargo.lock@@@ -2526,21 -2523,23 +2579,38 @@@ dependencies ="tokio",]+ [[package]]+ name = "litellm-cache-azure-blob"+ version = "0.1.0"+ dependencies = [+ "async-trait",+ "azure_core",+ "azure_storage_blob",+ "futures-util",+ "litellm-auth-azure",+ "litellm-auth-types",+ "litellm-cache",+ "litellm-cache-response",+ "serde_json",+ "tokio",+ "url",+ ]++[[package]]+name = "litellm-cache-disk"+version = "0.1.0"+dependencies = [+ "litellm-cache",+ "py_literal",+ "rand 0.8.7",+ "rstest",+ "rusqlite",+ "serde-pickle",+ "serde_json",+ "tempfile",+ "tokio",+]+[[package]]name = "litellm-cache-memory"version = "0.1.0"@@@ -2743,7 -2742,7 +2813,8 @@@ dependencies ="litellm-auth","litellm-auth-gcp","litellm-cache",+ "litellm-cache-azure-blob",+ "litellm-cache-disk","litellm-cache-memory","litellm-cache-redis","litellm-cache-response",diff --cc litellm-rust/Cargo.tomlindex 799741f0906,7d94d31db3e..fabec9bcd6c--- a/litellm-rust/Cargo.toml+++ b/litellm-rust/Cargo.toml@@@ -28,9 -29,9 +29,10 @@@ litellm-llms = { path = "crates/llms"litellm-types = { path = "crates/types" }litellm-core-utils = { path = "crates/core-utils" }litellm-cache = { path = "crates/cache" }+ litellm-cache-azure-blob = { path = "crates/cache-azure-blob" }litellm-cache-memory = { path = "crates/cache-memory" }litellm-cache-redis = { path = "crates/cache-redis" }+litellm-cache-disk = { path = "crates/cache-disk" }litellm-cache-response = { path = "crates/cache-response" }litellm-token-counter = { path = "crates/token-counter" }litellm-token-counter-fast = { path = "crates/token-counter-fast" }diff --cc litellm-rust/crates/python-bridge/Cargo.tomlindex eff08cafc04,5528e12ee2d..f5d08850b39--- a/litellm-rust/crates/python-bridge/Cargo.toml+++ b/litellm-rust/crates/python-bridge/Cargo.toml@@@ -21,9 -21,9 +21,10 @@@ tiktoken = ["litellm-token-counter/tikt[dependencies]bytes.workspace = truelitellm-cache.workspace = true+ litellm-cache-azure-blob.workspace = truelitellm-cache-memory.workspace = truelitellm-cache-redis.workspace = true+litellm-cache-disk.workspace = truelitellm-cache-response.workspace = trueserde.workspace = truelitellm-auth.workspace = truediff --cc litellm-rust/crates/python-bridge/src/cache/config.rsindex 745edc978d3,5c962f2bc7a..927017e2e60--- a/litellm-rust/crates/python-bridge/src/cache/config.rs+++ b/litellm-rust/crates/python-bridge/src/cache/config.rs@@@ -93,7 -94,7 +98,8 @@@ const REDIS_PY_DEFAULT_MAX_CONNECTIONSpub(super) enum CacheBackendConfig {Memory(MemoryCacheConfig),Redis(Box<RedisCacheConfig>),+ Disk(DiskCacheConfig),+ AzureBlob(AzureBlobCacheConfig),}#[allow(dead_code, reason = "consumed by the cache activation follow-up")]@@@ -162,19 -161,18 +168,24 @@@ impl NativeCacheConfig}))),Err(reason) => Ok(CacheConfigProjection::Unsupported(reason)),},+ Some(CacheType::Disk) => match project_disk(&backend)? {+ Ok(backend) => Ok(CacheConfigProjection::Native(Box::new(Self {+ policy,+ backend: CacheBackendConfig::Disk(backend),+ }))),+ Err(reason) => Ok(CacheConfigProjection::Unsupported(reason)),+ },+ Some(CacheType::AzureBlob) => project_azure_blob(&backend).map(|backend| {+ CacheConfigProjection::Native(Box::new(Self {+ policy,+ backend: CacheBackendConfig::AzureBlob(backend),+ }))+ }),Some(CacheType::RedisSemantic| CacheType::ValkeySemantic| CacheType::S3- | CacheType::Disk| CacheType::QdrantSemantic- | CacheType::AzureBlob| CacheType::Gcs,)| None => Ok(CacheConfigProjection::Unsupported(@@@ -187,7 -185,7 +198,8 @@@let default_ttl = match &self.backend {CacheBackendConfig::Memory(config) => Some(config.default_ttl),CacheBackendConfig::Redis(config) => Some(config.default_ttl),+ CacheBackendConfig::Disk(_) => None,+ CacheBackendConfig::AzureBlob(_) => None,};if service.default_ttl() != default_ttl {return Some("facade and native backend default TTLs must match");@@@ -214,17 -212,15 +226,26 @@@CacheBackendConfig::Redis(config) => (service.namespace()!= config.namespace.as_deref()).then_some("facade and native backend namespaces must match"),+ CacheBackendConfig::Disk(_) if service.kind() != "disk" => {+ Some("facade and native backend types must match")+ }+ CacheBackendConfig::Disk(config) => {+ let Some(directory) = service.directory() else {+ return Some("facade and native backend types must match");+ };+ let native = std::fs::canonicalize(directory).ok();+ let facade = std::fs::canonicalize(&config.directory).ok();+ (native != facade).then_some("facade and native backend directories must match")+ }+ CacheBackendConfig::AzureBlob(config) => match service.azure_blob_identity() {+ None => Some("facade and native backend types must match"),+ Some((account_url, container))+ if account_url != config.account_url || container != config.container =>+ {+ Some("facade and native backend containers must match")+ }+ Some(_) => None,+ },}}}diff --cc litellm-rust/crates/python-bridge/src/cache/facade.rsindex 0bb5c7571a4,0e20676938f..ee6423daf6e--- a/litellm-rust/crates/python-bridge/src/cache/facade.rs+++ b/litellm-rust/crates/python-bridge/src/cache/facade.rs@@@ -34,11 -34,19 +34,23 @@@ struct RedisPoolGuardattributes: RedisPoolAttributes,}+struct DiskStoreGuard {+ reference: Py<PyAny>,+ directory: String,+}++ struct AzureBlobClientGuard {+ sync_client: Py<PyAny>,+ async_client: Py<PyAny>,+ url: String,+ container_name: String,+ }++ enum ConnectionGuard {+ None,+ RedisPool(RedisPoolGuard),+ AzureBlob(AzureBlobClientGuard),+ }-struct RedisPoolAttributes {pool: &'static str,connection_class: &'static str,@@@ -60,8 -68,7 +72,8 @@@ const CLUSTER_POOL: RedisPoolAttributepub(super) struct FacadeGuard {outer: ObjectGuard,backend: ObjectGuard,- redis_pool: Option<RedisPoolGuard>,+ disk_store: Option<DiskStoreGuard>,+ connection: ConnectionGuard,}impl ObjectGuard {@@@ -211,26 -218,61 +223,81 @@@ impl RedisPoolGuard}}+impl DiskStoreGuard {+ fn capture(backend: &Bound<'_, PyAny>) -> PyResult<Self> {+ let store = backend.getattr("disk_cache")?;+ Ok(Self {+ reference: store.clone().unbind(),+ directory: store.getattr("directory")?.extract()?,+ })+ }++ fn matches(&self, py: Python<'_>, backend: &Bound<'_, PyAny>) -> PyResult<bool> {+ let store = backend.getattr("disk_cache")?;+ Ok(self.reference.bind(py).is(&store)+ && self.directory == store.getattr("directory")?.extract::<String>()?)+ }++ fn traverse(&self, visit: &PyVisit<'_>) -> Result<(), PyTraverseError> {+ visit.call(&self.reference)+ }+}++ impl AzureBlobClientGuard {+ fn capture(backend: &Bound<'_, PyAny>) -> PyResult<Self> {+ let sync_client = backend.getattr("container_client")?;+ Ok(Self {+ url: sync_client.getattr("url")?.extract::<String>()?,+ container_name: sync_client.getattr("container_name")?.extract::<String>()?,+ sync_client: sync_client.unbind(),+ async_client: backend.getattr("async_container_client")?.unbind(),+ })+ }++ fn matches(&self, py: Python<'_>, backend: &Bound<'_, PyAny>) -> PyResult<bool> {+ let sync_client = backend.getattr("container_client")?;+ Ok(self.sync_client.bind(py).is(&sync_client)+ && self+ .async_client+ .bind(py)+ .is(&backend.getattr("async_container_client")?)+ && self.url == sync_client.getattr("url")?.extract::<String>()?+ && self.container_name == sync_client.getattr("container_name")?.extract::<String>()?)+ }++ fn traverse(&self, visit: &PyVisit<'_>) -> Result<(), PyTraverseError> {+ visit.call(&self.sync_client)?;+ visit.call(&self.async_client)+ }+ }++ impl ConnectionGuard {+ fn capture(kind: &str, cluster: bool, backend: &Bound<'_, PyAny>) -> PyResult<Self> {+ Ok(match (kind, cluster) {+ ("redis", false) => Self::RedisPool(RedisPoolGuard::capture(backend, STANDALONE_POOL)?),+ ("redis", true) => Self::RedisPool(RedisPoolGuard::capture(backend, CLUSTER_POOL)?),+ ("azure-blob", _) => Self::AzureBlob(AzureBlobClientGuard::capture(backend)?),+ _ => Self::None,+ })+ }++ fn matches(&self, py: Python<'_>, backend: &Bound<'_, PyAny>) -> PyResult<bool> {+ match self {+ Self::None => Ok(true),+ Self::RedisPool(guard) => guard.matches(py, backend),+ Self::AzureBlob(guard) => guard.matches(py, backend),+ }+ }++ fn traverse(&self, visit: &PyVisit<'_>) -> Result<(), PyTraverseError> {+ match self {+ Self::None => Ok(()),+ Self::RedisPool(guard) => guard.traverse(visit),+ Self::AzureBlob(guard) => guard.traverse(visit),+ }+ }+ }+impl FacadeGuard {pub(super) fn capture(py: Python<'_>,@@@ -253,7 -295,11 +320,12 @@@"RedisClusterCache","redis",),+ ("disk", _) => ("litellm.caching.disk_cache", "DiskCache", "disk"),+ ("azure-blob", _) => (+ "litellm.caching.azure_blob_cache",+ "AzureBlobCache",+ "azure-blob",+ ),_ => unreachable!(),};let backend = facade.getattr("cache")?;@@@ -299,14 -345,7 +371,10 @@@"redis_flush_size",],)?,- 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()?,+ connection: ConnectionGuard::capture(kind, cluster, &backend)?,})}@@@ -318,25 -357,13 +386,21 @@@if !self.backend.matches(py, &backend)? {return Ok(false);}- match &self.redis_pool {- Some(guard) => guard.matches(py, &backend),- None => match &self.disk_store {- Some(guard) => guard.matches(py, &backend),- None => Ok(true),- },++ if let Some(guard) = &self.disk_store++ && !guard.matches(py, &backend)?++ {++ return Ok(false);+ }+ self.connection.matches(py, &backend)}pub(super) fn traverse(&self, visit: PyVisit<'_>) -> Result<(), PyTraverseError> {self.outer.traverse(&visit)?;self.backend.traverse(&visit)?;- if let Some(guard) = &self.redis_pool {- guard.traverse(&visit)?;- }+ if let Some(guard) = &self.disk_store {+ guard.traverse(&visit)?;+ }- Ok(())+ self.connection.traverse(&visit)}}diff --cc litellm-rust/crates/python-bridge/src/cache/handle.rsindex ba058ab0d77,002cd6b7a33..6e12e12040b--- a/litellm-rust/crates/python-bridge/src/cache/handle.rs+++ b/litellm-rust/crates/python-bridge/src/cache/handle.rs@@@ -64,18 -64,21 +64,33 @@@ impl CacheTestHandle})}+ #[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,+ pid: std::process::id(),+ })+ }++ #[staticmethod]+ #[pyo3(signature = (account_url, container))]+ fn azure_blob(py: Python<'_>, account_url: String, container: String) -> PyResult<Self> {+ let service = run_sync_value(py, async move {+ NativeResponseCache::azure_blob(&account_url, &container)+ .await+ .map_err(cache_error)+ })?;+ Ok(Self {+ service,+ guard: None,+ pid: std::process::id(),+ })+ }+#[getter]fn backend(&self) -> &'static str {self.service.kind()diff --cc litellm-rust/crates/python-bridge/src/cache/native.rsindex 50e02338574,2cd72a7ce14..bbd72e58825--- a/litellm-rust/crates/python-bridge/src/cache/native.rs+++ b/litellm-rust/crates/python-bridge/src/cache/native.rs@@@ -1,7 -1,7 +1,8 @@@-use std::{sync::Arc, time::Duration};+use std::{path::Path, sync::Arc, time::Duration};use litellm_cache::{CacheCodec, CacheConnectionResult, Error};+ use litellm_cache_azure_blob::AzureBlobCache;+use litellm_cache_disk::DiskCache;use litellm_cache_memory::InMemoryCache;use litellm_cache_redis::{RedisCache, RedisTopology};use litellm_cache_response::{@@@ -16,7 -16,7 +17,8 @@@ pub(super) enum NativeResponseCachecache: Arc<ResponseCache<RedisCache<ResponseCacheCodec>>>,buffer: Option<Arc<WriteBuffer>>,},+ Disk(Arc<ResponseCache<DiskCache<ResponseCacheCodec>>>),+ AzureBlob(Arc<ResponseCache<AzureBlobCache<ResponseCacheCodec>>>),}impl NativeResponseCache {@@@ -47,11 -47,29 +49,33 @@@buffer: None,})}-+ pub fn disk(directory: &str) -> Result<Self, Error> {+ let cache = DiskCache::open(directory, ResponseCacheCodec)?;+ Ok(Self::Disk(Arc::new(ResponseCache::new(Arc::new(cache)))))+ }++ pub async fn azure_blob(account_url: &str, container: &str) -> Result<Self, Error> {+ let backend = AzureBlobCache::connect(+ account_url,+ container,+ ResponseCacheCodec,+ tokio::runtime::Handle::current(),+ )+ .await?;+ Ok(Self::AzureBlob(Arc::new(ResponseCache::new(Arc::new(+ backend,+ )))))+ }++ pub fn azure_blob_identity(&self) -> Option<(&str, &str)> {+ match self {+ Self::AzureBlob(cache) => Some((+ cache.backend().account_url(),+ cache.backend().container_name(),+ )),- Self::Memory(_) | Self::Redis { .. } => None,++ Self::Memory(_) | Self::Redis { .. } | Self::Disk(_) => None,+ }+ }}impl NativeResponseCache {@@@ -59,7 -77,7 +83,8 @@@match self {Self::Memory(_) => "memory",Self::Redis { .. } => "redis",+ Self::Disk(_) => "disk",+ Self::AzureBlob(_) => "azure-blob",}}@@@ -67,39 -85,35 +92,42 @@@match self {Self::Memory(cache) => cache.default_ttl(),Self::Redis { cache, .. } => cache.default_ttl(),+ Self::Disk(cache) => cache.default_ttl(),+ Self::AzureBlob(cache) => cache.default_ttl(),}}pub fn namespace(&self) -> Option<&str> {match self {- Self::Memory(_) => None,+ Self::Memory(_) | Self::AzureBlob(_) => None,Self::Redis { cache, .. } => cache.backend().namespace(),+ Self::Disk(_) => None,}}pub fn topology(&self) -> Option<&RedisTopology> {match self {- Self::Memory(_) => None,+ Self::Memory(_) | Self::AzureBlob(_) => None,Self::Redis { cache, .. } => Some(cache.backend().topology()),+ Self::Disk(_) => None,}}pub fn capacity(&self) -> Option<usize> {match self {Self::Memory(cache) => Some(cache.backend().max_size_in_memory()),- Self::Redis { .. } | Self::AzureBlob(_) => None,+ Self::Redis { .. } => None,+ Self::Disk(_) => None,++ Self::AzureBlob(_) => None,}}pub fn max_entry_bytes(&self) -> Option<usize> {match self {Self::Memory(cache) => cache.backend().max_entry_bytes(),- Self::Redis { .. } | Self::AzureBlob(_) => None,+ Self::Redis { .. } => None,+ Self::Disk(_) => None,++ Self::AzureBlob(_) => None,}}@@@ -109,18 -123,10 +137,18 @@@cache,buffer: flush_size.map(|flush_size| Arc::new(WriteBuffer::new(flush_size))),},+ disk @ Self::Disk(_) => disk,- memory => memory,+ other => other,}}+ pub fn directory(&self) -> Option<&Path> {+ match self {+ Self::Disk(cache) => Some(cache.backend().directory()),- Self::Memory(_) | Self::Redis { .. } => None,++ Self::Memory(_) | Self::Redis { .. } | Self::AzureBlob(_) => None,+ }+ }+pub fn lookup(&self,request: &ResponseCacheRequest,@@@ -129,7 -135,7 +157,8 @@@match self {Self::Memory(cache) => cache.lookup(request, now),Self::Redis { cache, .. } => cache.lookup(request, now),+ Self::Disk(cache) => cache.lookup(request, now),+ Self::AzureBlob(cache) => cache.lookup(request, now),}}@@@ -142,7 -148,7 +171,8 @@@match self {Self::Memory(cache) => cache.store(request, response, now),Self::Redis { cache, .. } => cache.store(request, response, now),+ Self::Disk(cache) => cache.store(request, response, now),+ Self::AzureBlob(cache) => cache.store(request, response, now),}}@@@ -154,7 -160,7 +184,8 @@@match self {Self::Memory(cache) => cache.lookup_batch(requests, now),Self::Redis { cache, .. } => cache.lookup_batch(requests, now),+ Self::Disk(cache) => cache.lookup_batch(requests, now),+ Self::AzureBlob(cache) => cache.lookup_batch(requests, now),}}@@@ -166,7 -172,7 +197,8 @@@match self {Self::Memory(cache) => cache.async_lookup(request, now).await,Self::Redis { cache, .. } => cache.async_lookup(request, now).await,+ Self::Disk(cache) => cache.async_lookup(request, now).await,+ Self::AzureBlob(cache) => cache.async_lookup(request, now).await,}}@@@ -186,7 -192,7 +218,8 @@@cache,buffer: Some(buffer),} => buffer.async_store(cache, request, response, now).await,+ Self::Disk(cache) => cache.async_store(request, response, now).await,+ Self::AzureBlob(cache) => cache.async_store(request, response, now).await,}}@@@ -198,7 -204,7 +231,8 @@@match self {Self::Memory(cache) => cache.async_lookup_batch(requests, now).await,Self::Redis { cache, .. } => cache.async_lookup_batch(requests, now).await,+ Self::Disk(cache) => cache.async_lookup_batch(requests, now).await,+ Self::AzureBlob(cache) => cache.async_lookup_batch(requests, now).await,}}@@@ -210,7 -216,7 +244,8 @@@match self {Self::Memory(cache) => cache.async_store_batch(entries, now).await,Self::Redis { cache, .. } => cache.async_store_batch(entries, now).await,+ Self::Disk(cache) => cache.async_store_batch(entries, now).await,+ Self::AzureBlob(cache) => cache.async_store_batch(entries, now).await,}}@@@ -223,7 -229,7 +258,8 @@@}cache.async_flush().await}+ Self::Disk(cache) => cache.async_flush().await,+ Self::AzureBlob(cache) => cache.async_flush().await,}}@@@ -231,7 -237,7 +267,8 @@@match self {Self::Memory(cache) => cache.test_connection().await,Self::Redis { cache, .. } => cache.test_connection().await,+ Self::Disk(cache) => cache.test_connection().await,+ Self::AzureBlob(cache) => cache.test_connection().await,}}}diff --cc tests/test_litellm_rust/test_cache.pyindex bb022c26a3a,a0f2396a25d..8cddc868073--- a/tests/test_litellm_rust/test_cache.py+++ b/tests/test_litellm_rust/test_cache.py@@@ -5,9 -5,9 +5,10 @@@ import jsoimport osimport threadingimport time+ import uuidimport weakreffrom collections.abc import Generator+from pathlib import Pathfrom types import SimpleNamespacefrom typing import Final, Protocol, castfrom urllib.parse import urlparse@@@ -16,10 -15,11 +17,12 @@@ import diskcachimport fakeredisimport pytestimport redis+ from azure.storage.blob import ContainerClientimport litellm+ from litellm.caching.azure_blob_cache import AzureBlobCachefrom litellm.caching.caching import Cache, disable_cache, enable_cache, update_cache+from litellm.caching.disk_cache import DiskCachefrom litellm.caching.in_memory_cache import InMemoryCachefrom litellm.caching.redis_cluster_cache import RedisClusterCachefrom litellm.rust_bridge import _native