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_rust_qdrant_semantic_cache

Yujong Leeeec133dc275e
diff --cc litellm-rust/Cargo.lock
index 382009c95af,1a4eb51af08..fa0ec7fcb96
--- a/litellm-rust/Cargo.lock
+++ b/litellm-rust/Cargo.lock
@@@ -2806,8 -2814,8 +2877,9 @@@ dependencies =
"litellm-auth-gcp",
"litellm-cache",
"litellm-cache-azure-blob",
+ "litellm-cache-disk",
"litellm-cache-memory",
+ "litellm-cache-qdrant-semantic",
"litellm-cache-redis",
"litellm-cache-response",
"litellm-callbacks-legacy-python",
diff --cc litellm-rust/Cargo.toml
index a8cddfc3886,fabec9bcd6c..bb56210436a
--- a/litellm-rust/Cargo.toml
+++ b/litellm-rust/Cargo.toml
@@@ -32,8 -32,8 +32,9 @@@ 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-disk = { path = "crates/cache-disk" }
litellm-cache-response = { path = "crates/cache-response" }
+litellm-cache-qdrant-semantic = { path = "crates/cache-qdrant-semantic" }
litellm-token-counter = { path = "crates/token-counter" }
litellm-token-counter-fast = { path = "crates/token-counter-fast" }
litellm-token-counter-huggingface = { path = "crates/token-counter-huggingface" }
diff --cc litellm-rust/crates/python-bridge/Cargo.toml
index 0b9a0148d07,f5d08850b39..d214118a224
--- a/litellm-rust/crates/python-bridge/Cargo.toml
+++ b/litellm-rust/crates/python-bridge/Cargo.toml
@@@ -24,9 -24,8 +24,10 @@@ litellm-cache.workspace = tru
litellm-cache-azure-blob.workspace = true
litellm-cache-memory.workspace = true
litellm-cache-redis.workspace = true
+ litellm-cache-disk.workspace = true
litellm-cache-response.workspace = true
+litellm-cache-qdrant-semantic.workspace = true
+qdrant-client.workspace = true
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 2aba7012b54,927017e2e60..f085f2cfc7e
--- a/litellm-rust/crates/python-bridge/src/cache/config.rs
+++ b/litellm-rust/crates/python-bridge/src/cache/config.rs
@@@ -1,7 -1,6 +1,7 @@@
- use std::{env, time::Duration};
-use std::{path::PathBuf, time::Duration};
++use std::{env, path::PathBuf, time::Duration};
use litellm_cache::CacheType;
+use litellm_cache_qdrant_semantic::{OpenAiEmbedderConfig, QdrantSemanticConfig, Quantization};
use litellm_cache_redis::{RedisNode, RedisTopology};
use pyo3::{
exceptions::{PyTypeError, PyValueError},
@@@ -115,7 -98,7 +119,8 @@@ impl QdrantSemanticCacheConfig
pub(super) enum CacheBackendConfig {
Memory(MemoryCacheConfig),
Redis(Box<RedisCacheConfig>),
+ Disk(DiskCacheConfig),
+ QdrantSemantic(Box<QdrantSemanticCacheConfig>),
AzureBlob(AzureBlobCacheConfig),
}
@@@ -131,8 -114,7 +136,9 @@@ pub(super) enum UnsupportedCacheConfig
RedisCredentials,
RedisConnection,
RedisOption,
+ DiskStore,
+ QdrantEndpoint,
+ SemanticEmbedding,
}
impl UnsupportedCacheConfig {
@@@ -143,10 -125,7 +149,11 @@@
Self::RedisCredentials => "native Redis credentials require Python",
Self::RedisConnection => "native Redis connection type is not implemented",
Self::RedisOption => "native Redis configuration requires Python",
+ Self::DiskStore => "native disk cache requires the built-in diskcache store",
+ Self::QdrantEndpoint => {
+ "native Qdrant requires the default REST port so the gRPC port can be derived"
+ }
+ Self::SemanticEmbedding => "native semantic embedding requires Python",
}
}
}
@@@ -189,13 -168,13 +196,20 @@@ impl NativeCacheConfig
}))),
Err(reason) => Ok(CacheConfigProjection::Unsupported(reason)),
},
+ Some(CacheType::Disk) => match project_disk(&backend)? {
+ Ok(backend) => Ok(CacheConfigProjection::Native(Box::new(Self {
+ policy,
+ backend: CacheBackendConfig::Disk(backend),
+ }))),
+ Err(reason) => Ok(CacheConfigProjection::Unsupported(reason)),
+ },
+ Some(CacheType::QdrantSemantic) => match project_qdrant_semantic(&backend)? {
+ Ok(backend) => Ok(CacheConfigProjection::Native(Box::new(Self {
+ policy,
+ backend: CacheBackendConfig::QdrantSemantic(Box::new(backend)),
+ }))),
+ Err(reason) => Ok(CacheConfigProjection::Unsupported(reason)),
+ },
Some(CacheType::AzureBlob) => project_azure_blob(&backend).map(|backend| {
CacheConfigProjection::Native(Box::new(Self {
policy,
@@@ -206,7 -185,7 +220,6 @@@
CacheType::RedisSemantic
| CacheType::ValkeySemantic
| CacheType::S3
- | CacheType::Disk
- | CacheType::QdrantSemantic
| CacheType::Gcs,
)
| None => Ok(CacheConfigProjection::Unsupported(
@@@ -242,35 -225,18 +255,46 @@@
}
CacheBackendConfig::Redis(config) => (service.namespace()
!= config.namespace.as_deref())
- .then_some("facade and native backend namespaces must match"),
+ .then_some("facade and native backend namespaces must match")
+ .or_else(|| {
+ (service.default_ttl() != Some(config.default_ttl))
+ .then_some("facade and native backend default TTLs must match")
+ }),
+ CacheBackendConfig::Disk(_) if service.kind() != "disk" => {
+ Some("facade and native backend types must match")
+ }
+ CacheBackendConfig::Disk(config) => {
+ let Some(directory) = service.directory() else {
+ return Some("facade and native backend types must match");
+ };
+ let native = std::fs::canonicalize(directory).ok();
+ let facade = std::fs::canonicalize(&config.directory).ok();
+ (native != facade).then_some("facade and native backend directories must match")
+ }
+ CacheBackendConfig::QdrantSemantic(config) if service.kind() != "qdrant_semantic" => {
+ Some("facade and native backend types must match")
+ }
+ CacheBackendConfig::QdrantSemantic(config)
+ if service.collection_name() != Some(config.collection_name.as_str()) =>
+ {
+ Some("facade and native backend collections must match")
+ }
+ CacheBackendConfig::QdrantSemantic(config)
+ if service.similarity_threshold() != Some(config.similarity_threshold) =>
+ {
+ Some("facade and native backend similarity thresholds must match")
+ }
+ CacheBackendConfig::QdrantSemantic(config)
+ if service.vector_size() != Some(config.vector_size) =>
+ {
+ Some("facade and native backend vector sizes must match")
+ }
+ CacheBackendConfig::QdrantSemantic(config)
+ if service.embedding_model() != Some(config.embedding.model.as_str()) =>
+ {
+ Some("facade and native backend embedding models must match")
+ }
+ CacheBackendConfig::QdrantSemantic(_) => None,
CacheBackendConfig::AzureBlob(config) => match service.azure_blob_identity() {
None => Some("facade and native backend types must match"),
Some((account_url, container))
@@@ -823,8 -679,8 +862,8 @@@ mod tests
use litellm_cache_redis::{RedisNode, RedisTopology};
use super::{
- CacheBackendConfig, CacheConfigProjection, CertificateRequirement, NativeCacheConfig,
- RedisProtocol, UnsupportedCacheConfig,
+ CacheBackendConfig, CacheConfigProjection, CachePolicy, CertificateRequirement,
- DiskCacheConfig, NativeCacheConfig, RedisProtocol,
++ DiskCacheConfig, NativeCacheConfig, RedisProtocol, UnsupportedCacheConfig,
};
use crate::cache::native::NativeResponseCache;
@@@ -1027,6 -815,86 +1066,87 @@@ sys.modules['litellm.caching._embedding
assert_eq!(reason.message(), "native Redis credentials require Python");
});
}
++
+ #[test]
+ fn projects_builtin_disk_configuration_and_rejects_custom_stores() {
+ Python::initialize();
+ Python::attach(|py| {
+ let root =
+ std::env::temp_dir().join(format!("litellm-disk-config-{}", std::process::id()));
+ let directory = root.to_string_lossy();
+ let disk_facade = facade(
+ py,
+ &format!(
+ "Cache = type('Cache', (), {{'__module__': 'diskcache.core'}})\n\
+ Disk = type('Disk', (), {{'__module__': 'diskcache.core'}})\n\
+ store = Cache()\n\
+ store._disk = Disk()\n\
+ store.directory = {directory:?}\n\
+ backend = SimpleNamespace(disk_cache=store)\n\
+ facade = SimpleNamespace(type='disk', 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(&disk_facade).unwrap()
+ else {
+ panic!("disk cache should be supported");
+ };
+ let CacheBackendConfig::Disk(disk) = config.backend else {
+ panic!("expected disk configuration");
+ };
+ assert_eq!(disk.directory, root);
+ let matching = NativeResponseCache::disk(&directory).unwrap();
+ assert_eq!(
+ (NativeCacheConfig {
+ policy: config.policy,
+ backend: CacheBackendConfig::Disk(disk),
+ })
+ .service_mismatch(&matching),
+ None
+ );
+ let other = NativeResponseCache::disk(&root.join("other").to_string_lossy()).unwrap();
+ let mismatch = NativeCacheConfig {
+ policy: CachePolicy {
+ mode: "default-on".into(),
+ ttl: None,
+ namespace: None,
+ supported_call_types: None,
+ redis_flush_size: None,
+ semantic_cache_scope: "key".into(),
+ },
+ backend: CacheBackendConfig::Disk(DiskCacheConfig {
+ directory: root.clone(),
+ }),
+ };
+ assert_eq!(
+ mismatch.service_mismatch(&other),
+ Some("facade and native backend directories must match")
+ );
+
+ let custom = facade(
+ py,
+ &format!(
+ "CustomCache = type('CustomCache', (), {{'__module__': 'mypkg'}})\n\
+ CustomDisk = type('CustomDisk', (), {{'__module__': 'mypkg'}})\n\
+ store = CustomCache()\n\
+ store._disk = CustomDisk()\n\
+ store.directory = {directory:?}\n\
+ backend = SimpleNamespace(disk_cache=store)\n\
+ facade = SimpleNamespace(type='disk', 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(&custom).unwrap()
+ else {
+ panic!("custom disk store must stay on Python");
+ };
+ assert_eq!(
+ reason.message(),
+ "native disk cache requires the built-in diskcache store"
+ );
+ });
+ }
+
#[test]
fn projects_cluster_startup_nodes_as_redis_topology() {
Python::initialize();
diff --cc litellm-rust/crates/python-bridge/src/cache/facade.rs
index c8aafe41816,ee6423daf6e..e49ef2ab863
--- a/litellm-rust/crates/python-bridge/src/cache/facade.rs
+++ b/litellm-rust/crates/python-bridge/src/cache/facade.rs
@@@ -324,11 -320,7 +350,12 @@@ impl FacadeGuard
"RedisClusterCache",
"redis",
),
+ ("qdrant_semantic", _) => (
+ "litellm.caching.qdrant_semantic_cache",
+ "QdrantSemanticCache",
+ "qdrant-semantic",
+ ),
+ ("disk", _) => ("litellm.caching.disk_cache", "DiskCache", "disk"),
("azure-blob", _) => (
"litellm.caching.azure_blob_cache",
"AzureBlobCache",
@@@ -353,27 -345,6 +380,27 @@@
if let Some(message) = config.service_mismatch(service) {
return Err(PyTypeError::new_err(message));
}
+ let backend_config_names = match kind {
- "memory" | "redis" | "azure-blob" => &[
++ "memory" | "redis" | "azure-blob" | "disk" => &[
+ "namespace",
+ "default_ttl",
+ "max_size_in_memory",
+ "max_size_per_item",
+ "redis_kwargs",
+ "redis_flush_size",
+ ][..],
+ "qdrant_semantic" => &[
+ "qdrant_api_base",
+ "qdrant_api_key",
+ "collection_name",
+ "similarity_threshold",
+ "embedding_model",
+ "vector_size",
+ "embedding_max_input_tokens",
+ "embedding_timeout",
+ ][..],
+ _ => unreachable!(),
+ };
Ok(Self {
outer: ObjectGuard::capture(
py,
@@@ -388,7 -359,21 +415,10 @@@
"semantic_cache_scope",
],
)?,
- backend: ObjectGuard::capture(
- py,
- &backend,
- &[
- "namespace",
- "default_ttl",
- "max_size_in_memory",
- "max_size_per_item",
- "redis_kwargs",
- "redis_flush_size",
- ],
- )?,
+ backend: ObjectGuard::capture(py, &backend, backend_config_names)?,
+ disk_store: (kind == "disk")
+ .then(|| DiskStoreGuard::capture(&backend))
+ .transpose()?,
connection: ConnectionGuard::capture(kind, cluster, &backend)?,
})
}
diff --cc litellm-rust/crates/python-bridge/src/cache/handle.rs
index e71ad9f435d,6e12e12040b..b3fbc9bb253
--- a/litellm-rust/crates/python-bridge/src/cache/handle.rs
+++ b/litellm-rust/crates/python-bridge/src/cache/handle.rs
@@@ -74,105 -64,18 +74,117 @@@ impl CacheTestHandle
})
}
+ #[staticmethod]
+ #[pyo3(signature = (directory))]
+ fn disk(py: Python<'_>, directory: String) -> PyResult<Self> {
+ let service =
+ release_gil(py, move || NativeResponseCache::disk(&directory)).map_err(cache_error)?;
+ Ok(Self {
+ service,
+ guard: None,
+ pid: std::process::id(),
+ })
+ }
+
+ #[staticmethod]
+ #[pyo3(signature = (url, *, collection_name, similarity_threshold, vector_size, embedding_model="text-embedding-3-small", api_key=None, embedding_api_key=None, embedding_api_base=None, embedding_timeout_seconds=None, quantization="binary"))]
+ #[expect(
+ clippy::too_many_arguments,
+ reason = "the test handle exposes the complete Qdrant constructor"
+ )]
+ fn qdrant_semantic(
+ py: Python<'_>,
+ url: String,
+ collection_name: String,
+ similarity_threshold: f64,
+ vector_size: u64,
+ embedding_model: &str,
+ api_key: Option<String>,
+ embedding_api_key: Option<String>,
+ embedding_api_base: Option<String>,
+ embedding_timeout_seconds: Option<f64>,
+ quantization: &str,
+ ) -> PyResult<Self> {
+ let parsed = Url::parse(&url).map_err(|_| {
+ pyo3::exceptions::PyValueError::new_err(
+ "native Qdrant requires the default REST port so the gRPC port can be derived",
+ )
+ })?;
+ if !matches!(parsed.scheme(), "http" | "https")
+ || (!parsed.path().is_empty() && parsed.path() != "/")
+ || parsed.query().is_some()
+ || parsed.host_str().is_none()
+ || parsed.port().is_some_and(|port| port != 6333)
+ {
+ return Err(pyo3::exceptions::PyValueError::new_err(
+ "native Qdrant requires the default REST port so the gRPC port can be derived",
+ ));
+ }
+ let mut grpc_url = parsed;
+ grpc_url.set_port(Some(6334)).map_err(|_| {
+ pyo3::exceptions::PyValueError::new_err(
+ "native Qdrant requires the default REST port so the gRPC port can be derived",
+ )
+ })?;
+ grpc_url.set_path("");
+ grpc_url.set_query(None);
+ let embedding_api_key = embedding_api_key
+ .or_else(|| {
+ env::var("OPENAI_API_KEY")
+ .ok()
+ .filter(|value| !value.is_empty())
+ })
+ .ok_or_else(|| {
+ pyo3::exceptions::PyValueError::new_err(
+ "native semantic embedding requires an OpenAI API key",
+ )
+ })?;
+ let embedding_api_base = embedding_api_base.unwrap_or_else(|| {
+ env::var("OPENAI_BASE_URL")
+ .or_else(|_| env::var("OPENAI_API_BASE"))
+ .unwrap_or_else(|_| "https://api.openai.com/v1".to_owned())
+ });
+ let quantization = match quantization {
+ "binary" => Quantization::Binary,
+ "scalar" => Quantization::Scalar,
+ "product" => Quantization::Product,
+ _ => {
+ return Err(pyo3::exceptions::PyValueError::new_err(
+ "unsupported Qdrant quantization",
+ ));
+ }
+ };
+ let config = QdrantSemanticCacheConfig {
+ grpc_url: grpc_url.to_string().trim_end_matches('/').to_owned(),
+ api_key,
+ collection_name,
+ similarity_threshold,
+ vector_size,
+ embedding: OpenAiEmbedderConfig {
+ api_base: embedding_api_base,
+ api_key: embedding_api_key,
+ model: embedding_model.to_owned(),
+ timeout: embedding_timeout_seconds.map(duration).transpose()?,
+ },
+ quantization,
+ };
+ let http_config = http::call_config(py, &PyDict::new(py), true)?;
+ let client = http::pool()
+ .client(&http_config, ClientVariant::Provider)
+ .map_err(http::client_error)?;
+ let service = run_sync_value(py, async move {
+ let handle = tokio::runtime::Handle::current();
+ NativeResponseCache::qdrant_semantic(config, client, handle)
+ .await
+ .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> {
diff --cc litellm-rust/crates/python-bridge/src/cache/native.rs
index e4810a303c8,80789cc279a..b5aa9e2593a
--- 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 std::{path::Path, sync::Arc, time::Duration};
-use litellm_cache::{CacheCodec, CacheConnectionResult, Error};
+use litellm_cache::{CacheCodec, CacheConnectionResult, Error, SemanticCacheContext};
use litellm_cache_azure_blob::AzureBlobCache;
+ use litellm_cache_disk::DiskCache;
use litellm_cache_memory::InMemoryCache;
+use litellm_cache_qdrant_semantic::{Embedder, OpenAiEmbedder, QdrantSemanticCache};
use litellm_cache_redis::{RedisCache, RedisTopology};
use litellm_cache_response::{
CacheEntry, PartialHits, ResponseCache, ResponseCacheCodec, ResponseCacheRequest, WriteBuffer,
@@@ -19,7 -17,7 +20,8 @@@ pub(super) enum NativeResponseCache
cache: Arc<ResponseCache<RedisCache<ResponseCacheCodec>>>,
buffer: Option<Arc<WriteBuffer>>,
},
+ Disk(Arc<ResponseCache<DiskCache<ResponseCacheCodec>>>),
+ QdrantSemantic(Arc<ResponseCache<QdrantSemanticCache<OpenAiEmbedder, ResponseCacheCodec>>>),
AzureBlob(Arc<ResponseCache<AzureBlobCache<ResponseCacheCodec>>>),
}
@@@ -51,32 -49,11 +53,37 @@@ impl NativeResponseCache
buffer: None,
})
}
+
+ pub fn disk(directory: &str) -> Result<Self, Error> {
+ let cache = DiskCache::open(directory, ResponseCacheCodec)?;
+ Ok(Self::Disk(Arc::new(ResponseCache::new(Arc::new(cache)))))
+ }
+
+ pub async fn qdrant_semantic(
+ config: QdrantSemanticCacheConfig,
+ client: reqwest::Client,
+ runtime: tokio::runtime::Handle,
+ ) -> Result<Self, Error> {
+ let qdrant = qdrant_client::Qdrant::from_url(&config.grpc_url)
+ .skip_compatibility_check()
+ .api_key(config.api_key.as_deref())
+ .build()
+ .map_err(|_| Error::Unavailable)?;
+ let qdrant_config = config.to_qdrant_config();
+ let embedder = OpenAiEmbedder::new(client, config.embedding);
+ let cache = QdrantSemanticCache::connect(
+ qdrant,
+ embedder,
+ ResponseCacheCodec,
+ qdrant_config,
+ runtime,
+ )
+ .await?;
+ Ok(Self::QdrantSemantic(Arc::new(ResponseCache::new(
+ Arc::new(cache),
+ ))))
+ }
+
pub async fn azure_blob(account_url: &str, container: &str) -> Result<Self, Error> {
let backend = AzureBlobCache::connect(
account_url,
@@@ -96,7 -73,7 +103,7 @@@
cache.backend().account_url(),
cache.backend().container_name(),
)),
- Self::Memory(_) | Self::Redis { .. } | Self::QdrantSemantic(_) => None,
- Self::Memory(_) | Self::Redis { .. } | Self::Disk(_) => None,
++ Self::Memory(_) | Self::Redis { .. } | Self::Disk(_) | Self::QdrantSemantic(_) => None,
}
}
}
@@@ -106,7 -83,7 +113,8 @@@ impl NativeResponseCache
match self {
Self::Memory(_) => "memory",
Self::Redis { .. } => "redis",
+ Self::Disk(_) => "disk",
+ Self::QdrantSemantic(_) => "qdrant_semantic",
Self::AzureBlob(_) => "azure-blob",
}
}
@@@ -115,42 -92,36 +123,41 @@@
match self {
Self::Memory(cache) => cache.default_ttl(),
Self::Redis { cache, .. } => cache.default_ttl(),
+ Self::Disk(cache) => cache.default_ttl(),
+ Self::QdrantSemantic(_) => None,
Self::AzureBlob(cache) => cache.default_ttl(),
}
}
pub fn namespace(&self) -> Option<&str> {
match self {
- Self::Memory(_) | Self::AzureBlob(_) => None,
- Self::Memory(_) | Self::Disk(_) | Self::AzureBlob(_) => None,
++ Self::Memory(_) | Self::Disk(_) | Self::QdrantSemantic(_) | Self::AzureBlob(_) => None,
Self::Redis { cache, .. } => cache.backend().namespace(),
- Self::QdrantSemantic(_) => None,
}
}
pub fn topology(&self) -> Option<&RedisTopology> {
match self {
- Self::Memory(_) | Self::AzureBlob(_) => None,
- Self::Memory(_) | Self::Disk(_) | Self::AzureBlob(_) => None,
++ Self::Memory(_) | Self::Disk(_) | Self::QdrantSemantic(_) | Self::AzureBlob(_) => None,
Self::Redis { cache, .. } => Some(cache.backend().topology()),
- Self::QdrantSemantic(_) => None,
}
}
pub fn capacity(&self) -> Option<usize> {
match self {
Self::Memory(cache) => Some(cache.backend().max_size_in_memory()),
- Self::Redis { .. } => None,
- Self::Redis { .. } | Self::Disk(_) | Self::AzureBlob(_) => None,
++ Self::Redis { .. } | Self::Disk(_) => None,
+ Self::QdrantSemantic(_) => None,
+ Self::AzureBlob(_) => None,
}
}
pub fn max_entry_bytes(&self) -> Option<usize> {
match self {
Self::Memory(cache) => cache.backend().max_entry_bytes(),
- Self::Redis { .. } => None,
- Self::Redis { .. } | Self::Disk(_) | Self::AzureBlob(_) => None,
++ Self::Redis { .. } | Self::Disk(_) => None,
+ Self::QdrantSemantic(_) => None,
+ Self::AzureBlob(_) => None,
}
}
@@@ -164,31 -135,10 +171,40 @@@
}
}
+ pub fn directory(&self) -> Option<&Path> {
+ match self {
+ Self::Disk(cache) => Some(cache.backend().directory()),
- Self::Memory(_) | Self::Redis { .. } | Self::AzureBlob(_) => None,
++ Self::Memory(_) | Self::Redis { .. } | Self::QdrantSemantic(_) | Self::AzureBlob(_) => {
++ None
++ }
++ }
++ }
++
+ pub fn collection_name(&self) -> Option<&str> {
+ match self {
+ Self::QdrantSemantic(cache) => Some(cache.backend().collection_name()),
+ _ => None,
+ }
+ }
+
+ pub fn similarity_threshold(&self) -> Option<f64> {
+ match self {
+ Self::QdrantSemantic(cache) => Some(cache.backend().similarity_threshold()),
+ _ => None,
+ }
+ }
+
+ pub fn vector_size(&self) -> Option<u64> {
+ match self {
+ Self::QdrantSemantic(cache) => Some(cache.backend().vector_size()),
+ _ => None,
+ }
+ }
+
+ pub fn embedding_model(&self) -> Option<&str> {
+ match self {
+ Self::QdrantSemantic(cache) => Some(cache.backend().embedder().model()),
+ _ => None,
}
}
@@@ -198,10 -148,10 +214,11 @@@
now: Duration,
) -> Result<Option<Value>, Error> {
match self {
- Self::Memory(cache) => cache.lookup(request, now),
- Self::Redis { cache, .. } => cache.lookup(request, now),
- Self::Disk(cache) => cache.lookup(request, now),
- Self::AzureBlob(cache) => cache.lookup(request, now),
+ Self::Memory(cache) => cache.lookup(&exact(request), now),
+ Self::Redis { cache, .. } => cache.lookup(&exact(request), now),
++ Self::Disk(cache) => cache.lookup(&exact(request), now),
+ Self::QdrantSemantic(cache) => cache.lookup(request, now),
+ Self::AzureBlob(cache) => cache.lookup(&exact(request), now),
}
}
@@@ -212,10 -162,10 +229,11 @@@
now: Duration,
) -> Result<(), Error> {
match self {
- Self::Memory(cache) => cache.store(request, response, now),
- Self::Redis { 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(&exact(request), response, now),
+ Self::Redis { cache, .. } => cache.store(&exact(request), response, now),
++ Self::Disk(cache) => cache.store(&exact(request), response, now),
+ Self::QdrantSemantic(cache) => cache.store(request, response, now),
+ Self::AzureBlob(cache) => cache.store(&exact(request), response, now),
}
}
@@@ -225,16 -175,10 +243,19 @@@
now: Duration,
) -> Result<PartialHits, Error> {
match self {
- Self::Memory(cache) => cache.lookup_batch(requests, now),
- Self::Redis { 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) => {
+ cache.lookup_batch(&requests.iter().map(exact).collect::<Vec<_>>(), now)
+ }
+ Self::Redis { cache, .. } => {
+ cache.lookup_batch(&requests.iter().map(exact).collect::<Vec<_>>(), now)
+ }
++ Self::Disk(cache) => {
++ cache.lookup_batch(&requests.iter().map(exact).collect::<Vec<_>>(), now)
++ }
+ Self::QdrantSemantic(_) => Err(Error::UnsupportedOperation),
+ Self::AzureBlob(cache) => {
+ cache.lookup_batch(&requests.iter().map(exact).collect::<Vec<_>>(), now)
+ }
}
}
@@@ -244,10 -188,10 +265,11 @@@
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::Disk(cache) => cache.async_lookup(request, now).await,
- Self::AzureBlob(cache) => cache.async_lookup(request, now).await,
+ Self::Memory(cache) => cache.async_lookup(&exact(request), now).await,
+ Self::Redis { cache, .. } => cache.async_lookup(&exact(request), now).await,
++ Self::Disk(cache) => cache.async_lookup(&exact(request), now).await,
+ Self::QdrantSemantic(cache) => cache.async_lookup(request, now).await,
+ Self::AzureBlob(cache) => cache.async_lookup(&exact(request), now).await,
}
}
@@@ -266,12 -210,9 +288,13 @@@
Self::Redis {
cache,
buffer: Some(buffer),
- } => buffer.async_store(cache, request, response, now).await,
- Self::Disk(cache) => cache.async_store(request, response, now).await,
- Self::AzureBlob(cache) => cache.async_store(request, response, now).await,
+ } => {
+ let request = exact(request);
+ buffer.async_store(cache, &request, response, now).await
+ }
++ Self::Disk(cache) => cache.async_store(&exact(request), response, now).await,
+ Self::QdrantSemantic(cache) => cache.async_store(request, response, now).await,
+ Self::AzureBlob(cache) => cache.async_store(&exact(request), response, now).await,
}
}
@@@ -281,19 -222,10 +304,23 @@@
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::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(exact).collect::<Vec<_>>();
+ cache.async_lookup_batch(&requests, now).await
+ }
+ Self::Redis { cache, .. } => {
+ let requests = requests.iter().map(exact).collect::<Vec<_>>();
+ cache.async_lookup_batch(&requests, now).await
+ }
++ Self::Disk(cache) => {
++ let requests = requests.iter().map(exact).collect::<Vec<_>>();
++ cache.async_lookup_batch(&requests, now).await
++ }
+ Self::QdrantSemantic(_) => Err(Error::UnsupportedOperation),
+ Self::AzureBlob(cache) => {
+ let requests = requests.iter().map(exact).collect::<Vec<_>>();
+ cache.async_lookup_batch(&requests, now).await
+ }
}
}
@@@ -303,40 -235,10 +330,51 @@@
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::Disk(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)| (exact(&request), value))
+ .collect(),
+ now,
+ )
+ .await
+ }
+ Self::Redis { cache, .. } => {
+ cache
+ .async_store_batch(
+ entries
+ .into_iter()
+ .map(|(request, value)| (exact(&request), value))
+ .collect(),
+ now,
+ )
+ .await
+ }
++ Self::Disk(cache) => {
++ cache
++ .async_store_batch(
++ entries
++ .into_iter()
++ .map(|(request, value)| (exact(&request), value))
++ .collect(),
++ now,
++ )
++ .await
++ }
+ Self::QdrantSemantic(cache) => cache.async_store_batch(entries, now).await,
+ Self::AzureBlob(cache) => {
+ cache
+ .async_store_batch(
+ entries
+ .into_iter()
+ .map(|(request, value)| (exact(&request), value))
+ .collect(),
+ now,
+ )
+ .await
+ }
}
}
@@@ -349,7 -251,7 +387,8 @@@
}
cache.async_flush().await
}
+ Self::Disk(cache) => cache.async_flush().await,
+ Self::QdrantSemantic(_) => Err(Error::UnsupportedOperation),
Self::AzureBlob(cache) => cache.async_flush().await,
}
}
@@@ -358,7 -260,7 +397,8 @@@
match self {
Self::Memory(cache) => cache.test_connection().await,
Self::Redis { cache, .. } => cache.test_connection().await,
+ Self::Disk(cache) => cache.test_connection().await,
+ Self::QdrantSemantic(_) => Err(Error::UnsupportedOperation),
Self::AzureBlob(cache) => cache.test_connection().await,
}
}
diff --cc tests/test_litellm_rust/test_cache.py
index 60bb3c192f1,8cddc868073..c6b89583e9c
--- a/tests/test_litellm_rust/test_cache.py
+++ b/tests/test_litellm_rust/test_cache.py
@@@ -14,8 -12,8 +15,9 @@@ from pathlib import Pat
from types import SimpleNamespace
from typing import Final, Protocol, cast
from urllib.parse import urlparse
+from uuid import uuid4
+ import diskcache
import fakeredis
import pytest
import redis