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_native_redis_semantic_cache

Yujong Lee2129a94e5633
diff --cc litellm-rust/Cargo.lock
index ca686008de3,b37202dce1b..5c1688acac1
--- a/litellm-rust/Cargo.lock
+++ b/litellm-rust/Cargo.lock
@@@ -2687,9 -2742,9 +2757,10 @@@ dependencies =
"litellm-auth",
"litellm-auth-gcp",
"litellm-cache",
+ "litellm-cache-azure-blob",
"litellm-cache-memory",
"litellm-cache-redis",
+ "litellm-cache-redis-semantic",
"litellm-cache-response",
"litellm-callbacks-legacy-python",
"litellm-core",
diff --cc litellm-rust/Cargo.toml
index f1d40f83ef2,7d94d31db3e..91e0cc08c8f
--- 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-redis-semantic = { path = "crates/cache-redis-semantic" }
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 93ce5828489,5528e12ee2d..507bd20348a
--- 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-redis-semantic.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 3c20dc6f75c,5c962f2bc7a..3db49f9dfc5
--- a/litellm-rust/crates/python-bridge/src/cache/config.rs
+++ b/litellm-rust/crates/python-bridge/src/cache/config.rs
@@@ -75,19 -75,11 +75,24 @@@ pub(super) struct RedisCacheConfig
pub(super) connection: RedisConnectionConfig,
}
+ pub(super) struct AzureBlobCacheConfig {
+ pub(super) account_url: String,
+ pub(super) container: String,
+ }
+
+#[allow(
+ dead_code,
+ reason = "embedding settings are projected so drift falls back to Python"
+)]
+pub(super) struct RedisSemanticCacheConfig {
+ pub(super) redis_url: String,
+ pub(super) index_name: String,
+ pub(super) similarity_threshold: f64,
+ pub(super) embedding_model: String,
+ pub(super) embedding_max_input_tokens: Option<u64>,
+ pub(super) embedding_timeout: Option<f64>,
+}
+
struct RedisClientProjection<'py> {
topology: RedisTopology,
host: String,
@@@ -102,7 -94,7 +107,8 @@@ const REDIS_PY_DEFAULT_MAX_CONNECTIONS
pub(super) enum CacheBackendConfig {
Memory(MemoryCacheConfig),
Redis(Box<RedisCacheConfig>),
+ AzureBlob(AzureBlobCacheConfig),
+ RedisSemantic(Box<RedisSemanticCacheConfig>),
}
#[allow(dead_code, reason = "consumed by the cache activation follow-up")]
@@@ -169,14 -161,15 +175,20 @@@ impl NativeCacheConfig
}))),
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) => project_redis_semantic(&backend).map(|backend| {
+ CacheConfigProjection::Native(Box::new(Self {
+ policy,
+ backend: CacheBackendConfig::RedisSemantic(Box::new(backend)),
+ }))
+ }),
Some(
- CacheType::RedisSemantic
- | CacheType::ValkeySemantic
+ CacheType::ValkeySemantic
| CacheType::S3
| CacheType::Disk
| CacheType::QdrantSemantic
@@@ -190,13 -182,12 +201,12 @@@
}
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::RedisSemantic(_) => None,
- }
- {
+ let default_ttl = match &self.backend {
+ CacheBackendConfig::Memory(config) => Some(config.default_ttl),
+ CacheBackendConfig::Redis(config) => Some(config.default_ttl),
- CacheBackendConfig::AzureBlob(_) => None,
++ CacheBackendConfig::AzureBlob(_) | CacheBackendConfig::RedisSemantic(_) => None,
+ };
+ if service.default_ttl() != default_ttl {
return Some("facade and native backend default TTLs must match");
}
match &self.backend {
@@@ -221,45 -212,34 +231,69 @@@
CacheBackendConfig::Redis(config) => (service.namespace()
!= config.namespace.as_deref())
.then_some("facade and native backend namespaces must match"),
+ CacheBackendConfig::RedisSemantic(_) if service.kind() != "redis_semantic" => {
+ Some("facade and native backend types must match")
+ }
+ CacheBackendConfig::RedisSemantic(config)
+ if service.index_name() != Some(config.index_name.as_str()) =>
+ {
+ Some("facade and native backend index names must match")
+ }
+ CacheBackendConfig::RedisSemantic(config)
+ if service.similarity_threshold() != Some(config.similarity_threshold as f32) =>
+ {
+ Some("facade and native backend similarity thresholds must match")
+ }
+ CacheBackendConfig::RedisSemantic(_) => 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,
+ },
}
}
}
+ #[inline(never)]
+ fn project_azure_blob(backend: &Bound<'_, PyAny>) -> PyResult<AzureBlobCacheConfig> {
+ let client = backend.getattr("container_client")?;
+ let container = client.getattr("container_name")?.extract::<String>()?;
+ let url = client.getattr("url")?.extract::<String>()?;
+ let account_url = url
+ .strip_suffix(container.as_str())
+ .and_then(|url| url.strip_suffix('/'))
+ .ok_or_else(|| PyValueError::new_err("Azure Blob container URL is malformed"))?;
+ Ok(AzureBlobCacheConfig {
+ account_url: account_url.to_string(),
+ container,
+ })
+ }
+
+#[inline(never)]
+pub(super) fn project_redis_semantic(
+ backend: &Bound<'_, PyAny>,
+) -> PyResult<RedisSemanticCacheConfig> {
+ Ok(RedisSemanticCacheConfig {
+ redis_url: backend.getattr("_redis_url")?.extract::<String>()?,
+ index_name: backend
+ .getattr("_index_name")?
+ .extract::<Option<String>>()?
+ .unwrap_or_else(|| "litellm_semantic_cache_index".into()),
+ similarity_threshold: backend.getattr("similarity_threshold")?.extract::<f64>()?,
+ embedding_model: backend.getattr("embedding_model")?.extract::<String>()?,
+ embedding_max_input_tokens: backend
+ .getattr("embedding_max_input_tokens")?
+ .extract::<Option<u64>>()?,
+ embedding_timeout: backend
+ .getattr("embedding_timeout")?
+ .extract::<Option<f64>>()?,
+ })
+}
+
#[inline(never)]
fn project_memory(backend: &Bound<'_, PyAny>) -> PyResult<MemoryCacheConfig> {
let max_size_kib = backend.getattr("max_size_per_item")?.extract::<usize>()?;
diff --cc litellm-rust/crates/python-bridge/src/cache/facade.rs
index 398f46d0d1e,0e20676938f..bf1b69cfbf5
--- a/litellm-rust/crates/python-bridge/src/cache/facade.rs
+++ b/litellm-rust/crates/python-bridge/src/cache/facade.rs
@@@ -287,20 -343,9 +360,16 @@@ impl FacadeGuard
"max_size_per_item",
"redis_kwargs",
"redis_flush_size",
+ "similarity_threshold",
+ "distance_threshold",
+ "embedding_model",
+ "embedding_max_input_tokens",
+ "embedding_timeout",
+ "_index_name",
+ "_redis_url",
],
)?,
- 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 7b5300b52f7,002cd6b7a33..e124f489644
--- a/litellm-rust/crates/python-bridge/src/cache/handle.rs
+++ b/litellm-rust/crates/python-bridge/src/cache/handle.rs
@@@ -1,16 -1,8 +1,16 @@@
use litellm_cache_redis::{RedisNode, RedisTopology};
+use litellm_cache_redis_semantic::RedisSemanticConfig;
- use litellm_host_python::release_gil;
+ use litellm_host_python::{release_gil, run_sync_value};
-use pyo3::{PyTraverseError, PyVisit, exceptions::PyRuntimeError, prelude::*};
+use pyo3::{
+ PyTraverseError, PyVisit,
+ exceptions::{PyRuntimeError, PyTypeError},
+ prelude::*,
+};
-use super::{cache_error, facade::FacadeGuard, native::NativeResponseCache, request::duration};
+use super::{
+ cache_error, config::project_redis_semantic, embedder::PythonEmbedder, facade::FacadeGuard,
+ native::NativeResponseCache, request::duration,
+};
#[pyclass(frozen, name = "_CacheTestHandle")]
pub(crate) struct CacheTestHandle {
diff --cc litellm-rust/crates/python-bridge/src/cache/native.rs
index de9c4afa236,2cd72a7ce14..bad2c30f189
--- a/litellm-rust/crates/python-bridge/src/cache/native.rs
+++ b/litellm-rust/crates/python-bridge/src/cache/native.rs
@@@ -1,9 -1,9 +1,10 @@@
use std::{sync::Arc, time::Duration};
-use litellm_cache::{CacheCodec, CacheConnectionResult, Error};
+use litellm_cache::{CacheCodec, CacheConnectionResult, Error, ExactCacheContext};
+ use litellm_cache_azure_blob::AzureBlobCache;
use litellm_cache_memory::InMemoryCache;
use litellm_cache_redis::{RedisCache, RedisTopology};
+use litellm_cache_redis_semantic::{RedisSemanticCache, RedisSemanticConfig};
use litellm_cache_response::{
CacheEntry, PartialHits, ResponseCache, ResponseCacheCodec, ResponseCacheRequest, WriteBuffer,
};
@@@ -19,7 -16,7 +20,8 @@@ pub(super) enum NativeResponseCache
cache: Arc<ResponseCache<RedisCache<ResponseCacheCodec>>>,
buffer: Option<Arc<WriteBuffer>>,
},
+ AzureBlob(Arc<ResponseCache<AzureBlobCache<ResponseCacheCodec>>>),
+ RedisSemantic(Arc<ResponseCache<RedisSemanticCache<PythonEmbedder>>>),
}
impl NativeResponseCache {
@@@ -50,17 -47,29 +52,39 @@@
buffer: None,
})
}
-
+ pub fn redis_semantic(
+ url: &str,
+ embedder: PythonEmbedder,
+ config: RedisSemanticConfig,
+ ) -> Result<Self, Error> {
+ let backend = RedisSemanticCache::new(url, embedder, config)?;
+ Ok(Self::RedisSemantic(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::RedisSemantic(_) => None,
+ }
+ }
}
impl NativeResponseCache {
@@@ -68,7 -77,7 +92,8 @@@
match self {
Self::Memory(_) => "memory",
Self::Redis { .. } => "redis",
+ Self::RedisSemantic(_) => "redis_semantic",
+ Self::AzureBlob(_) => "azure-blob",
}
}
@@@ -76,20 -85,20 +101,21 @@@
match self {
Self::Memory(cache) => cache.default_ttl(),
Self::Redis { cache, .. } => cache.default_ttl(),
+ Self::RedisSemantic(cache) => cache.default_ttl(),
+ Self::AzureBlob(cache) => cache.default_ttl(),
}
}
pub fn namespace(&self) -> Option<&str> {
match self {
- Self::Memory(_) | Self::RedisSemantic(_) => None,
- Self::Memory(_) | Self::AzureBlob(_) => None,
++ Self::Memory(_) | Self::AzureBlob(_) | Self::RedisSemantic(_) => None,
Self::Redis { cache, .. } => cache.backend().namespace(),
}
}
pub fn topology(&self) -> Option<&RedisTopology> {
match self {
- Self::Memory(_) | Self::RedisSemantic(_) => None,
- Self::Memory(_) | Self::AzureBlob(_) => None,
++ Self::Memory(_) | Self::AzureBlob(_) | Self::RedisSemantic(_) => None,
Self::Redis { cache, .. } => Some(cache.backend().topology()),
}
}
@@@ -97,52 -106,17 +123,52 @@@
pub fn capacity(&self) -> Option<usize> {
match self {
Self::Memory(cache) => Some(cache.backend().max_size_in_memory()),
- Self::Redis { .. } | Self::RedisSemantic(_) => None,
- Self::Redis { .. } | Self::AzureBlob(_) => None,
++ Self::Redis { .. } | Self::AzureBlob(_) | Self::RedisSemantic(_) => None,
}
}
pub fn max_entry_bytes(&self) -> Option<usize> {
match self {
Self::Memory(cache) => cache.backend().max_entry_bytes(),
- Self::Redis { .. } | Self::RedisSemantic(_) => None,
- Self::Redis { .. } | Self::AzureBlob(_) => None,
++ Self::Redis { .. } | Self::AzureBlob(_) | Self::RedisSemantic(_) => None,
+ }
+ }
+
+ pub fn index_name(&self) -> Option<&str> {
+ match self {
+ Self::RedisSemantic(cache) => Some(cache.backend().index_name()),
- Self::Memory(_) | Self::Redis { .. } => None,
++ Self::Memory(_) | Self::Redis { .. } | Self::AzureBlob(_) => None,
}
}
+ pub fn similarity_threshold(&self) -> Option<f32> {
+ match self {
+ Self::RedisSemantic(cache) => Some(cache.backend().similarity_threshold()),
- Self::Memory(_) | Self::Redis { .. } => None,
++ Self::Memory(_) | Self::Redis { .. } | Self::AzureBlob(_) => None,
+ }
+ }
+
+ pub fn semantic_embedder(&self) -> Option<&PythonEmbedder> {
+ match self {
+ Self::RedisSemantic(cache) => Some(cache.backend().embedder()),
- Self::Memory(_) | Self::Redis { .. } => None,
++ Self::Memory(_) | Self::Redis { .. } | Self::AzureBlob(_) => None,
+ }
+ }
+
+ pub fn embedder_object(&self) -> Option<&Py<PyAny>> {
+ match self {
+ Self::RedisSemantic(cache) => Some(cache.backend().embedder().object()),
- Self::Memory(_) | Self::Redis { .. } => None,
++ Self::Memory(_) | Self::Redis { .. } | Self::AzureBlob(_) => None,
+ }
+ }
+
+ pub fn traverse(&self, visit: &PyVisit<'_>) -> Result<(), PyTraverseError> {
+ if let Self::RedisSemantic(cache) = self {
+ cache.backend().embedder().traverse(visit)?;
+ }
+ Ok(())
+ }
+
pub fn with_redis_flush_size(self, flush_size: Option<usize>) -> Self {
match self {
Self::Redis { cache, .. } => Self::Redis {
@@@ -153,15 -127,15 +179,16 @@@
}
}
- pub fn lookup(
- &self,
- request: &ResponseCacheRequest,
- now: Duration,
- ) -> Result<Option<Value>, Error> {
+ fn exact_requests(requests: &[CacheRequest]) -> Vec<ResponseCacheRequest<ExactCacheContext>> {
+ requests.iter().map(CacheRequest::exact).collect()
+ }
+
+ pub fn lookup(&self, request: &CacheRequest, now: Duration) -> Result<Option<Value>, Error> {
match self {
- Self::Memory(cache) => cache.lookup(request, now),
- Self::Redis { cache, .. } => cache.lookup(request, now),
- Self::AzureBlob(cache) => cache.lookup(request, now),
+ Self::Memory(cache) => cache.lookup(&request.exact(), now),
+ Self::Redis { cache, .. } => cache.lookup(&request.exact(), now),
+ Self::RedisSemantic(cache) => cache.lookup(&request.semantic(), now),
++ Self::AzureBlob(cache) => cache.lookup(&request.exact(), now),
}
}
@@@ -172,9 -146,9 +199,10 @@@
now: Duration,
) -> Result<(), Error> {
match self {
- Self::Memory(cache) => cache.store(request, response, now),
- Self::Redis { cache, .. } => cache.store(request, response, now),
- Self::AzureBlob(cache) => cache.store(request, response, now),
+ Self::Memory(cache) => cache.store(&request.exact(), response, now),
+ Self::Redis { cache, .. } => cache.store(&request.exact(), response, now),
+ Self::RedisSemantic(cache) => cache.store(&request.semantic(), response, now),
++ Self::AzureBlob(cache) => cache.store(&request.exact(), response, now),
}
}
@@@ -184,9 -158,9 +212,10 @@@
now: Duration,
) -> Result<PartialHits, Error> {
match self {
- Self::Memory(cache) => cache.lookup_batch(requests, now),
- Self::Redis { cache, .. } => cache.lookup_batch(requests, now),
- Self::AzureBlob(cache) => cache.lookup_batch(requests, now),
+ Self::Memory(cache) => cache.lookup_batch(&Self::exact_requests(requests), now),
+ Self::Redis { cache, .. } => cache.lookup_batch(&Self::exact_requests(requests), now),
+ Self::RedisSemantic(_) => Err(Error::UnsupportedOperation),
++ Self::AzureBlob(cache) => cache.lookup_batch(&Self::exact_requests(requests), now),
}
}
@@@ -196,9 -170,9 +225,10 @@@
now: Duration,
) -> Result<Option<Value>, Error> {
match self {
- Self::Memory(cache) => cache.async_lookup(request, now).await,
- Self::Redis { cache, .. } => cache.async_lookup(request, now).await,
- Self::AzureBlob(cache) => cache.async_lookup(request, now).await,
+ Self::Memory(cache) => cache.async_lookup(&request.exact(), now).await,
+ Self::Redis { cache, .. } => cache.async_lookup(&request.exact(), now).await,
+ Self::RedisSemantic(cache) => cache.async_lookup(&request.semantic(), now).await,
++ Self::AzureBlob(cache) => cache.async_lookup(&request.exact(), now).await,
}
}
@@@ -217,14 -191,8 +247,15 @@@
Self::Redis {
cache,
buffer: Some(buffer),
- } => buffer.async_store(cache, request, response, now).await,
- Self::AzureBlob(cache) => cache.async_store(request, response, now).await,
+ } => {
+ buffer
+ .async_store(cache, &request.exact(), response, now)
+ .await
+ }
+ Self::RedisSemantic(cache) => {
+ cache.async_store(&request.semantic(), response, now).await
+ }
++ Self::AzureBlob(cache) => cache.async_store(&request.exact(), response, now).await,
}
}
@@@ -234,17 -202,9 +265,22 @@@
now: Duration,
) -> Result<PartialHits, Error> {
match self {
- Self::Memory(cache) => cache.async_lookup_batch(requests, now).await,
- Self::Redis { cache, .. } => cache.async_lookup_batch(requests, now).await,
- Self::AzureBlob(cache) => cache.async_lookup_batch(requests, now).await,
+ Self::Memory(cache) => {
+ cache
+ .async_lookup_batch(&Self::exact_requests(requests), now)
+ .await
+ }
+ Self::Redis { cache, .. } => {
+ cache
+ .async_lookup_batch(&Self::exact_requests(requests), now)
+ .await
+ }
+ Self::RedisSemantic(_) => Err(Error::UnsupportedOperation),
++ Self::AzureBlob(cache) => {
++ cache
++ .async_lookup_batch(&Self::exact_requests(requests), now)
++ .await
++ }
}
}
@@@ -254,39 -214,9 +290,50 @@@
now: Duration,
) -> Result<(), Error> {
match self {
- Self::Memory(cache) => cache.async_store_batch(entries, now).await,
- Self::Redis { cache, .. } => cache.async_store_batch(entries, now).await,
- Self::AzureBlob(cache) => cache.async_store_batch(entries, now).await,
+ Self::Memory(cache) => {
+ cache
+ .async_store_batch(
+ entries
+ .into_iter()
+ .map(|(request, value)| (request.exact(), value))
+ .collect(),
+ now,
+ )
+ .await
+ }
+ Self::Redis { cache, .. } => {
+ cache
+ .async_store_batch(
+ entries
+ .into_iter()
+ .map(|(request, value)| (request.exact(), value))
+ .collect(),
+ now,
+ )
+ .await
+ }
+ Self::RedisSemantic(cache) => {
+ cache
+ .async_store_batch(
+ entries
+ .into_iter()
+ .map(|(request, value)| (request.semantic(), value))
+ .collect(),
+ now,
+ )
+ .await
+ }
++ Self::AzureBlob(cache) => {
++ cache
++ .async_store_batch(
++ entries
++ .into_iter()
++ .map(|(request, value)| (request.exact(), value))
++ .collect(),
++ now,
++ )
++ .await
++ }
}
}
@@@ -299,7 -229,7 +346,8 @@@
}
cache.async_flush().await
}
+ Self::RedisSemantic(_) => Err(Error::UnsupportedOperation),
+ Self::AzureBlob(cache) => cache.async_flush().await,
}
}
@@@ -307,7 -237,7 +355,8 @@@
match self {
Self::Memory(cache) => cache.test_connection().await,
Self::Redis { cache, .. } => cache.test_connection().await,
+ Self::RedisSemantic(_) => Err(Error::UnsupportedOperation),
+ Self::AzureBlob(cache) => cache.test_connection().await,
}
}
}
diff --cc tests/test_litellm_rust/test_cache.py
index 9312fdde075,a0f2396a25d..fd1610dff6b
--- a/tests/test_litellm_rust/test_cache.py
+++ b/tests/test_litellm_rust/test_cache.py
@@@ -7,9 -5,9 +7,10 @@@ import mat
import os
import threading
import time
+ import uuid
import weakref
-from collections.abc import Generator
+from collections.abc import Callable, Generator
+from contextlib import ExitStack
from types import SimpleNamespace
from typing import Final, Protocol, cast
from urllib.parse import urlparse
@@@ -378,9 -401,92 +411,92 @@@ async def test_unmodified_builtin_cache
def test_facade_registration_rejects_mismatched_capacity() -> None:
facade: Final = Cache(type=LiteLLMCacheType.LOCAL)
with pytest.raises(TypeError, match="capacities must match"):
- _native._CacheTestHandle.memory(capacity=7)._bind_facade(facade)
+ _CacheTestHandle.memory(capacity=7)._bind_facade(facade)
+ def test_azure_blob_facade_serves_natively_and_python_reads_the_same_blobs(azure_blob_facade: Cache) -> None:
+ backend: Final = azure_blob_facade.cache
+ assert isinstance(backend, AzureBlobCache)
+ handle: Final = azure_blob_handle(azure_blob_facade)
+ assert handle.backend == "azure-blob"
+ account_url: Final = backend.container_client.url.removesuffix(f"/{backend.container_client.container_name}")
+ with pytest.raises(TypeError, match="containers must match"):
+ _native._CacheTestHandle.azure_blob(account_url, f"{backend.container_client.container_name}-other")._bind_facade(
+ azure_blob_facade
+ )
+ handle._bind_facade(azure_blob_facade)
+ resolver: Final = _native._CacheTestResolver(SimpleNamespace(cache=azure_blob_facade))
+ native: Final = resolver.resolve()
+ assert native.kind == "native"
+
+ response: Final = {"choices": [{"text": "caf\u00e9 \u2603"}], "usage": {"total_tokens": 3}, "flag": True, "empty": None}
+ native.store({**request("sync"), "ttl_seconds": 0.001}, response)
+ native.store(request("sync"), {"choices": [{"text": "second"}]})
+ time.sleep(0.01)
+ stored: Final = json.loads(backend.container_client.download_blob("sync").readall())
+ assert stored["response"] == response
+ assert isinstance(stored["timestamp"], float)
+ assert native.lookup(request("sync")) == response
+ assert cast(CacheLookup, azure_blob_facade).get_cache(cache_key="sync") == response
+
+ backend.set_cache("python", {"timestamp": time.time(), "response": response})
+ backend.set_cache("legacy", "bare legacy value")
+ backend.container_client.upload_blob("invalid", b"{not json", overwrite=True)
+ assert native.lookup(request("python")) == response
+ assert native.lookup(request("legacy")) == cast(CacheLookup, azure_blob_facade).get_cache(cache_key="legacy")
+ assert native.lookup_batch([request("python"), request("missing"), request("invalid"), request("sync")]) == {
+ "values": [response, None, None, response],
+ "missing_indices": [1, 2],
+ }
+
+ with rebound(azure_blob_facade, "ttl", 12):
+ assert resolver.resolve().kind == "python_callback"
+ with rebound(backend, "container_client", ContainerClient.from_container_url(backend.container_client.url)):
+ assert resolver.resolve().kind == "python_callback"
+
+ def custom_get(*_args: object, **_kwargs: object) -> None:
+ return None
+
+ with rebound(backend, "get_cache", custom_get):
+ assert resolver.resolve().kind == "python_callback"
+ assert resolver.resolve().kind == "python_callback"
+ assert cast(CacheLookup, azure_blob_facade).get_cache(cache_key="sync") == response
+
+ class CustomBlobCache(AzureBlobCache):
+ pass
+
+ with rebound(azure_blob_facade, "cache", CustomBlobCache(account_url, backend.container_client.container_name)):
+ assert resolver.resolve().kind == "python_callback"
+ with pytest.raises(TypeError):
+ azure_blob_handle(azure_blob_facade)._bind_facade(azure_blob_facade)
+
+
+ async def test_azure_blob_native_async_writes_overwrite_batch_and_flush_like_python(azure_blob_facade: Cache) -> None:
+ backend: Final = azure_blob_facade.cache
+ assert isinstance(backend, AzureBlobCache)
+ azure_blob_handle(azure_blob_facade)._bind_facade(azure_blob_facade)
+ binding: Final = _native._CacheTestResolver(SimpleNamespace(cache=azure_blob_facade)).resolve()
+ assert binding.kind == "native"
+ ping: Final = cast(dict[str, object], await binding.ping())
+ assert ping["status"] == "success", ping
+
+ await binding.async_store(request("async"), {"value": 1})
+ await binding.async_store({**request("async"), "ttl_seconds": 0.001}, {"value": 2})
+ time.sleep(0.01)
+ assert await binding.async_lookup(request("async")) == {"value": 2}
+ assert await backend.async_get_cache("async") == json.loads(backend.container_client.download_blob("async").readall())
+ assert cast(CacheLookup, azure_blob_facade).get_cache(cache_key="async") == {"value": 2}
+
+ await binding.async_store_batch([request("first"), request("second")], [{"value": 3}, {"value": 4}])
+ assert await binding.async_lookup_batch([request("second"), request("missing"), request("first")]) == {
+ "values": [{"value": 4}, None, {"value": 3}],
+ "missing_indices": [1],
+ }
+ await binding.async_flush()
+ assert [blob.name for blob in backend.container_client.list_blobs()] == []
+ assert await binding.async_lookup(request("async")) is None
+
+
async def test_redis_facade_buffers_native_async_writes(redis_url: str) -> None:
parsed: Final = urlparse(redis_url)
with rebound(litellm, "default_redis_ttl", 60):