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 Lee3122d21ea6c5
diff --cc litellm-rust/Cargo.lock
index fa0ec7fcb96,b13bce2ed67..dd2566a6f84
--- a/litellm-rust/Cargo.lock
+++ b/litellm-rust/Cargo.lock
@@@ -2878,8 -2830,8 +2893,9 @@@ dependencies =
"litellm-cache",
"litellm-cache-azure-blob",
"litellm-cache-disk",
+ "litellm-cache-gcs",
"litellm-cache-memory",
+ "litellm-cache-qdrant-semantic",
"litellm-cache-redis",
"litellm-cache-response",
"litellm-callbacks-legacy-python",
diff --cc litellm-rust/Cargo.toml
index bb56210436a,3ab1e592c6a..0d8e77b4f96
--- a/litellm-rust/Cargo.toml
+++ b/litellm-rust/Cargo.toml
@@@ -32,9 -32,9 +32,10 @@@ 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-gcs = { path = "crates/cache-gcs" }
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/cache/src/error.rs
index 72fb338e7d8,1a381d0afd8..79ef9cd18b1
--- a/litellm-rust/crates/cache/src/error.rs
+++ b/litellm-rust/crates/cache/src/error.rs
@@@ -6,8 -6,6 +6,8 @@@ pub enum Error
InvalidEntry,
#[error("flushing Redis requires an explicit namespace")]
UnscopedFlush,
- #[error("cache backend does not support this operation")]
+ #[error("operation is not supported by this cache")]
UnsupportedOperation,
+ #[error("semantic cache requires request messages")]
+ MissingPrompt,
}
diff --cc litellm-rust/crates/python-bridge/Cargo.toml
index d214118a224,4a9ea633ac5..bace8d61f58
--- a/litellm-rust/crates/python-bridge/Cargo.toml
+++ b/litellm-rust/crates/python-bridge/Cargo.toml
@@@ -24,10 -24,9 +24,11 @@@ 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-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 f085f2cfc7e,6c180708335..8c26a6033c0
--- a/litellm-rust/crates/python-bridge/src/cache/config.rs
+++ b/litellm-rust/crates/python-bridge/src/cache/config.rs
@@@ -119,8 -105,8 +126,9 @@@ impl QdrantSemanticCacheConfig
pub(super) enum CacheBackendConfig {
Memory(MemoryCacheConfig),
Redis(Box<RedisCacheConfig>),
+ Gcs(GcsCacheConfig),
Disk(DiskCacheConfig),
+ QdrantSemantic(Box<QdrantSemanticCacheConfig>),
AzureBlob(AzureBlobCacheConfig),
}
@@@ -136,9 -122,8 +144,10 @@@ pub(super) enum UnsupportedCacheConfig
RedisCredentials,
RedisConnection,
RedisOption,
+ GcsBucket,
DiskStore,
+ QdrantEndpoint,
+ SemanticEmbedding,
}
impl UnsupportedCacheConfig {
@@@ -149,11 -134,8 +158,12 @@@
Self::RedisCredentials => "native Redis credentials require Python",
Self::RedisConnection => "native Redis connection type is not implemented",
Self::RedisOption => "native Redis configuration requires Python",
+ Self::GcsBucket => "native GCS cache requires a configured bucket name",
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",
}
}
}
@@@ -216,50 -198,76 +233,71 @@@ impl NativeCacheConfig
backend: CacheBackendConfig::AzureBlob(backend),
}))
}),
-- Some(
-- CacheType::RedisSemantic
-- | CacheType::ValkeySemantic
-- | CacheType::S3
- | CacheType::Gcs,
- | CacheType::QdrantSemantic,
-- )
-- | None => Ok(CacheConfigProjection::Unsupported(
-- UnsupportedCacheConfig::Backend,
-- )),
++ Some(CacheType::RedisSemantic | CacheType::ValkeySemantic | CacheType::S3) | None => {
++ Ok(CacheConfigProjection::Unsupported(
++ UnsupportedCacheConfig::Backend,
++ ))
++ }
}
}
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::Disk(_)
- | CacheBackendConfig::AzureBlob(_)
- | CacheBackendConfig::Gcs(_) => None,
- };
- if service.default_ttl() != default_ttl {
- return Some("facade and native backend default TTLs must match");
- }
match &self.backend {
- CacheBackendConfig::Memory(config) if service.kind() != "memory" => {
- Some("facade and native backend types must match")
- }
- CacheBackendConfig::Memory(config) if service.capacity() != Some(config.capacity) => {
- Some("facade and native backend capacities must match")
- }
- CacheBackendConfig::Memory(config)
- if service.max_entry_bytes() != Some(config.max_entry_bytes) =>
- {
- Some("facade and native backend item limits must match")
- }
- CacheBackendConfig::Memory(_) => None,
- CacheBackendConfig::Redis(_) if service.kind() != "redis" => {
- Some("facade and native backend types must match")
- }
- CacheBackendConfig::Redis(config) if service.topology() != Some(&config.topology) => {
- Some("facade and native backend topologies must match")
- }
- 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::Memory(_) if service.kind() != "memory" => {
+ Some("facade and native backend types must match")
+ }
+ CacheBackendConfig::Memory(config)
+ if service.default_ttl() != Some(config.default_ttl) =>
+ {
+ Some("facade and native backend default TTLs must match")
+ }
+ CacheBackendConfig::Memory(config) if service.capacity() != Some(config.capacity) => {
+ Some("facade and native backend capacities must match")
+ }
+ CacheBackendConfig::Memory(config)
+ if service.max_entry_bytes() != Some(config.max_entry_bytes) =>
+ {
+ Some("facade and native backend item limits must match")
+ }
+ CacheBackendConfig::Memory(_) => None,
+ CacheBackendConfig::Redis(config) if service.kind() != "redis" => {
+ Some("facade and native backend types must match")
+ }
+ CacheBackendConfig::Redis(config) if service.topology() != Some(&config.topology) => {
+ Some("facade and native backend topologies must match")
+ }
+ CacheBackendConfig::Redis(config) => (service.namespace()
+ != config.namespace.as_deref())
+ .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")
}
@@@ -421,18 -307,35 +459,35 @@@ fn project_azure_blob(backend: &Bound<'
})
}
-#[inline(never)]
-fn project_memory(backend: &Bound<'_, PyAny>) -> PyResult<MemoryCacheConfig> {
- let max_size_kib = backend.getattr("max_size_per_item")?.extract::<usize>()?;
- Ok(MemoryCacheConfig {
- default_ttl: duration(backend.getattr("default_ttl")?.extract::<f64>()?)?,
- capacity: backend.getattr("max_size_in_memory")?.extract::<usize>()?,
- max_entry_bytes: max_size_kib
- .checked_mul(1024)
- .ok_or_else(|| PyValueError::new_err("memory cache item limit is too large"))?,
- })
-}
-
+ #[inline(never)]
+ fn project_gcs(
+ backend: &Bound<'_, PyAny>,
+ ) -> PyResult<Result<GcsCacheConfig, UnsupportedCacheConfig>> {
+ let bucket_name = match backend.getattr("bucket_name")?.extract::<Option<String>>() {
+ Ok(Some(bucket_name)) if !bucket_name.is_empty() => bucket_name,
+ _ => return Ok(Err(UnsupportedCacheConfig::GcsBucket)),
+ };
+ Ok(Ok(GcsCacheConfig {
+ bucket_name,
+ key_prefix: backend.getattr("key_prefix")?.extract::<String>()?,
+ path_service_account: backend
+ .getattr("path_service_account")?
+ .extract::<Option<String>>()?,
+ }))
+ }
+
+#[inline(never)]
+fn project_memory(backend: &Bound<'_, PyAny>) -> PyResult<MemoryCacheConfig> {
+ let max_size_kib = backend.getattr("max_size_per_item")?.extract::<usize>()?;
+ Ok(MemoryCacheConfig {
+ default_ttl: duration(backend.getattr("default_ttl")?.extract::<f64>()?)?,
+ capacity: backend.getattr("max_size_in_memory")?.extract::<usize>()?,
+ max_entry_bytes: max_size_kib
+ .checked_mul(1024)
+ .ok_or_else(|| PyValueError::new_err("memory cache item limit is too large"))?,
+ })
+}
+
#[inline(never)]
fn project_disk(
backend: &Bound<'_, PyAny>,
@@@ -1066,7 -939,6 +1121,57 @@@ sys.modules['litellm.caching._embedding
assert_eq!(reason.message(), "native Redis credentials require Python");
});
}
+
++ #[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()),
++ }
++ );
++ });
++ }
++
++ #[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 projects_builtin_disk_configuration_and_rejects_custom_stores() {
Python::initialize();
diff --cc litellm-rust/crates/python-bridge/src/cache/facade.rs
index e49ef2ab863,0fa4511b1c1..3a998d511fd
--- a/litellm-rust/crates/python-bridge/src/cache/facade.rs
+++ b/litellm-rust/crates/python-bridge/src/cache/facade.rs
@@@ -350,11 -320,7 +350,12 @@@ impl FacadeGuard
"RedisClusterCache",
"redis",
),
+ ("qdrant_semantic", _) => (
+ "litellm.caching.qdrant_semantic_cache",
+ "QdrantSemanticCache",
+ "qdrant-semantic",
+ ),
+ ("gcs", _) => ("litellm.caching.gcs_cache", "GCSCache", "gcs"),
("disk", _) => ("litellm.caching.disk_cache", "DiskCache", "disk"),
("azure-blob", _) => (
"litellm.caching.azure_blob_cache",
@@@ -380,27 -346,6 +381,30 @@@
if let Some(message) = config.service_mismatch(service) {
return Err(PyTypeError::new_err(message));
}
+ let backend_config_names = match kind {
- "memory" | "redis" | "azure-blob" | "disk" => &[
++ "memory" | "redis" | "azure-blob" | "disk" | "gcs" => &[
+ "namespace",
+ "default_ttl",
+ "max_size_in_memory",
+ "max_size_per_item",
+ "redis_kwargs",
+ "redis_flush_size",
++ "bucket_name",
++ "key_prefix",
++ "path_service_account",
+ ][..],
+ "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,
diff --cc litellm-rust/crates/python-bridge/src/cache/handle.rs
index b3fbc9bb253,64ac3696e80..87f0ff98f67
--- a/litellm-rust/crates/python-bridge/src/cache/handle.rs
+++ b/litellm-rust/crates/python-bridge/src/cache/handle.rs
@@@ -1,18 -1,10 +1,19 @@@
-use litellm_cache_redis::{RedisNode, RedisTopology};
-use litellm_host_python::{release_gil, run_sync_value};
-use pyo3::{PyTraverseError, PyVisit, exceptions::PyRuntimeError, prelude::*};
+use std::env;
+ use litellm_cache_gcs::{DEFAULT_ENDPOINT, GcsConfig};
+use litellm_cache_redis::{RedisNode, RedisTopology};
+use litellm_http::ClientVariant;
-use super::{cache_error, facade::FacadeGuard, native::NativeResponseCache, request::duration};
+use litellm_cache_qdrant_semantic::{OpenAiEmbedderConfig, Quantization};
+use litellm_host_python::{release_gil, run_sync_value};
+use pyo3::{PyTraverseError, PyVisit, exceptions::PyRuntimeError, prelude::*, types::PyDict};
+use url::Url;
+
+use super::{
+ cache_error, config::QdrantSemanticCacheConfig, facade::FacadeGuard,
+ native::NativeResponseCache, request::duration,
+};
+use crate::http;
#[pyclass(frozen, name = "_CacheTestHandle")]
pub(crate) struct CacheTestHandle {
diff --cc litellm-rust/crates/python-bridge/src/cache/native.rs
index b5aa9e2593a,b10f9e2a443..7e1a4c27bc6
--- a/litellm-rust/crates/python-bridge/src/cache/native.rs
+++ b/litellm-rust/crates/python-bridge/src/cache/native.rs
@@@ -1,10 -1,10 +1,11 @@@
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_gcs::{GcsCache, GcsConfig, StaticTokenSource};
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,
@@@ -20,8 -18,8 +21,9 @@@ pub(super) enum NativeResponseCache
cache: Arc<ResponseCache<RedisCache<ResponseCacheCodec>>>,
buffer: Option<Arc<WriteBuffer>>,
},
+ Gcs(Arc<ResponseCache<GcsCache<ResponseCacheCodec>>>),
Disk(Arc<ResponseCache<DiskCache<ResponseCacheCodec>>>),
+ QdrantSemantic(Arc<ResponseCache<QdrantSemanticCache<OpenAiEmbedder, ResponseCacheCodec>>>),
AzureBlob(Arc<ResponseCache<AzureBlobCache<ResponseCacheCodec>>>),
}
@@@ -59,31 -56,18 +61,43 @@@ impl NativeResponseCache
Ok(Self::Disk(Arc::new(ResponseCache::new(Arc::new(cache)))))
}
+ pub fn gcs(config: GcsConfig, token: Option<String>) -> Result<Self, Error> {
+ let backend = match token {
+ Some(token) => GcsCache::with_token_source(
+ config,
+ ResponseCacheCodec,
+ Arc::new(StaticTokenSource(token)),
+ )?,
+ None => GcsCache::new(config, ResponseCacheCodec)?,
+ };
+ Ok(Self::Gcs(Arc::new(ResponseCache::new(Arc::new(backend)))))
+ }
+
+ 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,
@@@ -103,7 -87,7 +117,11 @@@
cache.backend().account_url(),
cache.backend().container_name(),
)),
- Self::Memory(_) | Self::Redis { .. } | Self::Disk(_) | Self::QdrantSemantic(_) => None,
- Self::Memory(_) | Self::Redis { .. } | Self::Disk(_) | Self::Gcs(_) => None,
++ Self::Memory(_)
++ | Self::Redis { .. }
++ | Self::Gcs(_)
++ | Self::Disk(_)
++ | Self::QdrantSemantic(_) => None,
}
}
}
@@@ -113,8 -97,8 +131,9 @@@ impl NativeResponseCache
match self {
Self::Memory(_) => "memory",
Self::Redis { .. } => "redis",
+ Self::Gcs(_) => "gcs",
Self::Disk(_) => "disk",
+ Self::QdrantSemantic(_) => "qdrant_semantic",
Self::AzureBlob(_) => "azure-blob",
}
}
@@@ -123,22 -107,23 +142,31 @@@
match self {
Self::Memory(cache) => cache.default_ttl(),
Self::Redis { cache, .. } => cache.default_ttl(),
+ Self::Gcs(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::Disk(_) | Self::QdrantSemantic(_) | Self::AzureBlob(_) => None,
- Self::Memory(_) | Self::Disk(_) | Self::AzureBlob(_) => None,
++ Self::Memory(_)
++ | Self::Disk(_)
++ | Self::QdrantSemantic(_)
++ | 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::Disk(_) | Self::QdrantSemantic(_) | Self::AzureBlob(_) => None,
- Self::Memory(_) | Self::Disk(_) | Self::AzureBlob(_) | Self::Gcs(_) => None,
++ Self::Memory(_)
++ | Self::Disk(_)
++ | Self::QdrantSemantic(_)
++ | Self::AzureBlob(_)
++ | Self::Gcs(_) => None,
Self::Redis { cache, .. } => Some(cache.backend().topology()),
}
}
@@@ -146,18 -131,14 +174,18 @@@
pub fn capacity(&self) -> Option<usize> {
match self {
Self::Memory(cache) => Some(cache.backend().max_size_in_memory()),
- Self::Redis { .. } | Self::Disk(_) => None,
- Self::Redis { .. } | Self::Disk(_) | Self::AzureBlob(_) | Self::Gcs(_) => None,
++ Self::Redis { .. } | Self::Gcs(_) | 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 { .. } | Self::Disk(_) => None,
- Self::Redis { .. } | Self::Disk(_) | Self::AzureBlob(_) | Self::Gcs(_) => None,
++ Self::Redis { .. } | Self::Gcs(_) | Self::Disk(_) => None,
+ Self::QdrantSemantic(_) => None,
+ Self::AzureBlob(_) => None,
}
}
@@@ -174,37 -155,7 +202,39 @@@
pub fn directory(&self) -> Option<&Path> {
match self {
Self::Disk(cache) => Some(cache.backend().directory()),
- Self::Memory(_) | Self::Redis { .. } | Self::QdrantSemantic(_) | Self::AzureBlob(_) => {
- None
- }
- Self::Memory(_) | Self::Redis { .. } | Self::AzureBlob(_) | Self::Gcs(_) => None,
++ Self::Memory(_)
++ | Self::Redis { .. }
++ | Self::Gcs(_)
++ | 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,
}
}
@@@ -214,11 -165,11 +244,12 @@@
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(&exact(request), now),
+ Self::Redis { cache, .. } => cache.lookup(&exact(request), now),
++ Self::Gcs(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),
}
}
@@@ -229,11 -180,11 +260,12 @@@
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(&exact(request), response, now),
+ Self::Redis { cache, .. } => cache.store(&exact(request), response, now),
++ Self::Gcs(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),
}
}
@@@ -243,19 -194,11 +275,22 @@@
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) => {
+ cache.lookup_batch(&requests.iter().map(exact).collect::<Vec<_>>(), now)
+ }
+ Self::Redis { cache, .. } => {
+ cache.lookup_batch(&requests.iter().map(exact).collect::<Vec<_>>(), now)
+ }
++ Self::Gcs(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)
+ }
}
}
@@@ -265,11 -208,11 +300,12 @@@
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(&exact(request), now).await,
+ Self::Redis { cache, .. } => cache.async_lookup(&exact(request), now).await,
++ Self::Gcs(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,
}
}
@@@ -288,13 -231,10 +324,14 @@@
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,
+ } => {
+ let request = exact(request);
+ buffer.async_store(cache, &request, response, now).await
+ }
++ Self::Gcs(cache) => cache.async_store(&exact(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,
}
}
@@@ -304,23 -244,11 +341,27 @@@
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(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::Gcs(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
+ }
}
}
@@@ -330,51 -258,11 +371,62 @@@
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) => {
+ 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::Gcs(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
+ }
}
}
@@@ -387,8 -275,8 +439,9 @@@
}
cache.async_flush().await
}
+ Self::Gcs(cache) => cache.async_flush().await,
Self::Disk(cache) => cache.async_flush().await,
+ Self::QdrantSemantic(_) => Err(Error::UnsupportedOperation),
Self::AzureBlob(cache) => cache.async_flush().await,
}
}
@@@ -397,8 -285,8 +450,9 @@@
match self {
Self::Memory(cache) => cache.test_connection().await,
Self::Redis { cache, .. } => cache.test_connection().await,
+ Self::Gcs(cache) => cache.test_connection().await,
Self::Disk(cache) => cache.test_connection().await,
+ Self::QdrantSemantic(_) => Err(Error::UnsupportedOperation),
Self::AzureBlob(cache) => cache.test_connection().await,
}
}