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]

Merge remote-tracking branch 'origin/main' into litellm_rust_cache_s3

Yujong Lee5ca79688124b
diff --cc litellm-rust/Cargo.lock
index d1ca1831717,b37202dce1b..836d286633a
--- a/litellm-rust/Cargo.lock
+++ b/litellm-rust/Cargo.lock
@@@ -2787,9 -2740,9 +2857,10 @@@ dependencies =
"criterion",
"futures-util",
"litellm-auth",
+ "litellm-auth-aws",
"litellm-auth-gcp",
"litellm-cache",
+ "litellm-cache-azure-blob",
"litellm-cache-memory",
"litellm-cache-redis",
"litellm-cache-response",
diff --cc litellm-rust/Cargo.toml
index 031cfcbbb21,7d94d31db3e..5800c1c611b
--- a/litellm-rust/Cargo.toml
+++ b/litellm-rust/Cargo.toml
@@@ -27,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-s3 = { path = "crates/cache-s3" }
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 2aea8122fa6,5528e12ee2d..cbf9eac0caf
--- 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-s3.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 269ddedfc0e,5c962f2bc7a..554db7adf81
--- a/litellm-rust/crates/python-bridge/src/cache/config.rs
+++ b/litellm-rust/crates/python-bridge/src/cache/config.rs
@@@ -91,7 -94,7 +96,8 @@@ const REDIS_PY_DEFAULT_MAX_CONNECTIONS
pub(super) enum CacheBackendConfig {
Memory(MemoryCacheConfig),
Redis(Box<RedisCacheConfig>),
+ S3(Box<S3CacheConfig>),
+ AzureBlob(AzureBlobCacheConfig),
}
#[allow(dead_code, reason = "consumed by the cache activation follow-up")]
@@@ -164,19 -161,18 +170,24 @@@ impl NativeCacheConfig
}))),
Err(reason) => Ok(CacheConfigProjection::Unsupported(reason)),
},
+ Some(CacheType::S3) => match project_s3(&backend)? {
+ Ok(backend) => Ok(CacheConfigProjection::Native(Box::new(Self {
+ policy,
+ backend: CacheBackendConfig::S3(Box::new(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(
@@@ -186,13 -182,12 +197,13 @@@
}
pub(super) fn service_mismatch(&self, service: &NativeResponseCache) -> Option<&'static str> {
- if service.default_ttl()
- != match &self.backend {
- CacheBackendConfig::Memory(config) => Some(config.default_ttl),
- CacheBackendConfig::Redis(config) => Some(config.default_ttl),
- CacheBackendConfig::S3(_) => None,
- }
- {
+ let default_ttl = match &self.backend {
+ CacheBackendConfig::Memory(config) => Some(config.default_ttl),
+ CacheBackendConfig::Redis(config) => Some(config.default_ttl),
++ CacheBackendConfig::S3(_) => None,
+ CacheBackendConfig::AzureBlob(_) => None,
+ };
+ if service.default_ttl() != default_ttl {
return Some("facade and native backend default TTLs must match");
}
match &self.backend {
@@@ -217,30 -212,15 +228,39 @@@
CacheBackendConfig::Redis(config) => (service.namespace()
!= config.namespace.as_deref())
.then_some("facade and native backend namespaces must match"),
+ CacheBackendConfig::S3(_) if service.kind() != "s3" => {
+ Some("facade and native backend types must match")
+ }
+ CacheBackendConfig::S3(config) if service.bucket() != Some(config.bucket.as_str()) => {
+ Some("facade and native backend buckets must match")
+ }
+ CacheBackendConfig::S3(config)
+ if service.key_prefix() != Some(config.key_prefix.as_str()) =>
+ {
+ Some("facade and native backend key prefixes must match")
+ }
+ CacheBackendConfig::S3(config) if service.region() != Some(config.region.as_str()) => {
+ Some("facade and native backend regions must match")
+ }
+ CacheBackendConfig::S3(config)
+ if service.endpoint()
+ != config
+ .endpoint
+ .as_ref()
+ .map(|endpoint| endpoint.url.as_str()) =>
+ {
+ Some("facade and native backend endpoints must match")
+ }
+ CacheBackendConfig::S3(_) => 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 955367d969e,0e20676938f..81f3a1f66d4
--- a/litellm-rust/crates/python-bridge/src/cache/facade.rs
+++ b/litellm-rust/crates/python-bridge/src/cache/facade.rs
@@@ -34,10 -34,19 +34,23 @@@ struct RedisPoolGuard
attributes: RedisPoolAttributes,
}
+struct S3ClientGuard {
+ reference: Py<PyAny>,
+}
+
+ struct AzureBlobClientGuard {
+ sync_client: Py<PyAny>,
+ async_client: Py<PyAny>,
+ url: String,
+ container_name: String,
+ }
+
+ enum ConnectionGuard {
+ None,
+ RedisPool(RedisPoolGuard),
+ AzureBlob(AzureBlobClientGuard),
++ S3(S3ClientGuard),
+ }
-
struct RedisPoolAttributes {
pool: &'static str,
connection_class: &'static str,
@@@ -209,22 -218,61 +221,79 @@@ impl RedisPoolGuard
}
}
+impl S3ClientGuard {
+ fn capture(backend: &Bound<'_, PyAny>) -> PyResult<Self> {
+ Ok(Self {
+ reference: backend.getattr("s3_client")?.unbind(),
+ })
+ }
+
+ fn matches(&self, py: Python<'_>, backend: &Bound<'_, PyAny>) -> PyResult<bool> {
+ Ok(self.reference.bind(py).is(&backend.getattr("s3_client")?))
+ }
+
+ 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)?),
++ ("s3", _) => Self::S3(S3ClientGuard::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),
++ Self::S3(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),
++ Self::S3(guard) => guard.traverse(visit),
+ }
+ }
+ }
-
impl FacadeGuard {
pub(super) fn capture(
py: Python<'_>,
@@@ -247,7 -295,11 +316,12 @@@
"RedisClusterCache",
"redis",
),
+ ("s3", _) => ("litellm.caching.s3_cache", "S3Cache", "s3"),
+ ("azure-blob", _) => (
+ "litellm.caching.azure_blob_cache",
+ "AzureBlobCache",
+ "azure-blob",
+ ),
_ => unreachable!(),
};
let backend = facade.getattr("cache")?;
@@@ -291,18 -343,9 +365,11 @@@
"max_size_per_item",
"redis_kwargs",
"redis_flush_size",
+ "bucket_name",
+ "key_prefix",
],
)?,
- redis_pool: match (kind, cluster) {
- ("redis", false) => Some(RedisPoolGuard::capture(&backend, STANDALONE_POOL)?),
- ("redis", true) => Some(RedisPoolGuard::capture(&backend, CLUSTER_POOL)?),
- _ => None,
- },
- s3_client: (kind == "s3")
- .then(|| S3ClientGuard::capture(&backend))
- .transpose()?,
+ connection: ConnectionGuard::capture(kind, cluster, &backend)?,
})
}
diff --cc litellm-rust/crates/python-bridge/src/cache/handle.rs
index b922f89d7c4,002cd6b7a33..98a869372b3
--- a/litellm-rust/crates/python-bridge/src/cache/handle.rs
+++ b/litellm-rust/crates/python-bridge/src/cache/handle.rs
@@@ -66,40 -64,21 +66,54 @@@ impl CacheTestHandle
})
}
+ #[staticmethod]
+ #[allow(clippy::too_many_arguments)]
+ #[pyo3(signature = (bucket, *, region, endpoint_url=None, key_prefix="", access_key_id=None, secret_access_key=None, session_token=None))]
+ fn s3(
+ py: Python<'_>,
+ bucket: String,
+ region: String,
+ endpoint_url: Option<String>,
+ key_prefix: &str,
+ access_key_id: Option<String>,
+ secret_access_key: Option<String>,
+ session_token: Option<String>,
+ ) -> PyResult<Self> {
+ let config = S3CacheConfig {
+ bucket,
+ key_prefix: key_prefix.to_string(),
+ region: region.clone(),
+ endpoint: endpoint_url.map(|url| S3Endpoint { url }),
+ auth: AwsAuthConfig {
+ access_key_id,
+ secret_access_key,
+ session_token,
+ region_name: Some(region),
+ ..Default::default()
+ },
+ };
+ let service = run_sync_value(py, async move { Ok(NativeResponseCache::s3(config).await) })?;
+ 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 78be6a243d7,2cd72a7ce14..ff3deb43a47
--- a/litellm-rust/crates/python-bridge/src/cache/native.rs
+++ b/litellm-rust/crates/python-bridge/src/cache/native.rs
@@@ -16,7 -16,7 +17,8 @@@ pub(super) enum NativeResponseCache
cache: Arc<ResponseCache<RedisCache<ResponseCacheCodec>>>,
buffer: Option<Arc<WriteBuffer>>,
},
+ S3(Arc<ResponseCache<S3Cache<ResponseCacheCodec>>>),
+ AzureBlob(Arc<ResponseCache<AzureBlobCache<ResponseCacheCodec>>>),
}
impl NativeResponseCache {
@@@ -47,15 -47,29 +49,37 @@@
buffer: None,
})
}
-
+ pub async fn s3(config: S3CacheConfig) -> Self {
+ let runtime = tokio::runtime::Handle::current();
+ Self::S3(Arc::new(ResponseCache::new(Arc::new(S3Cache::new(
+ config,
+ ResponseCacheCodec,
+ runtime,
+ )))))
+ }
+
+ 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::S3(_) => None,
+ }
+ }
}
impl NativeResponseCache {
@@@ -63,7 -77,7 +87,8 @@@
match self {
Self::Memory(_) => "memory",
Self::Redis { .. } => "redis",
+ Self::S3(_) => "s3",
+ Self::AzureBlob(_) => "azure-blob",
}
}
@@@ -71,65 -85,35 +96,66 @@@
match self {
Self::Memory(cache) => cache.default_ttl(),
Self::Redis { cache, .. } => cache.default_ttl(),
+ Self::S3(cache) => cache.default_ttl(),
+ Self::AzureBlob(cache) => cache.default_ttl(),
}
}
+ pub fn bucket(&self) -> Option<&str> {
+ match self {
+ Self::S3(cache) => Some(cache.backend().bucket()),
+ _ => None,
+ }
+ }
+
+ pub fn key_prefix(&self) -> Option<&str> {
+ match self {
+ Self::S3(cache) => Some(cache.backend().key_prefix()),
+ _ => None,
+ }
+ }
+
+ pub fn region(&self) -> Option<&str> {
+ match self {
+ Self::S3(cache) => Some(cache.backend().region()),
+ _ => None,
+ }
+ }
+
+ pub fn endpoint(&self) -> Option<&str> {
+ match self {
+ Self::S3(cache) => cache.backend().endpoint(),
+ _ => None,
+ }
+ }
+
pub fn namespace(&self) -> Option<&str> {
match self {
- Self::Memory(_) => None,
+ Self::Memory(_) | Self::AzureBlob(_) => None,
Self::Redis { cache, .. } => cache.backend().namespace(),
+ Self::S3(_) => 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::S3(_) => None,
}
}
pub fn capacity(&self) -> Option<usize> {
match self {
Self::Memory(cache) => Some(cache.backend().max_size_in_memory()),
- Self::Redis { .. } | Self::S3(_) => None,
- Self::Redis { .. } | Self::AzureBlob(_) => None,
++ Self::Redis { .. } | Self::S3(_) | Self::AzureBlob(_) => None,
}
}
pub fn max_entry_bytes(&self) -> Option<usize> {
match self {
Self::Memory(cache) => cache.backend().max_entry_bytes(),
- Self::Redis { .. } | Self::S3(_) => None,
- Self::Redis { .. } | Self::AzureBlob(_) => None,
++ Self::Redis { .. } | Self::S3(_) | Self::AzureBlob(_) => None,
}
}
@@@ -151,7 -135,7 +177,8 @@@
match self {
Self::Memory(cache) => cache.lookup(request, now),
Self::Redis { cache, .. } => cache.lookup(request, now),
+ Self::S3(cache) => cache.lookup(request, now),
+ Self::AzureBlob(cache) => cache.lookup(request, now),
}
}
@@@ -164,7 -148,7 +191,8 @@@
match self {
Self::Memory(cache) => cache.store(request, response, now),
Self::Redis { cache, .. } => cache.store(request, response, now),
+ Self::S3(cache) => cache.store(request, response, now),
+ Self::AzureBlob(cache) => cache.store(request, response, now),
}
}
@@@ -176,7 -160,7 +204,8 @@@
match self {
Self::Memory(cache) => cache.lookup_batch(requests, now),
Self::Redis { cache, .. } => cache.lookup_batch(requests, now),
+ Self::S3(cache) => cache.lookup_batch(requests, now),
+ Self::AzureBlob(cache) => cache.lookup_batch(requests, now),
}
}
@@@ -188,7 -172,7 +217,8 @@@
match self {
Self::Memory(cache) => cache.async_lookup(request, now).await,
Self::Redis { cache, .. } => cache.async_lookup(request, now).await,
+ Self::S3(cache) => cache.async_lookup(request, now).await,
+ Self::AzureBlob(cache) => cache.async_lookup(request, now).await,
}
}
@@@ -208,7 -192,7 +238,8 @@@
cache,
buffer: Some(buffer),
} => buffer.async_store(cache, request, response, now).await,
+ Self::S3(cache) => cache.async_store(request, response, now).await,
+ Self::AzureBlob(cache) => cache.async_store(request, response, now).await,
}
}
@@@ -220,7 -204,7 +251,8 @@@
match self {
Self::Memory(cache) => cache.async_lookup_batch(requests, now).await,
Self::Redis { cache, .. } => cache.async_lookup_batch(requests, now).await,
+ Self::S3(cache) => cache.async_lookup_batch(requests, now).await,
+ Self::AzureBlob(cache) => cache.async_lookup_batch(requests, now).await,
}
}
@@@ -232,7 -216,7 +264,8 @@@
match self {
Self::Memory(cache) => cache.async_store_batch(entries, now).await,
Self::Redis { cache, .. } => cache.async_store_batch(entries, now).await,
+ Self::S3(cache) => cache.async_store_batch(entries, now).await,
+ Self::AzureBlob(cache) => cache.async_store_batch(entries, now).await,
}
}
@@@ -245,7 -229,7 +278,8 @@@
}
cache.async_flush().await
}
+ Self::S3(cache) => cache.async_flush().await,
+ Self::AzureBlob(cache) => cache.async_flush().await,
}
}
@@@ -253,7 -237,7 +287,8 @@@
match self {
Self::Memory(cache) => cache.test_connection().await,
Self::Redis { cache, .. } => cache.test_connection().await,
+ Self::S3(cache) => cache.test_connection().await,
+ Self::AzureBlob(cache) => cache.test_connection().await,
}
}
}
diff --cc tests/test_litellm_rust/test_cache.py
index f786384633d,a0f2396a25d..cfa8e95703c
--- a/tests/test_litellm_rust/test_cache.py
+++ b/tests/test_litellm_rust/test_cache.py
@@@ -5,9 -5,9 +5,10 @@@ import jso
import os
import threading
import time
+ import uuid
import weakref
from collections.abc import Generator
+from datetime import datetime
from types import SimpleNamespace
from typing import Final, Protocol, cast
from urllib.parse import urlparse
@@@ -17,11 -15,12 +18,13 @@@ import botocore.confi
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.in_memory_cache import InMemoryCache
+from litellm.caching.s3_cache import S3Cache
from litellm.caching.redis_cluster_cache import RedisClusterCache
from litellm.rust_bridge import _native
from litellm.types.caching import LiteLLMCacheType