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

Yujong Leecb3e212e29b1
diff --cc litellm-rust/Cargo.lock
index bd02a57ca21,b37202dce1b..2f1e78a6577
--- a/litellm-rust/Cargo.lock
+++ b/litellm-rust/Cargo.lock
@@@ -2470,21 -2523,23 +2523,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-gcs"
+version = "0.1.0"
+dependencies = [
+ "futures-util",
+ "litellm-auth-gcp",
+ "litellm-auth-types",
+ "litellm-cache",
+ "percent-encoding",
+ "reqwest 0.12.28",
+ "serde_json",
+ "tokio",
+ "wiremock",
+]
+
[[package]]
name = "litellm-cache-memory"
version = "0.1.0"
@@@ -2687,7 -2742,7 +2757,8 @@@ dependencies =
"litellm-auth",
"litellm-auth-gcp",
"litellm-cache",
+ "litellm-cache-azure-blob",
+ "litellm-cache-gcs",
"litellm-cache-memory",
"litellm-cache-redis",
"litellm-cache-response",
diff --cc litellm-rust/Cargo.toml
index 71ecf2c64ef,7d94d31db3e..d313c004972
--- 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-gcs = { path = "crates/cache-gcs" }
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.toml
index 47dab2d22f2,5528e12ee2d..6bdfe2ac09d
--- 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 = true
litellm-cache.workspace = true
+ litellm-cache-azure-blob.workspace = true
litellm-cache-memory.workspace = true
litellm-cache-redis.workspace = true
+litellm-cache-gcs.workspace = true
litellm-cache-response.workspace = true
serde.workspace = true
litellm-auth.workspace = true
diff --cc litellm-rust/crates/python-bridge/src/cache/config.rs
index 96564b364c3,5c962f2bc7a..15fa8938c9c
--- a/litellm-rust/crates/python-bridge/src/cache/config.rs
+++ b/litellm-rust/crates/python-bridge/src/cache/config.rs
@@@ -75,13 -75,11 +75,18 @@@ 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>,
+}
+
+ pub(super) struct AzureBlobCacheConfig {
+ pub(super) account_url: String,
+ pub(super) container: String,
+ }
+
struct RedisClientProjection<'py> {
topology: RedisTopology,
host: String,
@@@ -96,7 -94,7 +101,8 @@@ const REDIS_PY_DEFAULT_MAX_CONNECTIONS
pub(super) enum CacheBackendConfig {
Memory(MemoryCacheConfig),
Redis(Box<RedisCacheConfig>),
+ Gcs(GcsCacheConfig),
+ AzureBlob(AzureBlobCacheConfig),
}
#[allow(dead_code, reason = "consumed by the cache activation follow-up")]
@@@ -165,20 -161,19 +171,25 @@@ impl NativeCacheConfig
}))),
Err(reason) => Ok(CacheConfigProjection::Unsupported(reason)),
},
+ Some(CacheType::Gcs) => match project_gcs(&backend)? {
+ Ok(backend) => Ok(CacheConfigProjection::Native(Box::new(Self {
+ policy,
+ backend: CacheBackendConfig::Gcs(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,
++ | CacheType::QdrantSemantic,
)
| None => Ok(CacheConfigProjection::Unsupported(
UnsupportedCacheConfig::Backend,
@@@ -187,12 -182,12 +198,12 @@@
}
pub(super) fn service_mismatch(&self, service: &NativeResponseCache) -> Option<&'static str> {
- let expected = match &self.backend {
+ let default_ttl = match &self.backend {
CacheBackendConfig::Memory(config) => Some(config.default_ttl),
CacheBackendConfig::Redis(config) => Some(config.default_ttl),
- CacheBackendConfig::Gcs(_) => None,
- CacheBackendConfig::AzureBlob(_) => None,
++ CacheBackendConfig::AzureBlob(_) | CacheBackendConfig::Gcs(_) => None,
};
- if service.default_ttl() != expected {
+ if service.default_ttl() != default_ttl {
return Some("facade and native backend default TTLs must match");
}
match &self.backend {
@@@ -217,31 -212,15 +228,40 @@@
CacheBackendConfig::Redis(config) => (service.namespace()
!= config.namespace.as_deref())
.then_some("facade and native backend namespaces must match"),
+ CacheBackendConfig::Gcs(_) if service.kind() != "gcs" => {
+ Some("facade and native backend types must match")
+ }
+ CacheBackendConfig::Gcs(config)
+ if service
+ .gcs_backend()
+ .is_none_or(|backend| backend.bucket_name() != config.bucket_name) =>
+ {
+ Some("facade and native backend buckets must match")
+ }
+ CacheBackendConfig::Gcs(config)
+ if service
+ .gcs_backend()
+ .is_none_or(|backend| backend.key_prefix() != config.key_prefix) =>
+ {
+ Some("facade and native backend key prefixes must match")
+ }
+ CacheBackendConfig::Gcs(config)
+ if service.gcs_backend().is_none_or(|backend| {
+ backend.path_service_account() != config.path_service_account.as_deref()
+ }) =>
+ {
+ Some("facade and native backend credentials must match")
+ }
+ CacheBackendConfig::Gcs(_) => None,
+ 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.rs
index 7d55ebb20cd,0e20676938f..facb529c8a9
--- a/litellm-rust/crates/python-bridge/src/cache/facade.rs
+++ b/litellm-rust/crates/python-bridge/src/cache/facade.rs
@@@ -227,7 -295,11 +295,12 @@@ impl FacadeGuard
"RedisClusterCache",
"redis",
),
+ ("gcs", _) => ("litellm.caching.gcs_cache", "GCSCache", "gcs"),
+ ("azure-blob", _) => (
+ "litellm.caching.azure_blob_cache",
+ "AzureBlobCache",
+ "azure-blob",
+ ),
_ => unreachable!(),
};
let backend = facade.getattr("cache")?;
@@@ -271,16 -343,9 +344,12 @@@
"max_size_per_item",
"redis_kwargs",
"redis_flush_size",
+ "bucket_name",
+ "key_prefix",
+ "path_service_account",
],
)?,
- redis_pool: match (kind, cluster) {
- ("redis", false) => Some(RedisPoolGuard::capture(&backend, STANDALONE_POOL)?),
- ("redis", true) => Some(RedisPoolGuard::capture(&backend, CLUSTER_POOL)?),
- _ => None,
- },
+ connection: ConnectionGuard::capture(kind, cluster, &backend)?,
})
}
diff --cc litellm-rust/crates/python-bridge/src/cache/handle.rs
index f754c5037fd,002cd6b7a33..c148791a9b2
--- a/litellm-rust/crates/python-bridge/src/cache/handle.rs
+++ b/litellm-rust/crates/python-bridge/src/cache/handle.rs
@@@ -1,9 -1,7 +1,9 @@@
use litellm_cache_redis::{RedisNode, RedisTopology};
- use litellm_host_python::release_gil;
+ use litellm_host_python::{release_gil, run_sync_value};
use pyo3::{PyTraverseError, PyVisit, exceptions::PyRuntimeError, prelude::*};
+use litellm_cache_gcs::{DEFAULT_ENDPOINT, GcsConfig};
+
use super::{cache_error, facade::FacadeGuard, native::NativeResponseCache, request::duration};
#[pyclass(frozen, name = "_CacheTestHandle")]
@@@ -66,31 -64,21 +66,46 @@@ impl CacheTestHandle
})
}
+ #[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,
+ 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.rs
index 3f087f1b476,2cd72a7ce14..cdf843110fd
--- 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 litellm_cache::{CacheCodec, CacheConnectionResult, Error};
+ use litellm_cache_azure_blob::AzureBlobCache;
+use litellm_cache_gcs::{GcsCache, GcsConfig, StaticTokenSource};
use litellm_cache_memory::InMemoryCache;
use litellm_cache_redis::{RedisCache, RedisTopology};
use litellm_cache_response::{
@@@ -16,7 -16,7 +17,8 @@@ pub(super) enum NativeResponseCache
cache: Arc<ResponseCache<RedisCache<ResponseCacheCodec>>>,
buffer: Option<Arc<WriteBuffer>>,
},
+ Gcs(Arc<ResponseCache<GcsCache<ResponseCacheCodec>>>),
+ AzureBlob(Arc<ResponseCache<AzureBlobCache<ResponseCacheCodec>>>),
}
impl NativeResponseCache {
@@@ -48,17 -48,28 +50,40 @@@
})
}
+ pub fn gcs(config: GcsConfig, token: Option<String>) -> Result<Self, Error> {
+ let backend = match token {
+ Some(token) => GcsCache::with_token_source(
+ config,
+ ResponseCacheCodec,
+ Arc::new(StaticTokenSource(token)),
+ )?,
+ None => GcsCache::new(config, ResponseCacheCodec)?,
+ };
+ Ok(Self::Gcs(Arc::new(ResponseCache::new(Arc::new(backend)))))
+ }
++
+ 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::Gcs(_) => None,
+ }
+ }
}
impl NativeResponseCache {
@@@ -66,7 -77,7 +91,8 @@@
match self {
Self::Memory(_) => "memory",
Self::Redis { .. } => "redis",
+ Self::Gcs(_) => "gcs",
+ Self::AzureBlob(_) => "azure-blob",
}
}
@@@ -74,21 -85,20 +100,22 @@@
match self {
Self::Memory(cache) => cache.default_ttl(),
Self::Redis { cache, .. } => cache.default_ttl(),
+ Self::Gcs(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::Gcs(_) => None,
}
}
pub fn topology(&self) -> Option<&RedisTopology> {
match self {
- Self::Memory(_) | Self::Gcs(_) => None,
- Self::Memory(_) | Self::AzureBlob(_) => None,
++ Self::Memory(_) | Self::AzureBlob(_) | Self::Gcs(_) => None,
Self::Redis { cache, .. } => Some(cache.backend().topology()),
}
}
@@@ -96,16 -106,14 +123,14 @@@
pub fn capacity(&self) -> Option<usize> {
match self {
Self::Memory(cache) => Some(cache.backend().max_size_in_memory()),
- Self::Redis { .. } => None,
- Self::Gcs(_) => None,
- Self::Redis { .. } | Self::AzureBlob(_) => None,
++ Self::Redis { .. } | Self::AzureBlob(_) | Self::Gcs(_) => None,
}
}
pub fn max_entry_bytes(&self) -> Option<usize> {
match self {
Self::Memory(cache) => cache.backend().max_entry_bytes(),
- Self::Redis { .. } => None,
- Self::Gcs(_) => None,
- Self::Redis { .. } | Self::AzureBlob(_) => None,
++ Self::Redis { .. } | Self::AzureBlob(_) | Self::Gcs(_) => None,
}
}
@@@ -127,7 -135,7 +152,8 @@@
match self {
Self::Memory(cache) => cache.lookup(request, now),
Self::Redis { cache, .. } => cache.lookup(request, now),
+ Self::Gcs(cache) => cache.lookup(request, now),
+ Self::AzureBlob(cache) => cache.lookup(request, now),
}
}
@@@ -140,7 -148,7 +166,8 @@@
match self {
Self::Memory(cache) => cache.store(request, response, now),
Self::Redis { cache, .. } => cache.store(request, response, now),
+ Self::Gcs(cache) => cache.store(request, response, now),
+ Self::AzureBlob(cache) => cache.store(request, response, now),
}
}
@@@ -152,7 -160,7 +179,8 @@@
match self {
Self::Memory(cache) => cache.lookup_batch(requests, now),
Self::Redis { cache, .. } => cache.lookup_batch(requests, now),
+ Self::Gcs(cache) => cache.lookup_batch(requests, now),
+ Self::AzureBlob(cache) => cache.lookup_batch(requests, now),
}
}
@@@ -164,7 -172,7 +192,8 @@@
match self {
Self::Memory(cache) => cache.async_lookup(request, now).await,
Self::Redis { cache, .. } => cache.async_lookup(request, now).await,
+ Self::Gcs(cache) => cache.async_lookup(request, now).await,
+ Self::AzureBlob(cache) => cache.async_lookup(request, now).await,
}
}
@@@ -184,7 -192,7 +213,8 @@@
cache,
buffer: Some(buffer),
} => buffer.async_store(cache, request, response, now).await,
+ Self::Gcs(cache) => cache.async_store(request, response, now).await,
+ Self::AzureBlob(cache) => cache.async_store(request, response, now).await,
}
}
@@@ -196,7 -204,7 +226,8 @@@
match self {
Self::Memory(cache) => cache.async_lookup_batch(requests, now).await,
Self::Redis { cache, .. } => cache.async_lookup_batch(requests, now).await,
+ Self::Gcs(cache) => cache.async_lookup_batch(requests, now).await,
+ Self::AzureBlob(cache) => cache.async_lookup_batch(requests, now).await,
}
}
@@@ -208,7 -216,7 +239,8 @@@
match self {
Self::Memory(cache) => cache.async_store_batch(entries, now).await,
Self::Redis { cache, .. } => cache.async_store_batch(entries, now).await,
+ Self::Gcs(cache) => cache.async_store_batch(entries, now).await,
+ Self::AzureBlob(cache) => cache.async_store_batch(entries, now).await,
}
}
@@@ -221,7 -229,7 +253,8 @@@
}
cache.async_flush().await
}
+ Self::Gcs(cache) => cache.async_flush().await,
+ Self::AzureBlob(cache) => cache.async_flush().await,
}
}
@@@ -229,14 -237,7 +262,15 @@@
match self {
Self::Memory(cache) => cache.test_connection().await,
Self::Redis { cache, .. } => cache.test_connection().await,
+ Self::Gcs(cache) => cache.test_connection().await,
+ Self::AzureBlob(cache) => cache.test_connection().await,
}
}
+
+ pub fn gcs_backend(&self) -> Option<&GcsCache<ResponseCacheCodec>> {
+ match self {
+ Self::Gcs(cache) => Some(cache.backend()),
+ _ => None,
+ }
+ }
}
diff --cc tests/test_litellm_rust/test_cache.py
index 8a436e8cd0b,a0f2396a25d..fb2e9daa5cb
--- a/tests/test_litellm_rust/test_cache.py
+++ b/tests/test_litellm_rust/test_cache.py
@@@ -14,10 -15,11 +15,12 @@@ from urllib.parse import urlpars
import fakeredis
import pytest
import redis
+ from azure.storage.blob import ContainerClient
import litellm
+ from litellm.caching.azure_blob_cache import AzureBlobCache
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
@@@ -50,15 -50,36 +53,45 @@@ 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 azure_blob_facade() -> Generator[Cache]:
+ account_url: Final = os.environ.get("AZURE_BLOB_CACHE_ACCOUNT_URL")
+ if account_url is None:
+ pytest.skip(
+ "live Azure Blob parity needs AZURE_BLOB_CACHE_ACCOUNT_URL plus DefaultAzureCredential inputs in the environment"
+ )
+ facade: Final = Cache(
+ type=LiteLLMCacheType.AZURE_BLOB,
+ azure_account_url=account_url,
+ azure_blob_container=f"litellm-parity-{uuid.uuid4().hex[:12]}",
+ )
+ backend: Final = facade.cache
+ assert isinstance(backend, AzureBlobCache)
+ try:
+ yield facade
+ finally:
+ backend.container_client.delete_container()
+ asyncio.run(backend.disconnect())
+
+
+ def azure_blob_handle(facade: Cache) -> _native._CacheTestHandle:
+ backend: Final = facade.cache
+ assert isinstance(backend, AzureBlobCache)
+ return _native._CacheTestHandle.azure_blob(
+ backend.container_client.url.removesuffix(f"/{backend.container_client.container_name}"),
+ backend.container_client.container_name,
+ )
+
+
@pytest.fixture
def cluster_nodes() -> tuple[tuple[str, int], ...]:
configured: Final = os.environ.get("LITELLM_TEST_REDIS_CLUSTER_NODES")