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 origin/main into litellm_valkey_semantic_native_cache

Yujong Leedd175245cff2
diff --cc litellm-rust/crates/python-bridge/src/cache/config.rs
index 92df6a8b78d,5c962f2bc7a..1d931b7b339
--- a/litellm-rust/crates/python-bridge/src/cache/config.rs
+++ b/litellm-rust/crates/python-bridge/src/cache/config.rs
@@@ -86,18 -91,10 +86,24 @@@ struct RedisClientProjection<'py>
const REDIS_PY_DEFAULT_MAX_CONNECTIONS: usize = 1 << 31;
+#[allow(dead_code, reason = "consumed by the cache activation follow-up")]
+pub(super) struct ValkeySemanticCacheConfig {
+ pub(super) similarity_threshold: f64,
+ pub(super) index_name: String,
+ pub(super) embedding_model: String,
+ pub(super) connection: RedisConnectionConfig,
+}
+
++pub(super) struct AzureBlobCacheConfig {
++ pub(super) account_url: String,
++ pub(super) container: String,
++}
++
pub(super) enum CacheBackendConfig {
Memory(MemoryCacheConfig),
Redis(Box<RedisCacheConfig>),
+ ValkeySemantic(Box<ValkeySemanticCacheConfig>),
+ AzureBlob(AzureBlobCacheConfig),
}
#[allow(dead_code, reason = "consumed by the cache activation follow-up")]
@@@ -164,15 -161,15 +170,21 @@@ impl NativeCacheConfig
}))),
Err(reason) => Ok(CacheConfigProjection::Unsupported(reason)),
},
+ Some(CacheType::ValkeySemantic) => match project_valkey_semantic(&backend)? {
+ Ok(backend) => Ok(CacheConfigProjection::Native(Box::new(Self {
+ policy,
+ backend: CacheBackendConfig::ValkeySemantic(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
@@@ -186,14 -182,12 +197,15 @@@
}
pub(super) fn service_mismatch(&self, service: &NativeResponseCache) -> Option<&'static str> {
+ let default_ttl = match &self.backend {
+ CacheBackendConfig::Memory(config) => Some(config.default_ttl),
+ CacheBackendConfig::Redis(config) => Some(config.default_ttl),
++ CacheBackendConfig::ValkeySemantic(_) => Some(Duration::ZERO),
+ CacheBackendConfig::AzureBlob(_) => None,
+ };
- if service.default_ttl() != default_ttl {
+ if !matches!(self.backend, CacheBackendConfig::ValkeySemantic(_))
- && service.default_ttl()
- != Some(match &self.backend {
- CacheBackendConfig::Memory(config) => config.default_ttl,
- CacheBackendConfig::Redis(config) => config.default_ttl,
- CacheBackendConfig::ValkeySemantic(_) => Duration::ZERO,
- })
++ && service.default_ttl() != default_ttl
+ {
return Some("facade and native backend default TTLs must match");
}
match &self.backend {
@@@ -218,16 -212,15 +230,25 @@@
CacheBackendConfig::Redis(config) => (service.namespace()
!= config.namespace.as_deref())
.then_some("facade and native backend namespaces must match"),
+ CacheBackendConfig::ValkeySemantic(config) => {
+ if service.kind() != "valkey-semantic" {
+ return Some("facade and native backend types must match");
+ }
+ let Some((threshold, index_name)) = service.semantic_config() else {
+ return Some("facade and native backend types must match");
+ };
+ (threshold != config.similarity_threshold || index_name != config.index_name)
+ .then_some("facade and native semantic settings 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.rs
index 6474fe7c787,0e20676938f..a5e83be0830
--- a/litellm-rust/crates/python-bridge/src/cache/facade.rs
+++ b/litellm-rust/crates/python-bridge/src/cache/facade.rs
@@@ -31,10 -31,22 +31,24 @@@ struct RedisPoolGuard
connection_class: Py<PyAny>,
connection_kwargs: Py<PyAny>,
max_connections: Option<usize>,
++ client_name: &'static str,
attributes: RedisPoolAttributes,
}
+ struct AzureBlobClientGuard {
+ sync_client: Py<PyAny>,
+ async_client: Py<PyAny>,
+ url: String,
+ container_name: String,
+ }
+
+ enum ConnectionGuard {
+ None,
+ RedisPool(RedisPoolGuard),
+ AzureBlob(AzureBlobClientGuard),
+ }
+
+#[derive(Clone, Copy)]
struct RedisPoolAttributes {
pool: &'static str,
connection_class: &'static str,
@@@ -164,12 -171,8 +177,12 @@@ impl ObjectGuard
}
impl RedisPoolGuard {
- fn capture(backend: &Bound<'_, PyAny>, attributes: RedisPoolAttributes) -> PyResult<Self> {
- let pool = backend.getattr("redis_client")?.getattr(attributes.pool)?;
+ fn capture(
+ backend: &Bound<'_, PyAny>,
- client_name: &str,
++ client_name: &'static str,
+ attributes: RedisPoolAttributes,
+ ) -> PyResult<Self> {
+ let pool = backend.getattr(client_name)?.getattr(attributes.pool)?;
Ok(Self {
reference: pool.clone().unbind(),
connection_class: pool.getattr(attributes.connection_class)?.unbind(),
@@@ -177,22 -180,24 +190,18 @@@
.getattr("connection_kwargs")?
.call_method0("copy")?
.unbind(),
- max_connections: Self::max_connections(&pool, &attributes)?,
+ max_connections: attributes
+ .max_connections
+ .map(|name| pool.getattr(name)?.extract::<usize>())
+ .transpose()?,
++ client_name,
attributes,
})
}
- fn matches(
- &self,
- py: Python<'_>,
- backend: &Bound<'_, PyAny>,
- client_name: &str,
- ) -> PyResult<bool> {
- fn max_connections(
- pool: &Bound<'_, PyAny>,
- attributes: &RedisPoolAttributes,
- ) -> PyResult<Option<usize>> {
- attributes
- .max_connections
- .map(|name| pool.getattr(name)?.extract::<usize>())
- .transpose()
- }
-
+ fn matches(&self, py: Python<'_>, backend: &Bound<'_, PyAny>) -> PyResult<bool> {
let pool = backend
- .getattr(client_name)?
- .getattr("redis_client")?
++ .getattr(self.client_name)?
.getattr(self.attributes.pool)?;
Ok(self.reference.bind(py).is(&pool)
&& self
@@@ -218,6 -218,61 +227,74 @@@
}
}
+ 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)?),
++ ("redis", false) => Self::RedisPool(RedisPoolGuard::capture(
++ backend,
++ "redis_client",
++ STANDALONE_POOL,
++ )?),
++ ("redis", true) => Self::RedisPool(RedisPoolGuard::capture(
++ backend,
++ "redis_client",
++ CLUSTER_POOL,
++ )?),
++ ("valkey-semantic", _) => Self::RedisPool(RedisPoolGuard::capture(
++ backend,
++ "sync_client",
++ VALKEY_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<'_>,
@@@ -240,11 -295,11 +317,16 @@@
"RedisClusterCache",
"redis",
),
+ ("valkey-semantic", false) => (
+ "litellm.caching.valkey_semantic_cache",
+ "ValkeySemanticCache",
+ "valkey-semantic",
+ ),
+ ("azure-blob", _) => (
+ "litellm.caching.azure_blob_cache",
+ "AzureBlobCache",
+ "azure-blob",
+ ),
_ => unreachable!(),
};
let backend = facade.getattr("cache")?;
@@@ -288,36 -343,9 +370,14 @@@
"max_size_per_item",
"redis_kwargs",
"redis_flush_size",
+ "similarity_threshold",
+ "embedding_model",
+ "index_name",
+ "embedding_max_input_tokens",
+ "embedding_timeout",
],
)?,
- redis_pool: match (kind, cluster) {
- ("redis", false) => Some(RedisPoolGuard::capture(
- &backend,
- "redis_client",
- STANDALONE_POOL,
- )?),
- ("redis", true) => Some(RedisPoolGuard::capture(
- &backend,
- "redis_client",
- CLUSTER_POOL,
- )?),
- ("valkey-semantic", false) => Some(RedisPoolGuard::capture(
- &backend,
- "sync_client",
- VALKEY_POOL,
- )?),
- _ => None,
- },
- redis_client_name: match (kind, cluster) {
- ("redis", _) => Some("redis_client"),
- ("valkey-semantic", false) => Some("sync_client"),
- _ => None,
- },
+ connection: ConnectionGuard::capture(kind, cluster, &backend)?,
})
}
diff --cc litellm-rust/crates/python-bridge/src/cache/handle.rs
index 9dff8d723e7,002cd6b7a33..5df3a5f25a2
--- a/litellm-rust/crates/python-bridge/src/cache/handle.rs
+++ b/litellm-rust/crates/python-bridge/src/cache/handle.rs
@@@ -1,11 -1,8 +1,11 @@@
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 super::{cache_error, facade::FacadeGuard, native::NativeResponseCache, request::duration};
+use super::{
+ cache_error, embedder::PythonEmbedder, facade::FacadeGuard, native::NativeResponseCache,
+ request::duration,
+};
#[pyclass(frozen, name = "_CacheTestHandle")]
pub(crate) struct CacheTestHandle {
@@@ -67,29 -64,21 +67,44 @@@ impl CacheTestHandle
})
}
+ #[staticmethod]
+ #[pyo3(signature = (url, similarity_threshold, index_name, embedder))]
+ fn valkey_semantic(
+ url: String,
+ similarity_threshold: f64,
+ index_name: String,
+ embedder: &Bound<'_, PyAny>,
+ ) -> PyResult<Self> {
+ let python_embedder = PythonEmbedder::from_backend(embedder)?;
+ let service = NativeResponseCache::valkey_semantic(
+ &url,
+ similarity_threshold,
+ index_name,
+ python_embedder,
+ )
+ .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 260dc8f349e,2cd72a7ce14..fefc09c1321
--- a/litellm-rust/crates/python-bridge/src/cache/native.rs
+++ b/litellm-rust/crates/python-bridge/src/cache/native.rs
@@@ -1,8 -1,7 +1,9 @@@
use std::{sync::Arc, time::Duration};
-use litellm_cache::{CacheCodec, CacheConnectionResult, Error};
+use litellm_cache::{
+ CacheCodec, CacheConnectionResult, Error, ExactCacheContext, SemanticCacheContext,
+};
+ use litellm_cache_azure_blob::AzureBlobCache;
use litellm_cache_memory::InMemoryCache;
use litellm_cache_redis::{RedisCache, RedisTopology};
use litellm_cache_response::{
@@@ -62,11 -16,7 +63,12 @@@ pub(super) enum NativeResponseCache
cache: Arc<ResponseCache<RedisCache<ResponseCacheCodec>>>,
buffer: Option<Arc<WriteBuffer>>,
},
+ ValkeySemantic {
+ cache: Arc<ResponseCache<ValkeySemanticCache<PythonEmbedder, ResponseCacheCodec>>>,
+ embedder: PythonEmbedder,
+ scope: String,
+ },
+ AzureBlob(Arc<ResponseCache<AzureBlobCache<ResponseCacheCodec>>>),
}
impl NativeResponseCache {
@@@ -98,83 -48,36 +100,107 @@@
})
}
+ pub fn valkey_semantic(
+ url: &str,
+ similarity_threshold: f64,
+ index_name: String,
+ embedder: PythonEmbedder,
+ ) -> Result<Self, Error> {
+ let backend = ValkeySemanticCache::new(
+ url,
+ embedder.clone(),
+ ResponseCacheCodec,
+ ValkeySemanticConfig {
+ similarity_threshold,
+ index_name,
+ },
+ )?;
+ Ok(Self::ValkeySemantic {
+ cache: Arc::new(ResponseCache::new(Arc::new(backend))),
+ embedder,
+ scope: String::from("key"),
+ })
+ }
+
+ 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::ValkeySemantic { .. } => None,
++ }
++ }
++
+ fn exact(request: &NativeRequest) -> ResponseCacheRequest<ExactCacheContext> {
+ ResponseCacheRequest {
+ key: request.key.clone(),
+ controls: request.controls,
+ context: ExactCacheContext { ttl: request.ttl },
+ max_age: request.max_age,
+ }
+ }
+
+ fn semantic(
+ request: &NativeRequest,
+ scope: &str,
+ ) -> ResponseCacheRequest<SemanticCacheContext> {
+ ResponseCacheRequest {
+ key: semantic_key(request, scope),
+ controls: request.controls,
+ context: SemanticCacheContext {
+ input: request.input.clone(),
+ messages: request.messages.clone(),
+ metadata: request.metadata.clone(),
+ scope: Some(scope.to_owned()),
+ ttl: request.ttl,
+ },
+ max_age: request.max_age,
+ }
+ }
+
+ pub fn with_redis_flush_size(self, flush_size: Option<usize>) -> Self {
+ match self {
+ Self::Redis { cache, .. } => Self::Redis {
+ cache,
+ buffer: flush_size.map(|size| Arc::new(WriteBuffer::new(size))),
+ },
+ value => value,
+ }
+ }
+
+ pub fn with_scope(self, scope: String) -> Self {
+ match self {
+ Self::ValkeySemantic {
+ cache, embedder, ..
+ } => Self::ValkeySemantic {
+ cache,
+ embedder,
+ scope,
+ },
+ value => value,
}
}
-}
-impl NativeResponseCache {
pub fn kind(&self) -> &'static str {
match self {
Self::Memory(_) => "memory",
Self::Redis { .. } => "redis",
+ Self::ValkeySemantic { .. } => "valkey-semantic",
+ Self::AzureBlob(_) => "azure-blob",
}
}
@@@ -182,20 -85,20 +208,21 @@@
match self {
Self::Memory(cache) => cache.default_ttl(),
Self::Redis { cache, .. } => cache.default_ttl(),
+ Self::ValkeySemantic { cache, .. } => cache.default_ttl(),
+ Self::AzureBlob(cache) => cache.default_ttl(),
}
}
pub fn namespace(&self) -> Option<&str> {
match self {
- Self::Memory(_) | Self::ValkeySemantic { .. } => None,
- Self::Memory(_) | Self::AzureBlob(_) => None,
++ Self::Memory(_) | Self::ValkeySemantic { .. } | Self::AzureBlob(_) => None,
Self::Redis { cache, .. } => cache.backend().namespace(),
}
}
pub fn topology(&self) -> Option<&RedisTopology> {
match self {
- Self::Memory(_) | Self::ValkeySemantic { .. } => None,
- Self::Memory(_) | Self::AzureBlob(_) => None,
++ Self::Memory(_) | Self::ValkeySemantic { .. } | Self::AzureBlob(_) => None,
Self::Redis { cache, .. } => Some(cache.backend().topology()),
}
}
@@@ -203,14 -106,14 +230,14 @@@
pub fn capacity(&self) -> Option<usize> {
match self {
Self::Memory(cache) => Some(cache.backend().max_size_in_memory()),
- Self::Redis { .. } | Self::ValkeySemantic { .. } => None,
- Self::Redis { .. } | Self::AzureBlob(_) => None,
++ Self::Redis { .. } | Self::ValkeySemantic { .. } | Self::AzureBlob(_) => None,
}
}
pub fn max_entry_bytes(&self) -> Option<usize> {
match self {
Self::Memory(cache) => cache.backend().max_entry_bytes(),
- Self::Redis { .. } | Self::ValkeySemantic { .. } => None,
- Self::Redis { .. } | Self::AzureBlob(_) => None,
++ Self::Redis { .. } | Self::ValkeySemantic { .. } | Self::AzureBlob(_) => None,
}
}
@@@ -224,13 -127,15 +251,14 @@@
}
}
- pub fn lookup(
- &self,
- request: &ResponseCacheRequest,
- now: Duration,
- ) -> Result<Option<Value>, Error> {
+ pub fn lookup(&self, request: &NativeRequest, 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(&Self::exact(request), now),
+ Self::Redis { cache, .. } => cache.lookup(&Self::exact(request), now),
+ Self::ValkeySemantic { cache, scope, .. } => {
+ cache.lookup(&Self::semantic(request, scope), now)
+ }
++ Self::AzureBlob(cache) => cache.lookup(&Self::exact(request), now),
}
}
@@@ -241,11 -146,9 +269,12 @@@
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(&Self::exact(request), response, now),
+ Self::Redis { cache, .. } => cache.store(&Self::exact(request), response, now),
+ Self::ValkeySemantic { cache, scope, .. } => {
+ cache.store(&Self::semantic(request, scope), response, now)
+ }
++ Self::AzureBlob(cache) => cache.store(&Self::exact(request), response, now),
}
}
@@@ -255,15 -158,9 +284,18 @@@
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) => {
+ let requests = requests.iter().map(Self::exact).collect::<Vec<_>>();
+ cache.lookup_batch(&requests, now)
+ }
+ Self::Redis { cache, .. } => {
+ let requests = requests.iter().map(Self::exact).collect::<Vec<_>>();
+ cache.lookup_batch(&requests, now)
+ }
+ Self::ValkeySemantic { .. } => Err(Error::UnsupportedOperation),
++ Self::AzureBlob(cache) => {
++ cache.lookup_batch(&requests.iter().map(Self::exact).collect::<Vec<_>>(), now)
++ }
}
}
@@@ -273,43 -170,9 +305,44 @@@
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(&Self::exact(request), now).await,
+ Self::Redis { cache, .. } => cache.async_lookup(&Self::exact(request), now).await,
+ Self::ValkeySemantic { cache, scope, .. } => {
+ cache
+ .async_lookup(&Self::semantic(request, scope), now)
+ .await
+ }
++ Self::AzureBlob(cache) => cache.async_lookup(&Self::exact(request), now).await,
+ }
+ }
+
+ pub(super) fn async_lookup_py<'py>(
+ &self,
+ py: Python<'py>,
+ request: NativeRequest,
+ ) -> PyResult<Bound<'py, PyAny>> {
+ match self {
- Self::Memory(_) | Self::Redis { .. } => {
++ Self::Memory(_) | Self::Redis { .. } | Self::AzureBlob(_) => {
+ let service = self.clone();
+ litellm_host_python::run_async(
+ py,
+ async move { service.async_lookup(&request, super::request::now()).await },
+ super::cache_error,
+ )
+ }
+ Self::ValkeySemantic {
+ cache,
+ embedder,
+ scope,
+ } => drive_semantic(
+ py,
+ SemanticEmbedExecution::lookup(
+ Arc::clone(cache.backend_arc()),
+ embedder.clone(),
+ Self::semantic(&request, scope),
+ super::request::now(),
+ ),
+ ),
}
}
@@@ -336,52 -191,8 +369,57 @@@
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, &Self::exact(request), response, now)
+ .await
+ }
+ Self::ValkeySemantic { cache, scope, .. } => {
+ cache
+ .async_store(&Self::semantic(request, scope), response, now)
+ .await
+ }
++ Self::AzureBlob(cache) => {
++ cache
++ .async_store(&Self::exact(request), response, now)
++ .await
++ }
+ }
+ }
+
+ pub(super) fn async_store_py<'py>(
+ &self,
+ py: Python<'py>,
+ request: NativeRequest,
+ response: Value,
+ ) -> PyResult<Bound<'py, PyAny>> {
+ match self {
- Self::Memory(_) | Self::Redis { .. } => {
++ Self::Memory(_) | Self::Redis { .. } | Self::AzureBlob(_) => {
+ let service = self.clone();
+ litellm_host_python::run_async(
+ py,
+ async move {
+ service
+ .async_store(&request, response, super::request::now())
+ .await
+ },
+ super::cache_error,
+ )
+ }
+ Self::ValkeySemantic {
+ cache,
+ embedder,
+ scope,
+ } => drive_semantic(
+ py,
+ SemanticEmbedExecution::store(
+ Arc::clone(cache.backend_arc()),
+ embedder.clone(),
+ Self::semantic(&request, scope),
+ response,
+ super::request::now(),
+ ),
+ ),
}
}
@@@ -391,15 -202,9 +429,20 @@@
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) => {
+ let requests = requests.iter().map(Self::exact).collect::<Vec<_>>();
+ cache.async_lookup_batch(&requests, now).await
+ }
+ Self::Redis { cache, .. } => {
+ let requests = requests.iter().map(Self::exact).collect::<Vec<_>>();
+ cache.async_lookup_batch(&requests, now).await
+ }
+ Self::ValkeySemantic { .. } => Err(Error::UnsupportedOperation),
++ Self::AzureBlob(cache) => {
++ cache
++ .async_lookup_batch(&requests.iter().map(Self::exact).collect::<Vec<_>>(), now)
++ .await
++ }
}
}
@@@ -409,68 -214,9 +452,75 @@@
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) => {
+ let entries = entries
+ .into_iter()
+ .map(|(request, value)| (Self::exact(&request), value))
+ .collect();
+ cache.async_store_batch(entries, now).await
+ }
+ Self::Redis { cache, .. } => {
+ let entries = entries
+ .into_iter()
+ .map(|(request, value)| (Self::exact(&request), value))
+ .collect();
+ cache.async_store_batch(entries, now).await
+ }
+ Self::ValkeySemantic { cache, scope, .. } => {
+ let entries = entries
+ .into_iter()
+ .map(|(request, value)| (Self::semantic(&request, scope), value))
+ .collect();
+ cache.async_store_batch(entries, now).await
+ }
++ Self::AzureBlob(cache) => {
++ let entries = entries
++ .into_iter()
++ .map(|(request, value)| (Self::exact(&request), value))
++ .collect();
++ cache.async_store_batch(entries, now).await
++ }
+ }
+ }
+
+ pub(super) fn async_store_batch_py<'py>(
+ &self,
+ py: Python<'py>,
+ entries: Vec<(NativeRequest, Value)>,
+ ) -> PyResult<Bound<'py, PyAny>> {
+ match self {
- Self::Memory(_) | Self::Redis { .. } => {
++ Self::Memory(_) | Self::Redis { .. } | Self::AzureBlob(_) => {
+ let service = self.clone();
+ litellm_host_python::run_async(
+ py,
+ async move {
+ service
+ .async_store_batch(entries, super::request::now())
+ .await
+ },
+ super::cache_error,
+ )
+ }
+ Self::ValkeySemantic {
+ cache,
+ embedder,
+ scope,
+ } => {
+ let (requests, responses): (Vec<_>, Vec<_>) = entries
+ .into_iter()
+ .map(|(request, response)| (Self::semantic(&request, scope), response))
+ .unzip();
+ drive_semantic(
+ py,
+ SemanticEmbedExecution::store_batch(
+ Arc::clone(cache.backend_arc()),
+ embedder.clone(),
+ requests,
+ responses,
+ super::request::now(),
+ ),
+ )
+ }
}
}
@@@ -483,7 -229,7 +533,8 @@@
}
cache.async_flush().await
}
+ Self::ValkeySemantic { .. } => Err(Error::UnsupportedOperation),
+ Self::AzureBlob(cache) => cache.async_flush().await,
}
}
@@@ -491,7 -237,7 +542,8 @@@
match self {
Self::Memory(cache) => cache.test_connection().await,
Self::Redis { cache, .. } => cache.test_connection().await,
+ Self::ValkeySemantic { cache, .. } => cache.test_connection().await,
+ Self::AzureBlob(cache) => cache.test_connection().await,
}
}
}