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 Lee4c9e45f5f188
diff --cc litellm-rust/crates/python-bridge/Cargo.toml
index 25b0a677a2d,4a9ea633ac5..92dadd7253d
--- a/litellm-rust/crates/python-bridge/Cargo.toml
+++ b/litellm-rust/crates/python-bridge/Cargo.toml
@@@ -24,9 -24,9 +24,10 @@@ litellm-cache.workspace = tru
litellm-cache-azure-blob.workspace = true
litellm-cache-memory.workspace = true
litellm-cache-redis.workspace = true
+ litellm-cache-gcs.workspace = true
litellm-cache-disk.workspace = true
litellm-cache-response.workspace = true
+litellm-cache-valkey-semantic = { path = "../cache-valkey-semantic" }
serde.workspace = true
litellm-auth.workspace = true
litellm-callbacks-legacy-python.workspace = true
diff --cc litellm-rust/crates/python-bridge/src/cache/config.rs
index b91fbee603c,6c180708335..975a569771c
--- a/litellm-rust/crates/python-bridge/src/cache/config.rs
+++ b/litellm-rust/crates/python-bridge/src/cache/config.rs
@@@ -79,6 -79,18 +79,13 @@@ 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,
@@@ -106,7 -105,7 +113,8 @@@ pub(super) struct AzureBlobCacheConfig
pub(super) enum CacheBackendConfig {
Memory(MemoryCacheConfig),
Redis(Box<RedisCacheConfig>),
+ Gcs(GcsCacheConfig),
+ ValkeySemantic(Box<ValkeySemanticCacheConfig>),
Disk(DiskCacheConfig),
AzureBlob(AzureBlobCacheConfig),
}
@@@ -177,13 -178,13 +187,20 @@@ 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::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::Disk) => match project_disk(&backend)? {
Ok(backend) => Ok(CacheConfigProjection::Native(Box::new(Self {
policy,
@@@ -197,15 -198,15 +214,11 @@@
backend: CacheBackendConfig::AzureBlob(backend),
}))
}),
-- Some(
-- CacheType::RedisSemantic
- | CacheType::ValkeySemantic
-- | CacheType::S3
- | CacheType::QdrantSemantic
- | CacheType::Gcs,
- | CacheType::QdrantSemantic,
-- )
-- | None => Ok(CacheConfigProjection::Unsupported(
-- UnsupportedCacheConfig::Backend,
-- )),
++ Some(CacheType::RedisSemantic | CacheType::S3 | CacheType::QdrantSemantic) | None => {
++ Ok(CacheConfigProjection::Unsupported(
++ UnsupportedCacheConfig::Backend,
++ ))
++ }
}
}
@@@ -213,13 -214,11 +226,14 @@@
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::Disk(_) => None,
- CacheBackendConfig::AzureBlob(_) => None,
+ CacheBackendConfig::Disk(_)
+ | CacheBackendConfig::AzureBlob(_)
+ | CacheBackendConfig::Gcs(_) => None,
};
- if service.default_ttl() != default_ttl {
+ if !matches!(self.backend, CacheBackendConfig::ValkeySemantic(_))
+ && service.default_ttl() != default_ttl
+ {
return Some("facade and native backend default TTLs must match");
}
match &self.backend {
@@@ -244,16 -243,31 +258,41 @@@
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::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::Disk(_) if service.kind() != "disk" => {
Some("facade and native backend types must match")
}
@@@ -772,8 -738,8 +828,8 @@@ mod tests
use litellm_cache_redis::{RedisNode, RedisTopology};
use super::{
- CacheBackendConfig, CacheConfigProjection, CertificateRequirement, NativeCacheConfig,
- RedisProtocol,
- CacheBackendConfig, CacheConfigProjection, CachePolicy, CertificateRequirement,
- DiskCacheConfig, GcsCacheConfig, NativeCacheConfig, RedisProtocol, UnsupportedCacheConfig,
++ CacheBackendConfig, CacheConfigProjection, CertificateRequirement, GcsCacheConfig,
++ NativeCacheConfig, RedisProtocol, UnsupportedCacheConfig,
};
use crate::cache::native::NativeResponseCache;
@@@ -1036,6 -1065,6 +1092,71 @@@
});
}
++ #[test]
++ fn projects_gcs_configuration() {
++ Python::initialize();
++ Python::attach(|py| {
++ let facade = facade(
++ py,
++ "backend = SimpleNamespace(bucket_name='bucket', key_prefix='cache/', path_service_account='credentials.json')\n\
++ facade = SimpleNamespace(type='gcs', mode='default-on', ttl=None, namespace=None, supported_call_types=None, redis_flush_size=None, semantic_cache_scope='key', cache=backend)",
++ );
++ let CacheConfigProjection::Native(config) =
++ NativeCacheConfig::project(&facade).unwrap()
++ else {
++ panic!("GCS cache should be supported");
++ };
++ let CacheBackendConfig::Gcs(gcs) = config.backend else {
++ panic!("expected GCS configuration");
++ };
++ assert_eq!(
++ gcs,
++ GcsCacheConfig {
++ bucket_name: "bucket".into(),
++ key_prefix: "cache/".into(),
++ path_service_account: Some("credentials.json".into()),
++ }
++ );
++ let matching = NativeResponseCache::gcs(
++ litellm_cache_gcs::GcsConfig {
++ bucket_name: "bucket".into(),
++ gcs_path: Some("cache/".into()),
++ path_service_account: Some("credentials.json".into()),
++ endpoint: litellm_cache_gcs::DEFAULT_ENDPOINT.into(),
++ },
++ Some("token".into()),
++ )
++ .unwrap();
++ let matching_config = NativeCacheConfig {
++ policy: config.policy,
++ backend: CacheBackendConfig::Gcs(gcs),
++ };
++ assert_eq!(matching_config.service_mismatch(&matching), None);
++ });
++ }
++
++ #[test]
++ fn rejects_gcs_without_a_bucket_name() {
++ Python::initialize();
++ Python::attach(|py| {
++ let facade = facade(
++ py,
++ "backend = SimpleNamespace(bucket_name=None, key_prefix='', path_service_account=None)\n\
++ facade = SimpleNamespace(type='gcs', mode='default-on', ttl=None, namespace=None, supported_call_types=None, redis_flush_size=None, semantic_cache_scope='key', cache=backend)",
++ );
++ let CacheConfigProjection::Unsupported(reason) =
++ NativeCacheConfig::project(&facade).unwrap()
++ else {
++ panic!("GCS cache without a bucket should be unsupported");
++ };
++ assert!(matches!(&reason, UnsupportedCacheConfig::GcsBucket));
++ assert_eq!(
++ reason.message(),
++ "native GCS cache requires a configured bucket name"
++ );
++ });
++ }
++
#[test]
fn malformed_startup_nodes_and_foreign_connect_hooks_stay_on_python() {
Python::initialize();
diff --cc litellm-rust/crates/python-bridge/src/cache/facade.rs
index 085db26c0d7,0fa4511b1c1..dd3f66451ca
--- a/litellm-rust/crates/python-bridge/src/cache/facade.rs
+++ b/litellm-rust/crates/python-bridge/src/cache/facade.rs
@@@ -344,11 -320,7 +344,12 @@@ impl FacadeGuard
"RedisClusterCache",
"redis",
),
+ ("gcs", _) => ("litellm.caching.gcs_cache", "GCSCache", "gcs"),
+ ("valkey-semantic", false) => (
+ "litellm.caching.valkey_semantic_cache",
+ "ValkeySemanticCache",
+ "valkey-semantic",
+ ),
("disk", _) => ("litellm.caching.disk_cache", "DiskCache", "disk"),
("azure-blob", _) => (
"litellm.caching.azure_blob_cache",
@@@ -398,11 -370,9 +399,14 @@@
"max_size_per_item",
"redis_kwargs",
"redis_flush_size",
+ "similarity_threshold",
+ "embedding_model",
+ "index_name",
+ "embedding_max_input_tokens",
+ "embedding_timeout",
+ "bucket_name",
+ "key_prefix",
+ "path_service_account",
],
)?,
disk_store: (kind == "disk")
diff --cc litellm-rust/crates/python-bridge/src/cache/handle.rs
index 273252d36dc,64ac3696e80..fe7287ee2d9
--- a/litellm-rust/crates/python-bridge/src/cache/handle.rs
+++ b/litellm-rust/crates/python-bridge/src/cache/handle.rs
@@@ -1,3 -1,3 +1,4 @@@
++use litellm_cache_gcs::{DEFAULT_ENDPOINT, GcsConfig};
use litellm_cache_redis::{RedisNode, RedisTopology};
use litellm_host_python::{release_gil, run_sync_value};
use pyo3::{PyTraverseError, PyVisit, exceptions::PyRuntimeError, prelude::*};
diff --cc litellm-rust/crates/python-bridge/src/cache/native.rs
index 5f2ddf484a6,b10f9e2a443..914ad71affb
--- a/litellm-rust/crates/python-bridge/src/cache/native.rs
+++ b/litellm-rust/crates/python-bridge/src/cache/native.rs
@@@ -1,10 -1,9 +1,11 @@@
use std::{path::Path, 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_disk::DiskCache;
+ use litellm_cache_gcs::{GcsCache, GcsConfig, StaticTokenSource};
use litellm_cache_memory::InMemoryCache;
use litellm_cache_redis::{RedisCache, RedisTopology};
use litellm_cache_response::{
@@@ -77,11 -18,7 +78,12 @@@ pub(super) enum NativeResponseCache
cache: Arc<ResponseCache<RedisCache<ResponseCacheCodec>>>,
buffer: Option<Arc<WriteBuffer>>,
},
+ Gcs(Arc<ResponseCache<GcsCache<ResponseCacheCodec>>>),
+ ValkeySemantic {
+ cache: Arc<ResponseCache<ValkeySemanticCache<PythonEmbedder, ResponseCacheCodec>>>,
+ embedder: PythonEmbedder,
+ scope: String,
+ },
Disk(Arc<ResponseCache<DiskCache<ResponseCacheCodec>>>),
AzureBlob(Arc<ResponseCache<AzureBlobCache<ResponseCacheCodec>>>),
}
@@@ -161,67 -87,17 +175,70 @@@ impl NativeResponseCache
cache.backend().account_url(),
cache.backend().container_name(),
)),
- Self::Memory(_) | Self::Redis { .. } | Self::ValkeySemantic { .. } | Self::Disk(_) => {
- None
- }
- Self::Memory(_) | Self::Redis { .. } | Self::Disk(_) | Self::Gcs(_) => None,
++ Self::Memory(_)
++ | Self::Redis { .. }
++ | Self::ValkeySemantic { .. }
++ | Self::Disk(_)
++ | Self::Gcs(_) => 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::Gcs(_) => "gcs",
+ Self::ValkeySemantic { .. } => "valkey-semantic",
Self::Disk(_) => "disk",
Self::AzureBlob(_) => "azure-blob",
}
@@@ -231,7 -107,7 +248,8 @@@
match self {
Self::Memory(cache) => cache.default_ttl(),
Self::Redis { cache, .. } => cache.default_ttl(),
+ Self::Gcs(cache) => cache.default_ttl(),
+ Self::ValkeySemantic { cache, .. } => cache.default_ttl(),
Self::Disk(cache) => cache.default_ttl(),
Self::AzureBlob(cache) => cache.default_ttl(),
}
@@@ -239,18 -115,15 +257,22 @@@
pub fn namespace(&self) -> Option<&str> {
match self {
- Self::Memory(_) | Self::ValkeySemantic { .. } | Self::Disk(_) | Self::AzureBlob(_) => {
- None
- }
- Self::Memory(_) | Self::Disk(_) | Self::AzureBlob(_) => None,
++ Self::Memory(_)
++ | Self::ValkeySemantic { .. }
++ | Self::Disk(_)
++ | Self::AzureBlob(_)
++ | Self::Gcs(_) => None,
Self::Redis { cache, .. } => cache.backend().namespace(),
- Self::Gcs(_) => None,
}
}
pub fn topology(&self) -> Option<&RedisTopology> {
match self {
- Self::Memory(_) | Self::ValkeySemantic { .. } | Self::Disk(_) | Self::AzureBlob(_) => {
- None
- }
- Self::Memory(_) | Self::Disk(_) | Self::AzureBlob(_) | Self::Gcs(_) => None,
++ Self::Memory(_)
++ | Self::ValkeySemantic { .. }
++ | Self::Disk(_)
++ | Self::AzureBlob(_)
++ | Self::Gcs(_) => None,
Self::Redis { cache, .. } => Some(cache.backend().topology()),
}
}
@@@ -258,30 -131,24 +280,33 @@@
pub fn capacity(&self) -> Option<usize> {
match self {
Self::Memory(cache) => Some(cache.backend().max_size_in_memory()),
- Self::Redis { .. } | Self::Disk(_) | Self::AzureBlob(_) | Self::Gcs(_) => None,
+ Self::Redis { .. }
+ | Self::ValkeySemantic { .. }
+ | Self::Disk(_)
- | Self::AzureBlob(_) => None,
++ | 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 { .. } | Self::Disk(_) | Self::AzureBlob(_) | Self::Gcs(_) => None,
+ Self::Redis { .. }
+ | Self::ValkeySemantic { .. }
+ | Self::Disk(_)
- | Self::AzureBlob(_) => None,
++ | Self::AzureBlob(_)
++ | Self::Gcs(_) => None,
}
}
- pub fn with_redis_flush_size(self, flush_size: Option<usize>) -> Self {
+ pub fn directory(&self) -> Option<&Path> {
match self {
- Self::Redis { cache, .. } => Self::Redis {
- cache,
- buffer: flush_size.map(|flush_size| Arc::new(WriteBuffer::new(flush_size))),
- },
- other => other,
+ Self::Disk(cache) => Some(cache.backend().directory()),
+ Self::Memory(_)
+ | Self::Redis { .. }
+ | Self::ValkeySemantic { .. }
- | Self::AzureBlob(_) => None,
++ | Self::AzureBlob(_)
++ | Self::Gcs(_) => None,
}
}
@@@ -295,15 -159,17 +320,16 @@@
}
}
- 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::Gcs(cache) => cache.lookup(request, now),
- Self::Disk(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::Gcs(cache) => cache.lookup(&Self::exact(request), now),
+ Self::Disk(cache) => cache.lookup(&Self::exact(request), now),
+ Self::AzureBlob(cache) => cache.lookup(&Self::exact(request), now),
}
}
@@@ -314,13 -180,11 +340,14 @@@
now: Duration,
) -> Result<(), Error> {
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::Disk(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::Gcs(cache) => cache.store(&Self::exact(request), response, now),
+ Self::Disk(cache) => cache.store(&Self::exact(request), response, now),
+ Self::AzureBlob(cache) => cache.store(&Self::exact(request), response, now),
}
}
@@@ -330,21 -194,11 +357,24 @@@
now: Duration,
) -> Result<PartialHits, Error> {
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::Disk(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::Gcs(cache) => {
++ cache.lookup_batch(&requests.iter().map(Self::exact).collect::<Vec<_>>(), now)
++ }
+ Self::Disk(cache) => {
+ cache.lookup_batch(&requests.iter().map(Self::exact).collect::<Vec<_>>(), now)
+ }
+ Self::AzureBlob(cache) => {
+ cache.lookup_batch(&requests.iter().map(Self::exact).collect::<Vec<_>>(), now)
+ }
}
}
@@@ -354,44 -208,11 +384,49 @@@
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::Gcs(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,
+ 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::Gcs(cache) => cache.async_lookup(&Self::exact(request), now).await,
+ Self::Disk(cache) => cache.async_lookup(&Self::exact(request), 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::Disk(_) | Self::AzureBlob(_) => {
++ Self::Memory(_)
++ | Self::Redis { .. }
++ | Self::Disk(_)
++ | Self::AzureBlob(_)
++ | Self::Gcs(_) => {
+ 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),
+ ),
+ ),
}
}
@@@ -418,61 -231,10 +453,70 @@@
Self::Redis {
cache,
buffer: Some(buffer),
- } => buffer.async_store(cache, request, response, now).await,
- Self::Gcs(cache) => cache.async_store(request, response, now).await,
- Self::Disk(cache) => cache.async_store(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::Gcs(cache) => {
++ cache
++ .async_store(&Self::exact(request), response, now)
++ .await
++ }
+ Self::Disk(cache) => {
+ cache
+ .async_store(&Self::exact(request), 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::Disk(_) | Self::AzureBlob(_) => {
++ Self::Memory(_)
++ | Self::Redis { .. }
++ | Self::Disk(_)
++ | Self::AzureBlob(_)
++ | Self::Gcs(_) => {
+ 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,
+ ),
+ ),
}
}
@@@ -482,25 -244,11 +526,30 @@@
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::Gcs(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,
+ 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::Gcs(cache) => {
++ cache
++ .async_lookup_batch(&requests.iter().map(Self::exact).collect::<Vec<_>>(), now)
++ .await
++ }
+ Self::Disk(cache) => {
+ cache
+ .async_lookup_batch(&requests.iter().map(Self::exact).collect::<Vec<_>>(), now)
+ .await
+ }
+ Self::AzureBlob(cache) => {
+ cache
+ .async_lookup_batch(&requests.iter().map(Self::exact).collect::<Vec<_>>(), now)
+ .await
+ }
}
}
@@@ -510,81 -258,11 +559,92 @@@
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::Gcs(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,
+ 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::Gcs(cache) => {
++ let entries = entries
++ .into_iter()
++ .map(|(request, value)| (Self::exact(&request), value))
++ .collect();
++ cache.async_store_batch(entries, now).await
++ }
+ Self::Disk(cache) => {
+ let entries = entries
+ .into_iter()
+ .map(|(request, value)| (Self::exact(&request), 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::Disk(_) | Self::AzureBlob(_) => {
++ Self::Memory(_)
++ | Self::Redis { .. }
++ | Self::Disk(_)
++ | Self::AzureBlob(_)
++ | Self::Gcs(_) => {
+ 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,
+ ),
+ )
+ }
}
}
@@@ -597,7 -275,7 +657,8 @@@
}
cache.async_flush().await
}
+ Self::ValkeySemantic { .. } => Err(Error::UnsupportedOperation),
+ Self::Gcs(cache) => cache.async_flush().await,
Self::Disk(cache) => cache.async_flush().await,
Self::AzureBlob(cache) => cache.async_flush().await,
}
@@@ -607,85 -285,16 +668,93 @@@
match self {
Self::Memory(cache) => cache.test_connection().await,
Self::Redis { cache, .. } => cache.test_connection().await,
+ Self::ValkeySemantic { cache, .. } => cache.test_connection().await,
+ Self::Gcs(cache) => cache.test_connection().await,
Self::Disk(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,
+ }
+ }
}
+
+#[cfg(test)]
+mod tests {
+ use litellm_cache_response::{CacheControls, CacheKeyInput, cache_key};
+ use serde_json::json;
+ use sha2::{Digest, Sha256};
+
+ use super::*;
+
+ fn native_request(key: CacheKeyInput, metadata: Value) -> NativeRequest {
+ NativeRequest {
+ key,
+ controls: CacheControls::default(),
+ ttl: None,
+ max_age: None,
+ messages: Some(json!([{"role": "user", "content": "prompt"}])),
+ input: None,
+ metadata: Some(metadata),
+ litellm_metadata: None,
+ litellm_params: None,
+ }
+ }
+
+ #[test]
+ fn semantic_key_matches_python_scope_material() {
+ let key = CacheKeyInput {
+ fields: vec![
+ CacheKeyField {
+ name: "model".to_owned(),
+ value: Some("gpt-4.1".to_owned()),
+ api_parameter: true,
+ internal_parameter: false,
+ },
+ CacheKeyField {
+ name: "messages".to_owned(),
+ value: Some("prompt".to_owned()),
+ api_parameter: true,
+ internal_parameter: false,
+ },
+ ],
+ ..Default::default()
+ };
+ let request = native_request(
+ key,
+ json!({"user_api_key": "k1", "user_api_key_team_id": null}),
+ );
+ let expected = format!("{:x}", Sha256::digest(b"model: gpt-4.1user_api_key: k1"));
+ assert_eq!(cache_key(&semantic_key(&request, "key")), expected);
+
+ let end_user_request = native_request(
+ request.key.clone(),
+ json!({"user_api_key": "k1", "user_api_key_end_user_id": "u1"}),
+ );
+ let expected = format!(
+ "{:x}",
+ Sha256::digest(b"model: gpt-4.1user_api_key: k1user_api_key_end_user_id: u1")
+ );
+ assert_eq!(
+ cache_key(&semantic_key(&end_user_request, "end_user")),
+ expected
+ );
+
+ let preset_request = native_request(
+ CacheKeyInput {
+ preset: Some("preset-key".to_owned()),
+ ..Default::default()
+ },
+ json!({"user_api_key": "k1"}),
+ );
+ assert_eq!(
+ semantic_key(&preset_request, "end_user").preset.as_deref(),
+ Some("preset-key")
+ );
+ assert!(semantic_key(&preset_request, "end_user").fields.is_empty());
+ }
+}