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 Lee2eee880abac1
diff --cc litellm-rust/Cargo.lock
index f19ebf91713,de234fa3afa..c02f460f22e
--- a/litellm-rust/Cargo.lock
+++ b/litellm-rust/Cargo.lock
@@@ -2664,22 -2757,21 +2757,37 @@@ dependencies =
"tokio",
]
+ [[package]]
+ name = "litellm-cache-s3"
+ version = "0.1.0"
+ dependencies = [
+ "aws-credential-types",
+ "aws-sdk-s3",
+ "aws-smithy-types",
+ "aws-types",
+ "litellm-auth-aws",
+ "litellm-cache",
+ "serde_json",
+ "tokio",
+ "wiremock",
+ ]
+
+[[package]]
+name = "litellm-cache-valkey-semantic"
+version = "0.1.0"
+dependencies = [
+ "litellm-cache",
+ "litellm-cache-redis",
+ "litellm-cache-response",
+ "redis",
+ "redis-test",
+ "rstest",
+ "serde_json",
+ "sha2 0.10.9",
+ "tokio",
+ "uuid",
+]
+
[[package]]
name = "litellm-callbacks-legacy-python"
version = "0.1.0"
@@@ -2850,7 -2943,7 +2959,8 @@@ dependencies =
"litellm-cache-memory",
"litellm-cache-redis",
"litellm-cache-response",
+ "litellm-cache-s3",
+ "litellm-cache-valkey-semantic",
"litellm-callbacks-legacy-python",
"litellm-core",
"litellm-core-utils",
diff --cc litellm-rust/crates/python-bridge/Cargo.toml
index 92dadd7253d,9191e61a25c..d07a9839ebf
--- a/litellm-rust/crates/python-bridge/Cargo.toml
+++ b/litellm-rust/crates/python-bridge/Cargo.toml
@@@ -27,9 -28,9 +28,10 @@@ litellm-cache-s3.workspace = tru
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-auth-aws.workspace = true
litellm-callbacks-legacy-python.workspace = true
litellm-core.workspace = true
litellm-core-utils.workspace = true
diff --cc litellm-rust/crates/python-bridge/src/cache/config.rs
index 975a569771c,7316b3e259c..9bc666c4f2d
--- a/litellm-rust/crates/python-bridge/src/cache/config.rs
+++ b/litellm-rust/crates/python-bridge/src/cache/config.rs
@@@ -113,8 -107,8 +115,9 @@@ pub(super) struct AzureBlobCacheConfig
pub(super) enum CacheBackendConfig {
Memory(MemoryCacheConfig),
Redis(Box<RedisCacheConfig>),
+ S3(Box<S3CacheConfig>),
Gcs(GcsCacheConfig),
+ ValkeySemantic(Box<ValkeySemanticCacheConfig>),
Disk(DiskCacheConfig),
AzureBlob(AzureBlobCacheConfig),
}
@@@ -214,11 -214,12 +230,9 @@@ impl NativeCacheConfig
backend: CacheBackendConfig::AzureBlob(backend),
}))
}),
- Some(CacheType::RedisSemantic | CacheType::S3 | CacheType::QdrantSemantic) | None => {
- Ok(CacheConfigProjection::Unsupported(
- UnsupportedCacheConfig::Backend,
- ))
- }
- Some(
- CacheType::RedisSemantic | CacheType::ValkeySemantic | CacheType::QdrantSemantic,
- )
- | None => Ok(CacheConfigProjection::Unsupported(
- UnsupportedCacheConfig::Backend,
- )),
++ Some(CacheType::RedisSemantic | CacheType::QdrantSemantic) | None => Ok(
++ CacheConfigProjection::Unsupported(UnsupportedCacheConfig::Backend),
++ ),
}
}
@@@ -226,7 -227,7 +240,8 @@@
let default_ttl = match &self.backend {
CacheBackendConfig::Memory(config) => Some(config.default_ttl),
CacheBackendConfig::Redis(config) => Some(config.default_ttl),
+ CacheBackendConfig::S3(_) => None,
+ CacheBackendConfig::ValkeySemantic(_) => Some(Duration::ZERO),
CacheBackendConfig::Disk(_)
| CacheBackendConfig::AzureBlob(_)
| CacheBackendConfig::Gcs(_) => None,
diff --cc litellm-rust/crates/python-bridge/src/cache/facade.rs
index dd3f66451ca,e89d0fc9715..4b4e3255cb4
--- a/litellm-rust/crates/python-bridge/src/cache/facade.rs
+++ b/litellm-rust/crates/python-bridge/src/cache/facade.rs
@@@ -47,13 -49,12 +47,18 @@@ struct AzureBlobClientGuard
container_name: String,
}
++struct S3ClientGuard {
++ reference: Py<PyAny>,
++}
++
enum ConnectionGuard {
None,
RedisPool(RedisPoolGuard),
AzureBlob(AzureBlobClientGuard),
+ S3(S3ClientGuard),
}
+
+#[derive(Clone, Copy)]
struct RedisPoolAttributes {
pool: &'static str,
connection_class: &'static str,
@@@ -281,26 -289,13 +286,43 @@@ impl AzureBlobClientGuard
}
}
++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 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,
+ )?),
+ ("disk", _) => Self::None,
("azure-blob", _) => Self::AzureBlob(AzureBlobClientGuard::capture(backend)?),
+ ("s3", _) => Self::S3(S3ClientGuard::capture(backend)?),
_ => Self::None,
})
}
@@@ -356,6 -348,6 +380,7 @@@ impl FacadeGuard
"AzureBlobCache",
"azure-blob",
),
++ ("s3", _) => ("litellm.caching.s3_cache", "S3Cache", "s3"),
_ => unreachable!(),
};
let backend = facade.getattr("cache")?;
diff --cc litellm-rust/crates/python-bridge/src/cache/handle.rs
index fe7287ee2d9,d6e622a5c49..769ad3548be
--- a/litellm-rust/crates/python-bridge/src/cache/handle.rs
+++ b/litellm-rust/crates/python-bridge/src/cache/handle.rs
@@@ -1,5 -1,6 +1,7 @@@
+ use litellm_auth_aws::AwsAuthConfig;
+use litellm_cache_gcs::{DEFAULT_ENDPOINT, GcsConfig};
use litellm_cache_redis::{RedisNode, RedisTopology};
+ use litellm_cache_s3::{S3CacheConfig, S3Endpoint};
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 914ad71affb,39496890009..575dae45833
--- a/litellm-rust/crates/python-bridge/src/cache/native.rs
+++ b/litellm-rust/crates/python-bridge/src/cache/native.rs
@@@ -9,68 -7,11 +9,69 @@@ use litellm_cache_gcs::{GcsCache, GcsCo
use litellm_cache_memory::InMemoryCache;
use litellm_cache_redis::{RedisCache, RedisTopology};
use litellm_cache_response::{
- CacheEntry, PartialHits, ResponseCache, ResponseCacheCodec, ResponseCacheRequest, WriteBuffer,
+ CacheEntry, CacheKeyField, PartialHits, ResponseCache, ResponseCacheCodec,
+ ResponseCacheRequest, WriteBuffer,
};
+ use litellm_cache_s3::{S3Cache, S3CacheConfig};
+use litellm_cache_valkey_semantic::{ValkeySemanticCache, ValkeySemanticConfig};
+use pyo3::prelude::*;
use serde_json::Value;
+use super::{
+ embedder::PythonEmbedder,
+ request::NativeRequest,
+ semantic_step::{SemanticEmbedExecution, drive_semantic},
+};
+
+fn semantic_key(request: &NativeRequest, scope: &str) -> litellm_cache_response::CacheKeyInput {
+ let mut key = request.key.clone();
+ if key.preset.is_some() {
+ return key;
+ }
+ key.fields
+ .retain(|field| !matches!(field.name.as_str(), "messages" | "prompt" | "input"));
+ const TENANT: [&str; 3] = [
+ "user_api_key",
+ "user_api_key_team_id",
+ "user_api_key_org_id",
+ ];
+ let end_user = (scope == "end_user").then_some("user_api_key_end_user_id");
+ for name in TENANT.into_iter().chain(end_user) {
+ let sources = [
+ request.metadata.as_ref(),
+ request.litellm_metadata.as_ref(),
+ request
+ .litellm_params
+ .as_ref()
+ .and_then(|params| params.get("metadata")),
+ request
+ .litellm_params
+ .as_ref()
+ .and_then(|params| params.get("litellm_metadata")),
+ ];
+ let Some(value) = sources.into_iter().flatten().find_map(|source| {
+ source
+ .as_object()
+ .and_then(|values| values.get(name))
+ .filter(|value| !value.is_null())
+ }) else {
+ continue;
+ };
+ let value = match value {
+ Value::Null => continue,
+ Value::String(text) => text.clone(),
+ other => other.to_string(),
+ };
+ key.fields.push(CacheKeyField {
+ name: name.to_owned(),
+ value: Some(value),
+ api_parameter: true,
+ internal_parameter: false,
+ });
+ }
+ key
+}
+
#[derive(Clone)]
pub(super) enum NativeResponseCache {
Memory(Arc<ResponseCache<InMemoryCache<CacheEntry>>>),
@@@ -78,12 -19,8 +79,13 @@@
cache: Arc<ResponseCache<RedisCache<ResponseCacheCodec>>>,
buffer: Option<Arc<WriteBuffer>>,
},
+ S3(Arc<ResponseCache<S3Cache<ResponseCacheCodec>>>),
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>>>),
}
@@@ -116,29 -53,14 +118,38 @@@ impl NativeResponseCache
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 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 fn disk(directory: &str) -> Result<Self, Error> {
let cache = DiskCache::open(directory, ResponseCacheCodec)?;
Ok(Self::Disk(Arc::new(ResponseCache::new(Arc::new(cache)))))
@@@ -175,70 -97,20 +186,72 @@@
cache.backend().account_url(),
cache.backend().container_name(),
)),
- Self::Memory(_) | Self::Redis { .. } | Self::S3(_) | Self::Disk(_) | Self::Gcs(_) => {
- None
- }
+ Self::Memory(_)
+ | Self::Redis { .. }
++ | Self::S3(_)
+ | 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::S3(_) => "s3",
Self::Gcs(_) => "gcs",
+ Self::ValkeySemantic { .. } => "valkey-semantic",
Self::Disk(_) => "disk",
Self::AzureBlob(_) => "azure-blob",
}
@@@ -248,32 -120,54 +261,63 @@@
match self {
Self::Memory(cache) => cache.default_ttl(),
Self::Redis { cache, .. } => cache.default_ttl(),
+ Self::S3(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(),
}
}
+ 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(_) | Self::Disk(_) | Self::AzureBlob(_) => None,
+ Self::Memory(_)
++ | Self::S3(_)
+ | Self::ValkeySemantic { .. }
+ | Self::Disk(_)
+ | Self::AzureBlob(_)
+ | Self::Gcs(_) => None,
Self::Redis { cache, .. } => cache.backend().namespace(),
- Self::S3(_) | Self::Gcs(_) => None,
}
}
pub fn topology(&self) -> Option<&RedisTopology> {
match self {
- Self::Memory(_) | Self::Disk(_) | Self::AzureBlob(_) | Self::Gcs(_) => None,
+ Self::Memory(_)
++ | Self::S3(_)
+ | Self::ValkeySemantic { .. }
+ | Self::Disk(_)
+ | Self::AzureBlob(_)
+ | Self::Gcs(_) => None,
Self::Redis { cache, .. } => Some(cache.backend().topology()),
- Self::S3(_) => None,
}
}
@@@ -281,7 -175,7 +325,8 @@@
match self {
Self::Memory(cache) => Some(cache.backend().max_size_in_memory()),
Self::Redis { .. }
+ | Self::S3(_)
+ | Self::ValkeySemantic { .. }
| Self::Disk(_)
| Self::AzureBlob(_)
| Self::Gcs(_) => None,
@@@ -292,7 -186,7 +337,8 @@@
match self {
Self::Memory(cache) => cache.backend().max_entry_bytes(),
Self::Redis { .. }
+ | Self::S3(_)
+ | Self::ValkeySemantic { .. }
| Self::Disk(_)
| Self::AzureBlob(_)
| Self::Gcs(_) => None,
@@@ -304,32 -208,24 +350,34 @@@
Self::Disk(cache) => Some(cache.backend().directory()),
Self::Memory(_)
| Self::Redis { .. }
+ | Self::S3(_)
+ | Self::ValkeySemantic { .. }
| Self::AzureBlob(_)
| Self::Gcs(_) => None,
}
}
- pub fn lookup(
- &self,
- request: &ResponseCacheRequest,
- now: Duration,
- ) -> Result<Option<Value>, Error> {
+ pub fn semantic_config(&self) -> Option<(f64, &str)> {
match self {
- Self::Memory(cache) => cache.lookup(request, now),
- Self::Redis { cache, .. } => cache.lookup(request, now),
- Self::S3(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::ValkeySemantic { cache, .. } => Some((
+ cache.backend().similarity_threshold(),
+ cache.backend().index_name(),
+ )),
+ _ => None,
+ }
+ }
+
+ pub fn lookup(&self, request: &NativeRequest, now: Duration) -> Result<Option<Value>, Error> {
+ match self {
+ Self::Memory(cache) => cache.lookup(&Self::exact(request), now),
+ Self::Redis { cache, .. } => cache.lookup(&Self::exact(request), now),
++ Self::S3(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),
}
}
@@@ -340,14 -236,12 +388,15 @@@
now: Duration,
) -> Result<(), Error> {
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::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::S3(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),
}
}
@@@ -357,24 -251,12 +406,27 @@@
now: Duration,
) -> Result<PartialHits, Error> {
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::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::S3(cache) => {
++ cache.lookup_batch(&requests.iter().map(Self::exact).collect::<Vec<_>>(), 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)
+ }
}
}
@@@ -384,49 -266,12 +436,51 @@@
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::S3(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::S3(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::S3(_)
+ | 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),
+ ),
+ ),
}
}
@@@ -453,70 -290,11 +507,76 @@@
Self::Redis {
cache,
buffer: Some(buffer),
- } => buffer.async_store(cache, request, response, now).await,
- Self::S3(cache) => cache.async_store(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::S3(cache) => {
++ cache
++ .async_store(&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::S3(_)
+ | 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,
+ ),
+ ),
}
}
@@@ -526,30 -304,12 +586,35 @@@
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::S3(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::S3(cache) => {
++ cache
++ .async_lookup_batch(&requests.iter().map(Self::exact).collect::<Vec<_>>(), 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
+ }
}
}
@@@ -559,92 -319,12 +624,100 @@@
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::S3(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::S3(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::S3(_)
+ | 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,
+ ),
+ )
+ }
}
}
@@@ -657,7 -337,7 +730,8 @@@
}
cache.async_flush().await
}
+ Self::S3(cache) => 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,
@@@ -668,7 -348,7 +742,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::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,