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]
Python ai-gatewayanthropicazure-openaibedrockgatewaylangchainlitellmllmllm-gatewayllmopsmcp-gatewayopenaiopenai-proxyrustrust-aivertex-ai
Merge origin/main into litellm_rust_qdrant_semantic_cache
Yujong Leee3ca80b19a05
diff --cc litellm-rust/Cargo.lockindex dd2566a6f84,66270501312..464edb3b104--- a/litellm-rust/Cargo.lock+++ b/litellm-rust/Cargo.lock@@@ -2895,9 -2972,11 +3035,12 @@@ dependencies ="litellm-cache-disk","litellm-cache-gcs","litellm-cache-memory",+ "litellm-cache-qdrant-semantic","litellm-cache-redis",+ "litellm-cache-redis-semantic","litellm-cache-response",+ "litellm-cache-s3",+ "litellm-cache-valkey-semantic","litellm-callbacks-legacy-python","litellm-core","litellm-core-utils",@@@ -2908,15 -2987,14 +3051,17 @@@"litellm-types","pyo3","pyo3-async-runtimes",+ "qdrant-client",+ "redis",+ "reqwest 0.12.28","rstest","serde","serde_json","serde_with",+ "sha2 0.10.9","tokio","tokio-tungstenite",+ "url",][[package]]@@@ -3143,12 -3251,16 +3318,22 @@@ version = "0.2.3source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "fc04a4c58212d57930a24bf47d3fa87485264a3a054e9c10e042eb373573ad3c"+[[package]]+name = "matchit"+version = "0.8.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "47e1ffaa40ddd1f3ed91f717a33c8c0ee23fff369e3aa8772b9605cc1d22f4c3"++ [[package]]+ name = "md-5"+ version = "0.11.0"+ source = "registry+https://github.com/rust-lang/crates.io-index"+ checksum = "69b6441f590336821bb897fb28fc622898ccceb1d6cea3fde5ea86b090c4de98"+ dependencies = [+ "cfg-if",+ "digest 0.11.3",+ ]+[[package]]name = "memchr"version = "2.8.3"diff --cc litellm-rust/Cargo.tomlindex 0d8e77b4f96,4e370c13766..0e8941cb8e6--- a/litellm-rust/Cargo.toml+++ b/litellm-rust/Cargo.toml@@@ -32,10 -33,11 +33,12 @@@ litellm-cache = { path = "crates/cachelitellm-cache-azure-blob = { path = "crates/cache-azure-blob" }litellm-cache-memory = { path = "crates/cache-memory" }litellm-cache-redis = { path = "crates/cache-redis" }+ litellm-cache-s3 = { path = "crates/cache-s3" }litellm-cache-gcs = { path = "crates/cache-gcs" }litellm-cache-disk = { path = "crates/cache-disk" }+ litellm-cache-redis-semantic = { path = "crates/cache-redis-semantic" }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-qdrant-semantic/src/semantic.rsindex cc82118d280,00000000000..fb165ed5a8emode 100644,000000..100644--- a/litellm-rust/crates/cache-qdrant-semantic/src/semantic.rs+++ b/litellm-rust/crates/cache-qdrant-semantic/src/semantic.rs@@@ -1,259 -1,0 +1,262 @@@+use std::future::Future;++use futures_util::future::try_join_all;+use litellm_cache::{BaseCache, CacheCodec, CacheConnectionResult, Error, SemanticCacheContext};+use qdrant_client::{+ Payload, Qdrant,+ qdrant::{+ BinaryQuantizationBuilder, CompressionRatio, Condition, CreateCollectionBuilder,+ CreateFieldIndexCollectionBuilder, Distance, FieldType, Filter, PointStruct,+ ProductQuantizationBuilder, QuantizationSearchParamsBuilder, ScalarQuantizationBuilder,+ SearchParamsBuilder, SearchPointsBuilder, UpsertPointsBuilder, VectorParamsBuilder,+ },+};+use serde_json::{Map, Value, json};+use uuid::Uuid;++use crate::prompt_from_messages;++pub trait Embedder: Send + Sync + 'static {+ fn model(&self) -> &str;+ fn embed(&self, input: &str) -> impl Future<Output = Result<Vec<f32>, Error>> + Send;+}++#[derive(Clone, Debug, PartialEq)]+pub enum Quantization {+ Binary,+ Scalar,+ Product,+}++pub struct QdrantSemanticConfig {+ pub collection_name: String,+ pub similarity_threshold: f64,+ pub vector_size: u64,+ pub quantization: Quantization,+}++pub struct QdrantSemanticCache<E: Embedder, C: CacheCodec> {+ client: Qdrant,+ embedder: E,+ codec: C,+ config: QdrantSemanticConfig,+ runtime: tokio::runtime::Handle,+}++impl<E: Embedder, C: CacheCodec> QdrantSemanticCache<E, C> {+ pub async fn connect(+ client: Qdrant,+ embedder: E,+ codec: C,+ config: QdrantSemanticConfig,+ runtime: tokio::runtime::Handle,+ ) -> Result<Self, Error> {+ let exists = client+ .collection_exists(config.collection_name.clone())+ .await+ .map_err(|_| Error::Unavailable)?;+ if !exists {+ client+ .create_collection(+ CreateCollectionBuilder::new(config.collection_name.clone())+ .vectors_config(VectorParamsBuilder::new(+ config.vector_size,+ Distance::Cosine,+ ))+ .quantization_config(quantization(&config.quantization)),+ )+ .await+ .map_err(|_| Error::Unavailable)?;+ }+ let _ = client+ .create_field_index(CreateFieldIndexCollectionBuilder::new(+ config.collection_name.clone(),+ "litellm_cache_key".to_owned(),+ FieldType::Keyword,+ ))+ .await;+ Ok(Self {+ client,+ embedder,+ codec,+ config,+ runtime,+ })+ }++ pub fn collection_name(&self) -> &str {+ &self.config.collection_name+ }++ pub fn similarity_threshold(&self) -> f64 {+ self.config.similarity_threshold+ }++ pub fn vector_size(&self) -> u64 {+ self.config.vector_size+ }++ pub fn embedder(&self) -> &E {+ &self.embedder+ }++ fn prompt(context: &SemanticCacheContext) -> Result<String, Error> {- if context.messages.is_empty() {++ let Some(messages) = context.messages.as_ref().and_then(Value::as_array) else {++ return Err(Error::MissingPrompt);++ };++ if messages.is_empty() {+ return Err(Error::MissingPrompt);+ }- Ok(prompt_from_messages(&context.messages))++ Ok(prompt_from_messages(messages))+ }++ async fn set(+ &self,+ key: &str,+ value: C::Value,+ context: &SemanticCacheContext,+ ) -> Result<(), Error> {+ let prompt = Self::prompt(context)?;+ let vector = self.embedder.embed(&prompt).await?;+ let response =+ String::from_utf8(self.codec.encode(&value)?).map_err(|_| Error::InvalidEntry)?;+ let payload = Payload::try_from(json!({+ "litellm_cache_key": key,+ "text": prompt,+ "response": response,+ }))+ .map_err(|_| Error::InvalidEntry)?;+ self.client+ .upsert_points(+ UpsertPointsBuilder::new(+ self.collection_name(),+ vec![PointStruct::new(+ Uuid::new_v4().to_string(),+ vector,+ payload,+ )],+ )+ .wait(true),+ )+ .await+ .map_err(|_| Error::Unavailable)?;+ Ok(())+ }++ async fn get(+ &self,+ key: &str,+ context: &SemanticCacheContext,+ ) -> Result<Option<C::Value>, Error> {+ let prompt = Self::prompt(context)?;+ let vector = self.embedder.embed(&prompt).await?;+ let result = self+ .client+ .search_points(+ SearchPointsBuilder::new(self.collection_name(), vector, 1)+ .with_payload(true)+ .filter(Filter::must([Condition::matches(+ "litellm_cache_key",+ key.to_owned(),+ )]))+ .params(+ SearchParamsBuilder::default().quantization(+ QuantizationSearchParamsBuilder::default()+ .ignore(false)+ .rescore(true)+ .oversampling(3.0),+ ),+ ),+ )+ .await+ .map_err(|_| Error::Unavailable)?;+ let Some(point) = result.result.into_iter().next() else {+ return Ok(None);+ };+ let payload: Map<String, Value> = Payload::from(point.payload).into();+ if payload.get("litellm_cache_key").and_then(Value::as_str) != Some(key) {+ return Ok(None);+ }+ if f64::from(point.score) < self.config.similarity_threshold {+ return Ok(None);+ }+ let response = payload+ .get("response")+ .and_then(Value::as_str)+ .ok_or(Error::InvalidEntry)?;+ self.codec.decode(response.as_bytes()).map(Some)+ }+}++fn quantization(value: &Quantization) -> qdrant_client::qdrant::quantization_config::Quantization {+ match value {+ Quantization::Binary => BinaryQuantizationBuilder::new(false).into(),+ Quantization::Scalar => ScalarQuantizationBuilder::default()+ .quantile(0.99)+ .always_ram(false)+ .into(),+ Quantization::Product => ProductQuantizationBuilder::new(CompressionRatio::X16.into())+ .always_ram(false)+ .into(),+ }+}++impl<E: Embedder, C: CacheCodec> BaseCache for QdrantSemanticCache<E, C> {+ type Value = C::Value;+ type Context = SemanticCacheContext;++ fn get_ttl(&self, _: &Self::Context) -> Option<std::time::Duration> {+ None+ }++ fn set_cache(+ &self,+ key: &str,+ value: Self::Value,+ context: &Self::Context,+ ) -> Result<(), Error> {+ self.runtime.block_on(self.set(key, value, context))+ }++ fn get_cache(&self, key: &str, context: &Self::Context) -> Result<Option<Self::Value>, Error> {+ self.runtime.block_on(self.get(key, context))+ }++ async fn async_set_cache(+ &self,+ key: &str,+ value: Self::Value,+ context: Self::Context,+ ) -> Result<(), Error> {+ self.set(key, value, &context).await+ }++ async fn async_get_cache(+ &self,+ key: &str,+ context: &Self::Context,+ ) -> Result<Option<Self::Value>, Error> {+ self.get(key, context).await+ }++ async fn async_set_cache_pipeline(+ &self,+ entries: Vec<(String, Self::Value)>,+ context: Self::Context,+ ) -> Result<(), Error> {+ try_join_all(entries.into_iter().map(|(key, value)| {+ let context = context.clone();+ async move { self.async_set_cache(&key, value, context).await }+ }))+ .await+ .map(|_| ())+ }++ async fn disconnect(&self) -> Result<(), Error> {+ Ok(())+ }++ async fn test_connection(&self) -> Result<CacheConnectionResult, Error> {+ Err(Error::UnsupportedOperation)+ }+}diff --cc litellm-rust/crates/cache-qdrant-semantic/tests/qdrant.rsindex d806a9cb455,00000000000..c7522c0b313mode 100644,000000..100644--- a/litellm-rust/crates/cache-qdrant-semantic/tests/qdrant.rs+++ b/litellm-rust/crates/cache-qdrant-semantic/tests/qdrant.rs@@@ -1,425 -1,0 +1,422 @@@+#[path = "support/mod.rs"]+mod support;++use std::{collections::HashMap, sync::Arc, time::Duration};+- use litellm_cache::{- BaseCache, CacheCodec, CacheContext, Error, SemanticCacheContext, SemanticCacheScope,- };++use litellm_cache::{BaseCache, CacheCodec, CacheContext, Error, SemanticCacheContext};+use litellm_cache_qdrant_semantic::{+ Embedder, QdrantSemanticCache, QdrantSemanticConfig, Quantization,+};+use litellm_cache_response::{+ CacheEntry, CacheKeyInput, ResponseCache, ResponseCacheCodec, ResponseCacheRequest,+};+use qdrant_client::Payload;+use qdrant_client::{+ Qdrant,+ qdrant::{self, CompressionRatio, Distance, PointId, QuantizationType, Value, VectorParams},+};+use serde_json::{Value as JsonValue, json};++use support::{FakeQdrant, FakeState, StoredPoint};++#[derive(Clone)]+struct FixedEmbedder {+ vectors: Arc<HashMap<String, Vec<f32>>>,+}++impl FixedEmbedder {+ fn new(vectors: impl IntoIterator<Item = (&'static str, Vec<f32>)>) -> Self {+ Self {+ vectors: Arc::new(+ vectors+ .into_iter()+ .map(|(prompt, vector)| (prompt.to_owned(), vector))+ .collect(),+ ),+ }+ }+}++impl Embedder for FixedEmbedder {+ fn model(&self) -> &str {+ "fixed"+ }++ async fn embed(&self, input: &str) -> Result<Vec<f32>, Error> {+ self.vectors.get(input).cloned().ok_or(Error::Unavailable)+ }+}++fn config(quantization: Quantization) -> QdrantSemanticConfig {+ QdrantSemanticConfig {+ collection_name: "semantic".to_owned(),+ similarity_threshold: 0.9,+ vector_size: 2,+ quantization,+ }+}++fn context(prompt: &str) -> SemanticCacheContext {+ SemanticCacheContext {- messages: vec![json!({"role": "user", "content": prompt})],- scope: SemanticCacheScope::default(),++ messages: Some(json!([{"role": "user", "content": prompt}])),+ ..Default::default()+ }+}++fn value(response: JsonValue) -> CacheEntry {+ CacheEntry {+ timestamp: Some(1.0),+ response,+ }+}++async fn connect(+ server: &FakeQdrant,+ vectors: impl IntoIterator<Item = (&'static str, Vec<f32>)>,+) -> QdrantSemanticCache<FixedEmbedder, ResponseCacheCodec> {+ let client = Qdrant::from_url(&server.url()).build().unwrap();+ QdrantSemanticCache::connect(+ client,+ FixedEmbedder::new(vectors),+ ResponseCacheCodec,+ config(Quantization::Binary),+ tokio::runtime::Handle::current(),+ )+ .await+ .unwrap()+}++#[tokio::test(flavor = "multi_thread")]+#[expect(+ deprecated,+ reason = "the test verifies Qdrant's legacy always_ram quantization contract"+)]+async fn connect_sets_collection_quantization_and_index() {+ for (quantization, expected) in [+ (Quantization::Binary, 0),+ (Quantization::Scalar, 1),+ (Quantization::Product, 2),+ ] {+ let server = FakeQdrant::start(FakeState::default()).await;+ let client = Qdrant::from_url(&server.url()).build().unwrap();+ QdrantSemanticCache::connect(+ client,+ FixedEmbedder::new([]),+ ResponseCacheCodec,+ config(quantization),+ tokio::runtime::Handle::current(),+ )+ .await+ .unwrap();+ let state = server.state.lock().unwrap();+ let request = &state.created_collections[0];+ let Some(qdrant::vectors_config::Config::Params(VectorParams { size, distance, .. })) =+ request+ .vectors_config+ .as_ref()+ .and_then(|config| config.config.clone())+ else {+ panic!("missing vector params");+ };+ assert_eq!(size, 2);+ assert_eq!(distance, Distance::Cosine as i32);+ let quantization_config = request+ .quantization_config+ .as_ref()+ .unwrap()+ .quantization+ .unwrap();+ match (expected, quantization_config) {+ (0, qdrant::quantization_config::Quantization::Binary(binary)) => {+ assert_eq!(binary.always_ram, Some(false));+ }+ (1, qdrant::quantization_config::Quantization::Scalar(scalar)) => {+ assert_eq!(scalar.r#type, QuantizationType::Int8 as i32);+ assert_eq!(scalar.quantile, Some(0.99));+ assert_eq!(scalar.always_ram, Some(false));+ }+ (2, qdrant::quantization_config::Quantization::Product(product)) => {+ assert_eq!(product.compression, CompressionRatio::X16 as i32);+ assert_eq!(product.always_ram, Some(false));+ }+ _ => panic!("unexpected quantization"),+ }+ assert!(state.index_creations >= 1);+ assert_eq!(state.field_indexes[0].collection_name, "semantic");+ assert_eq!(state.field_indexes[0].field_name, "litellm_cache_key");+ assert_eq!(+ state.field_indexes[0].field_type,+ Some(qdrant::FieldType::Keyword as i32)+ );+ server.stop();+ }+}++#[tokio::test(flavor = "multi_thread")]+async fn existing_collection_skips_create_and_index_failure_is_non_fatal() {+ let server = FakeQdrant::start(FakeState {+ collections: ["semantic".to_owned()].into_iter().collect(),+ fail_field_index: true,+ ..Default::default()+ })+ .await;+ let _cache = connect(&server, [("hello", vec![1.0, 0.0])]).await;+ let state = server.state.lock().unwrap();+ assert!(state.created_collections.is_empty());+ assert!(state.index_creations >= 1);+ server.stop();+}++#[tokio::test(flavor = "multi_thread")]+async fn async_and_sync_set_get_store_exact_payload() {+ let server = FakeQdrant::start(FakeState::default()).await;+ let cache = Arc::new(connect(&server, [("hello", vec![1.0, 0.0])]).await);+ let ctx = context("hello");+ let entry = value(json!({"answer": 42}));+ cache+ .async_set_cache("key", entry.clone(), ctx.clone())+ .await+ .unwrap();+ assert_eq!(+ cache.async_get_cache("key", &ctx).await.unwrap().as_ref(),+ Some(&entry)+ );+ {+ let state = server.state.lock().unwrap();+ let payload = &state.points[0].payload;+ let mut payload_keys = payload.keys().cloned().collect::<Vec<_>>();+ payload_keys.sort();+ assert_eq!(payload_keys, ["litellm_cache_key", "response", "text"]);+ assert_eq!(payload["litellm_cache_key"], Value::from("key"));+ assert_eq!(+ payload["response"],+ Value::from(String::from_utf8(ResponseCacheCodec.encode(&entry).unwrap()).unwrap())+ );+ }+ let sync_entry = entry.clone();+ let sync_cache = cache.clone();+ let sync_ctx = ctx.clone();+ tokio::task::spawn_blocking(move || {+ sync_cache+ .set_cache("sync", sync_entry.clone(), &sync_ctx)+ .unwrap();+ assert_eq!(+ sync_cache.get_cache("sync", &sync_ctx).unwrap(),+ Some(sync_entry)+ );+ })+ .await+ .unwrap();+ server.stop();+}++#[tokio::test(flavor = "multi_thread")]+async fn misses_and_payload_validation_are_safe() {+ let server = FakeQdrant::start(FakeState::default()).await;+ let cache = connect(+ &server,+ [("hello", vec![1.0, 0.0]), ("near", vec![0.7, 0.71414286])],+ )+ .await;+ let entry = value(json!({"answer": 1}));+ cache+ .async_set_cache("key", entry, context("hello"))+ .await+ .unwrap();+ assert_eq!(+ cache+ .async_get_cache("other", &context("hello"))+ .await+ .unwrap(),+ None+ );+ assert_eq!(+ cache+ .async_get_cache("key", &context("near"))+ .await+ .unwrap(),+ None+ );+ server.insert_point(StoredPoint {+ id: Some(PointId::from(99_u64)),+ vector: vec![1.0, 0.0],+ payload: Payload::try_from(json!({+ "litellm_cache_key": 99,+ "response": "{}",+ }))+ .unwrap()+ .into(),+ });+ assert_eq!(+ cache+ .async_get_cache("99", &context("hello"))+ .await+ .unwrap(),+ None+ );+ server.stop();+}++#[tokio::test(flavor = "multi_thread")]+async fn decoding_errors_missing_prompt_pipeline_and_ttl_behave_as_required() {+ let server = FakeQdrant::start(FakeState::default()).await;+ let cache = connect(&server, [("one", vec![1.0, 0.0]), ("two", vec![0.0, 1.0])]).await;+ let empty = SemanticCacheContext::default();+ assert_eq!(+ cache+ .async_set_cache("key", value(json!({})), empty.clone())+ .await,+ Err(Error::MissingPrompt)+ );+ assert_eq!(+ cache.async_get_cache("key", &empty).await,+ Err(Error::MissingPrompt)+ );+ assert_eq!(+ cache.async_get_cache("key", &context("unknown")).await,+ Err(Error::Unavailable)+ );+ cache+ .async_set_cache(+ "ttl",+ value(json!({"ttl": true})),+ context("one").with_ttl(Some(Duration::from_secs(1))),+ )+ .await+ .unwrap();+ tokio::time::sleep(Duration::from_millis(1_100)).await;+ assert!(+ cache+ .async_get_cache(+ "ttl",+ &context("one").with_ttl(Some(Duration::from_secs(1))),+ )+ .await+ .unwrap()+ .is_some()+ );+ cache+ .async_set_cache_pipeline(+ vec![+ ("one".to_owned(), value(json!({"n": 1}))),+ ("two".to_owned(), value(json!({"n": 2}))),+ ],+ context("one"),+ )+ .await+ .unwrap();+ assert!(+ cache+ .async_get_cache("one", &context("one"))+ .await+ .unwrap()+ .is_some()+ );+ assert!(+ cache+ .async_get_cache("two", &context("one"))+ .await+ .unwrap()+ .is_some()+ );+ assert_eq!(+ server.state.lock().unwrap().upsert_waits,+ vec![Some(true), Some(true), Some(true)]+ );+ assert_eq!(cache.get_ttl(&context("one")), None);+ assert_eq!(+ cache.test_connection().await,+ Err(Error::UnsupportedOperation)+ );+ server.stop();+}++#[tokio::test(flavor = "multi_thread")]+async fn response_payloads_decode_and_invalid_entries_fail() {+ let server = FakeQdrant::start(FakeState::default()).await;+ let cache = connect(&server, [("hello", vec![1.0, 0.0])]).await;+ for (key, response) in [+ ("python", json!("{'timestamp': 1.0, 'response': {'a': 1}}")),+ ("garbage", json!("not json")),+ ("missing", json!("unused")),+ ] {+ let mut payload = serde_json::Map::new();+ payload.insert("litellm_cache_key".to_owned(), json!(key));+ if key != "missing" {+ payload.insert("response".to_owned(), response);+ }+ server.insert_point(StoredPoint {+ id: Some(PointId::from(key.len() as u64)),+ vector: vec![1.0, 0.0],+ payload: Payload::try_from(JsonValue::Object(payload))+ .unwrap()+ .into(),+ });+ }+ assert_eq!(+ cache+ .async_get_cache("python", &context("hello"))+ .await+ .unwrap(),+ Some(value(json!({"a": 1})))+ );+ assert_eq!(+ cache.async_get_cache("garbage", &context("hello")).await,+ Err(Error::InvalidEntry)+ );+ assert_eq!(+ cache.async_get_cache("missing", &context("hello")).await,+ Err(Error::InvalidEntry)+ );+ server.stop();+}++#[tokio::test(flavor = "multi_thread")]+async fn response_cache_facade_turns_invalid_entry_into_miss() {+ let server = FakeQdrant::start(FakeState::default()).await;+ let cache = Arc::new(connect(&server, [("hello", vec![1.0, 0.0])]).await);+ let request = ResponseCacheRequest::<SemanticCacheContext>::new(CacheKeyInput {+ preset: Some("key".to_owned()),+ ..Default::default()+ })+ .with_context(context("hello"));+ let response = json!({"answer": 42});+ let facade = ResponseCache::new(cache.clone());+ facade+ .async_store(&request, response.clone(), Duration::from_secs(1))+ .await+ .unwrap();+ assert_eq!(+ facade+ .async_lookup(&request, Duration::from_secs(1))+ .await+ .unwrap(),+ Some(response)+ );+ {+ let mut state = server.state.lock().unwrap();+ state.points[0]+ .payload+ .insert("response".to_owned(), Value::from("not json"));+ }+ assert_eq!(+ facade+ .async_lookup(&request, Duration::from_secs(1))+ .await+ .unwrap(),+ None+ );+ server.stop();+}++#[tokio::test(flavor = "multi_thread")]+async fn stopped_qdrant_server_maps_to_unavailable() {+ let server = FakeQdrant::start(FakeState::default()).await;+ let cache = connect(&server, [("hello", vec![1.0, 0.0])]).await;+ server.stop();+ tokio::time::sleep(Duration::from_millis(50)).await;+ assert_eq!(+ cache.async_get_cache("key", &context("hello")).await,+ Err(Error::Unavailable)+ );+}diff --cc litellm-rust/crates/cache-response/tests/response.rsindex 56589063291,e4f78dae8b2..dcfc0301148--- a/litellm-rust/crates/cache-response/tests/response.rs+++ b/litellm-rust/crates/cache-response/tests/response.rs@@@ -33,82 -30,6 +33,82 @@@ fn request() -> ResponseCacheRequest})}+struct SemanticBackend {+ entries: Mutex<Vec<(String, CacheEntry)>>,+ contexts: Mutex<Vec<SemanticCacheContext>>,+}++impl BaseCache for SemanticBackend {+ type Value = CacheEntry;+ type Context = SemanticCacheContext;++ fn get_ttl(&self, _: &Self::Context) -> Option<Duration> {+ None+ }++ fn set_cache(+ &self,+ key: &str,+ value: Self::Value,+ context: &Self::Context,+ ) -> Result<(), Error> {+ self.contexts.lock().unwrap().push(context.clone());+ self.entries.lock().unwrap().push((key.to_owned(), value));+ Ok(())+ }++ fn get_cache(&self, key: &str, context: &Self::Context) -> Result<Option<Self::Value>, Error> {+ self.contexts.lock().unwrap().push(context.clone());+ Ok(self+ .entries+ .lock()+ .unwrap()+ .iter()+ .find(|(entry_key, _)| entry_key == key)+ .map(|(_, entry)| entry.clone()))+ }++ async fn disconnect(&self) -> Result<(), Error> {+ Ok(())+ }++ async fn test_connection(&self) -> Result<CacheConnectionResult, Error> {+ Ok(CacheConnectionResult {+ status: CacheConnectionStatus::Success,+ message: "ok".into(),+ error: None,+ })+ }+}++#[test]+fn semantic_context_reaches_backend_for_store_and_lookup() {+ let backend = Arc::new(SemanticBackend {+ entries: Mutex::new(Vec::new()),+ contexts: Mutex::new(Vec::new()),+ });+ let cache = ResponseCache::new(backend.clone());+ let context = SemanticCacheContext {- messages: vec![json!({"role": "user", "content": "hello"})],++ messages: Some(json!([{"role": "user", "content": "hello"}])),+ ..Default::default()+ };+ let request = request().with_context(context.clone());+ let response = json!({"answer": 42});++ cache+ .store(&request, response.clone(), Duration::from_secs(100))+ .unwrap();++ assert_eq!(+ cache.lookup(&request, Duration::from_secs(100)).unwrap(),+ Some(response)+ );+ assert_eq!(+ backend.contexts.lock().unwrap().as_slice(),+ &[context.clone(), context]+ );+}+#[tokio::test]async fn sync_and_async_consumers_share_keys_ttls_and_freshness() {let clock = Arc::new(AtomicU64::new(100));diff --cc litellm-rust/crates/python-bridge/Cargo.tomlindex bace8d61f58,bbe727f9345..6b4476d897c--- a/litellm-rust/crates/python-bridge/Cargo.toml+++ b/litellm-rust/crates/python-bridge/Cargo.toml@@@ -24,13 -24,15 +24,17 @@@ litellm-cache.workspace = trulitellm-cache-azure-blob.workspace = truelitellm-cache-memory.workspace = truelitellm-cache-redis.workspace = true+ litellm-cache-s3.workspace = truelitellm-cache-gcs.workspace = truelitellm-cache-disk.workspace = true+ litellm-cache-redis-semantic.workspace = truelitellm-cache-response.workspace = true+litellm-cache-qdrant-semantic.workspace = true+qdrant-client.workspace = true+ litellm-cache-valkey-semantic = { path = "../cache-valkey-semantic" }serde.workspace = truelitellm-auth.workspace = true+ litellm-auth-aws.workspace = truelitellm-callbacks-legacy-python.workspace = truelitellm-core.workspace = truelitellm-core-utils.workspace = true@@@ -42,10 -44,9 +46,11 @@@ litellm-host-python.workspace = trulitellm-token-counter = { path = "../token-counter", default-features = false }pyo3.workspace = truepyo3-async-runtimes.workspace = true+reqwest.workspace = true+ redis = { version = "1.7.0", features = ["tls-rustls"] }serde_json.workspace = true+url.workspace = true- tokio = { workspace = true, features = ["sync"] }+ tokio = { workspace = true, features = ["rt", "sync"] }[dev-dependencies]serde.workspace = truediff --cc litellm-rust/crates/python-bridge/src/cache/config.rsindex 8c26a6033c0,ef2a03ac9ba..d161b401928--- a/litellm-rust/crates/python-bridge/src/cache/config.rs+++ b/litellm-rust/crates/python-bridge/src/cache/config.rs@@@ -1,12 -1,13 +1,14 @@@- use std::{env, path::PathBuf, time::Duration};+ use std::{path::PathBuf, time::Duration};+ use litellm_auth_aws::AwsAuthConfig;use litellm_cache::CacheType;+use litellm_cache_qdrant_semantic::{OpenAiEmbedderConfig, QdrantSemanticConfig, Quantization};use litellm_cache_redis::{RedisNode, RedisTopology};+ use litellm_cache_s3::{S3CacheConfig, S3Endpoint};use pyo3::{- exceptions::{PyTypeError, PyValueError},+ exceptions::{PyAttributeError, PyTypeError, PyValueError},prelude::*,- types::{PyAny, PyDict, PyList, PyString},+ types::{PyAny, PyBool, PyDict, PyList, PyString},};use super::{native::NativeResponseCache, request::duration};@@@ -103,33 -117,23 +118,45 @@@ struct RedisClientProjection<'py>const REDIS_PY_DEFAULT_MAX_CONNECTIONS: usize = 1 << 31;+ #[allow(dead_code, reason = "consumed by the cache activation follow-up")]+ pub(super) struct ValkeySemanticCacheConfig {+ pub(super) similarity_threshold: f64,+ pub(super) index_name: String,+ pub(super) embedding_model: String,+ pub(super) connection: RedisConnectionConfig,+ }++pub(super) struct QdrantSemanticCacheConfig {+ pub(super) grpc_url: String,+ pub(super) api_key: Option<String>,+ pub(super) collection_name: String,+ pub(super) similarity_threshold: f64,+ pub(super) vector_size: u64,+ pub(super) embedding: OpenAiEmbedderConfig,+ pub(super) quantization: Quantization,+}++impl QdrantSemanticCacheConfig {+ pub(super) fn to_qdrant_config(&self) -> QdrantSemanticConfig {+ QdrantSemanticConfig {+ collection_name: self.collection_name.clone(),+ similarity_threshold: self.similarity_threshold,+ vector_size: self.vector_size,+ quantization: self.quantization.clone(),+ }+ }+}++pub(super) enum CacheBackendConfig {Memory(MemoryCacheConfig),Redis(Box<RedisCacheConfig>),+ S3(Box<S3CacheConfig>),Gcs(GcsCacheConfig),+ ValkeySemantic(Box<ValkeySemanticCacheConfig>),Disk(DiskCacheConfig),- QdrantSemantic(Box<QdrantSemanticCacheConfig>),AzureBlob(AzureBlobCacheConfig),+ RedisSemantic(Box<RedisSemanticCacheConfig>),++ QdrantSemantic(Box<QdrantSemanticCacheConfig>),}#[allow(dead_code, reason = "consumed by the cache activation follow-up")]@@@ -144,10 -148,11 +171,13 @@@ pub(super) enum UnsupportedCacheConfigRedisCredentials,RedisConnection,RedisOption,+ S3Client,+ S3Credentials,+ S3Option,GcsBucket,DiskStore,+ QdrantEndpoint,+ SemanticEmbedding,}impl UnsupportedCacheConfig {@@@ -158,12 -163,11 +188,15 @@@Self::RedisCredentials => "native Redis credentials require Python",Self::RedisConnection => "native Redis connection type is not implemented",Self::RedisOption => "native Redis configuration requires Python",+ Self::S3Client => "native S3 client type is not implemented",+ Self::S3Credentials => "native S3 credentials require Python",+ Self::S3Option => "native S3 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",}}}@@@ -233,16 -244,80 +280,81 @@@ impl NativeCacheConfigbackend: CacheBackendConfig::AzureBlob(backend),}))}),- Some(CacheType::RedisSemantic | CacheType::ValkeySemantic | CacheType::S3) | None => {- Ok(CacheConfigProjection::Unsupported(- UnsupportedCacheConfig::Backend,- ))- }+ Some(CacheType::RedisSemantic) => project_redis_semantic(&backend).map(|backend| {+ CacheConfigProjection::Native(Box::new(Self {+ policy,+ backend: CacheBackendConfig::RedisSemantic(Box::new(backend)),+ }))+ }),- Some(CacheType::QdrantSemantic) | None => Ok(CacheConfigProjection::Unsupported(++ 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::S3(_) => None,+ CacheBackendConfig::ValkeySemantic(_) => Some(Duration::ZERO),+ CacheBackendConfig::Disk(_)+ | CacheBackendConfig::AzureBlob(_)+ | CacheBackendConfig::Gcs(_)- | CacheBackendConfig::RedisSemantic(_) => None,++ | CacheBackendConfig::RedisSemantic(_)++ | CacheBackendConfig::QdrantSemantic(_) => None,+ };+ if !matches!(self.backend, CacheBackendConfig::ValkeySemantic(_))+ && 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::S3(_) if service.kind() != "s3" => {+ Some("facade and native backend types must match")+ }+ CacheBackendConfig::S3(config) if service.bucket() != Some(config.bucket.as_str()) => {+ Some("facade and native backend buckets must match")+ }+ CacheBackendConfig::S3(config)+ if service.key_prefix() != Some(config.key_prefix.as_str()) =>+ {+ Some("facade and native backend key prefixes must match")+ }+ CacheBackendConfig::S3(config) if service.region() != Some(config.region.as_str()) => {+ Some("facade and native backend regions must match")+ }+ CacheBackendConfig::S3(config)+ if service.endpoint()+ != config+ .endpoint+ .as_ref()+ .map(|endpoint| endpoint.url.as_str()) =>+ {+ Some("facade and native backend endpoints must match")+ }+ CacheBackendConfig::S3(_) => None,CacheBackendConfig::Gcs(_) if service.kind() != "gcs" => {Some("facade and native backend types must match")}@@@ -309,30 -364,20 +401,44 @@@let facade = std::fs::canonicalize(&config.directory).ok();(native != facade).then_some("facade and native backend directories must match")}+ CacheBackendConfig::RedisSemantic(_) if service.kind() != "redis_semantic" => {+ Some("facade and native backend types must match")+ }+ CacheBackendConfig::RedisSemantic(config)+ if service.index_name() != Some(config.index_name.as_str()) =>+ {+ Some("facade and native backend index names must match")+ }+ CacheBackendConfig::RedisSemantic(config)- if service.similarity_threshold() != Some(config.similarity_threshold as f32) =>++ if service.similarity_threshold() != Some(config.similarity_threshold) =>+ {+ Some("facade and native backend similarity thresholds must match")+ }+ CacheBackendConfig::RedisSemantic(_) => None,+ 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))@@@ -349,101 -391,6 +452,105 @@@}}+#[inline(never)]+fn project_qdrant_semantic(+ backend: &Bound<'_, PyAny>,+) -> PyResult<Result<QdrantSemanticCacheConfig, UnsupportedCacheConfig>> {+ let rest_url = backend.getattr("qdrant_api_base")?.extract::<String>()?;+ let parsed = match url::Url::parse(&rest_url) {+ Ok(value) => value,+ Err(_) => return Ok(Err(UnsupportedCacheConfig::QdrantEndpoint)),+ };+ if !matches!(parsed.scheme(), "http" | "https")- || !parsed.path().is_empty() && parsed.path() != "/"++ || (!parsed.path().is_empty() && parsed.path() != "/")+ || parsed.query().is_some()+ || parsed.host_str().is_none()+ || parsed.port() != Some(6333)+ {+ return Ok(Err(UnsupportedCacheConfig::QdrantEndpoint));+ }+ let mut grpc_url = parsed;+ if grpc_url.set_port(Some(6334)).is_err() {+ return Ok(Err(UnsupportedCacheConfig::QdrantEndpoint));+ }+ grpc_url.set_path("");+ grpc_url.set_query(None);+- let embedding_max_input_tokens = optional_attribute_i64(backend, "embedding_max_input_tokens")?;- if embedding_max_input_tokens.is_some() {++ if optional_attribute(backend, "embedding_max_input_tokens")?++ .is_some_and(|value| !value.is_none())++ {+ return Ok(Err(UnsupportedCacheConfig::SemanticEmbedding));+ }+ let configured_model = backend.getattr("embedding_model")?.extract::<String>()?;+ let embedding_model = configured_model+ .strip_prefix("openai/")+ .unwrap_or(&configured_model)+ .to_owned();+ if !embedding_model.starts_with("text-embedding-") {+ return Ok(Err(UnsupportedCacheConfig::SemanticEmbedding));+ }+ let proxy_server = py_sys_module(backend.py())?;+ if let Some(proxy_server) = proxy_server {+ let router = proxy_server.getattr("llm_router")?;+ let model_list = proxy_server.getattr("llm_model_list")?;+ let embedding_router = backend.py().import("litellm.caching._embedding_router")?;+ if !embedding_router+ .getattr("resolve_embedding_router")?+ .call1((configured_model.as_str(), router, model_list))?+ .is_none()+ {+ return Ok(Err(UnsupportedCacheConfig::SemanticEmbedding));+ }+ }+ let litellm = backend.py().import("litellm")?;+ for name in ["api_key", "openai_key", "api_base"] {+ if !litellm.getattr(name)?.is_none() {+ return Ok(Err(UnsupportedCacheConfig::SemanticEmbedding));+ }+ }- let Ok(embedding_api_key) = env::var("OPENAI_API_KEY") else {++ let Ok(embedding_api_key) = std::env::var("OPENAI_API_KEY") else {+ return Ok(Err(UnsupportedCacheConfig::SemanticEmbedding));+ };+ if embedding_api_key.is_empty() {+ return Ok(Err(UnsupportedCacheConfig::SemanticEmbedding));+ }- let embedding_api_base = env::var("OPENAI_BASE_URL")- .or_else(|_| env::var("OPENAI_API_BASE"))++ let embedding_api_base = std::env::var("OPENAI_BASE_URL")++ .or_else(|_| std::env::var("OPENAI_API_BASE"))+ .unwrap_or_else(|_| "https://api.openai.com/v1".to_owned());- let timeout = optional_attribute_f64(backend, "embedding_timeout")?++ let timeout = optional_attribute(backend, "embedding_timeout")?++ .map(|value| value.extract::<Option<f64>>())++ .transpose()?++ .flatten()+ .map(duration)+ .transpose()?;+ Ok(Ok(QdrantSemanticCacheConfig {+ grpc_url: grpc_url.to_string().trim_end_matches('/').to_owned(),+ api_key: optional_string(backend.getattr("qdrant_api_key")?)?,+ collection_name: backend.getattr("collection_name")?.extract()?,+ similarity_threshold: backend.getattr("similarity_threshold")?.extract()?,+ vector_size: backend.getattr("vector_size")?.extract::<u64>()?,+ embedding: OpenAiEmbedderConfig {+ api_base: embedding_api_base,+ api_key: embedding_api_key,+ model: embedding_model,+ timeout,+ },+ quantization: Quantization::Binary,+ }))+}++fn py_sys_module(py: Python<'_>) -> PyResult<Option<Bound<'_, PyAny>>> {+ match py+ .import("sys")?+ .getattr("modules")?+ .get_item("litellm.proxy.proxy_server")+ {+ Ok(module) => Ok(Some(module)),+ Err(error) if error.is_instance_of::<pyo3::exceptions::PyKeyError>(py) => Ok(None),+ Err(error) => Err(error),+ }+}+#[inline(never)]fn project_azure_blob(backend: &Bound<'_, PyAny>) -> PyResult<AzureBlobCacheConfig> {let client = backend.getattr("container_client")?;diff --cc litellm-rust/crates/python-bridge/src/cache/facade.rsindex 3a998d511fd,f1389b745e9..43b53584943--- a/litellm-rust/crates/python-bridge/src/cache/facade.rs+++ b/litellm-rust/crates/python-bridge/src/cache/facade.rs@@@ -345,17 -363,22 +363,27 @@@ impl FacadeGuardlet (module, name, cache_kind) = match (kind, cluster) {("memory", _) => ("litellm.caching.in_memory_cache", "InMemoryCache", "local"),("redis", false) => ("litellm.caching.redis_cache", "RedisCache", "redis"),- ("redis", true) => (- "litellm.caching.redis_cluster_cache",- "RedisClusterCache",- "redis",+ ("redis_semantic", _) => (+ "litellm.caching.redis_semantic_cache",+ "RedisSemanticCache",+ "redis-semantic",),+ ("qdrant_semantic", _) => (+ "litellm.caching.qdrant_semantic_cache",+ "QdrantSemanticCache",+ "qdrant-semantic",+ ),+ ("redis", true) => (+ "litellm.caching.redis_cluster_cache",+ "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",@@@ -419,7 -428,33 +433,37 @@@"semantic_cache_scope",],)?,- backend: ObjectGuard::capture(py, &backend, backend_config_names)?,+ backend: ObjectGuard::capture(+ py,+ &backend,+ &[+ "namespace",+ "default_ttl",+ "max_size_in_memory",+ "max_size_per_item",+ "redis_kwargs",+ "redis_flush_size",+ "similarity_threshold",+ "distance_threshold",+ "embedding_model",+ "embedding_max_input_tokens",+ "embedding_timeout",++ "qdrant_api_base",++ "qdrant_api_key",++ "collection_name",++ "vector_size",+ "_index_name",+ "_redis_url",+ "similarity_threshold",+ "embedding_model",+ "index_name",+ "embedding_max_input_tokens",+ "embedding_timeout",+ "bucket_name",+ "key_prefix",+ "path_service_account",+ ],+ )?,disk_store: (kind == "disk").then(|| DiskStoreGuard::capture(&backend)).transpose()?,diff --cc litellm-rust/crates/python-bridge/src/cache/handle.rsindex 87f0ff98f67,e6edf48d72f..51e1b02c405--- a/litellm-rust/crates/python-bridge/src/cache/handle.rs+++ b/litellm-rust/crates/python-bridge/src/cache/handle.rs@@@ -1,19 -1,19 +1,27 @@@- use std::env;-+ use litellm_auth_aws::AwsAuthConfig;use litellm_cache_gcs::{DEFAULT_ENDPOINT, GcsConfig};- use litellm_cache_redis::{RedisNode, RedisTopology};- use litellm_http::ClientVariant;-+use litellm_cache_qdrant_semantic::{OpenAiEmbedderConfig, Quantization};+ use litellm_cache_redis::{RedisNode, RedisTopology};+ use litellm_cache_redis_semantic::RedisSemanticConfig;+ use litellm_cache_s3::{S3CacheConfig, S3Endpoint};use litellm_host_python::{release_gil, run_sync_value};- use pyo3::{PyTraverseError, PyVisit, exceptions::PyRuntimeError, prelude::*, types::PyDict};++use litellm_http::ClientVariant;+ use pyo3::{+ PyTraverseError, PyVisit,+ exceptions::{PyRuntimeError, PyTypeError},+ prelude::*,++ types::PyDict,+ };+use url::Url;use super::{- cache_error, config::QdrantSemanticCacheConfig, facade::FacadeGuard,- cache_error, config::project_redis_semantic, embedder::PythonEmbedder, facade::FacadeGuard,-- native::NativeResponseCache, request::duration,++ cache_error,++ config::{QdrantSemanticCacheConfig, project_redis_semantic},++ embedder::PythonEmbedder,++ facade::FacadeGuard,++ native::NativeResponseCache,++ request::duration,};- use crate::http;#[pyclass(frozen, name = "_CacheTestHandle")]pub(crate) struct CacheTestHandle {@@@ -112,105 -146,29 +154,128 @@@ impl CacheTestHandle})}+ #[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)++ || parsed.port() != Some(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")++ std::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"))++ std::env::var("OPENAI_BASE_URL")++ .or_else(|_| std::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()++ let http_config = crate::http::call_config(py, &PyDict::new(py), true)?;++ let client = crate::http::pool()+ .client(&http_config, ClientVariant::Provider)- .map_err(http::client_error)?;++ .map_err(crate::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 = (url, similarity_threshold, index_name, embedder))]+ fn valkey_semantic(+ url: String,+ similarity_threshold: f64,+ index_name: String,+ embedder: &Bound<'_, PyAny>,+ ) -> PyResult<Self> {+ let python_embedder = PythonEmbedder::from_backend(embedder)?;+ let service = NativeResponseCache::valkey_semantic(+ &url,+ similarity_threshold,+ index_name,+ python_embedder,+ )+ .map_err(cache_error)?;+ Ok(Self {+ service,+ guard: None,+ pid: std::process::id(),+ })+ }+#[staticmethod]#[pyo3(signature = (account_url, container))]fn azure_blob(py: Python<'_>, account_url: String, container: String) -> PyResult<Self> {diff --cc litellm-rust/crates/python-bridge/src/cache/native.rsindex 7e1a4c27bc6,acc457d8c9c..7ca62f10ec8--- a/litellm-rust/crates/python-bridge/src/cache/native.rs+++ b/litellm-rust/crates/python-bridge/src/cache/native.rs@@@ -5,14 -7,72 +7,74 @@@ use litellm_cache_azure_blob::AzureBlobuse 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_redis_semantic::{RedisSemanticCache, RedisSemanticConfig};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::{PyTraverseError, PyVisit, prelude::*};use serde_json::Value;- use super::{config::QdrantSemanticCacheConfig, request::exact};+ use super::{++ config::QdrantSemanticCacheConfig,+ embedder::PythonEmbedder,+ request::NativeRequest,+ semantic::{SemanticBody, SemanticOperation, drive},+ 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 {@@@ -21,9 -81,18 +83,19 @@@cache: Arc<ResponseCache<RedisCache<ResponseCacheCodec>>>,buffer: Option<Arc<WriteBuffer>>,},+ S3(Arc<ResponseCache<S3Cache<ResponseCacheCodec>>>),Gcs(Arc<ResponseCache<GcsCache<ResponseCacheCodec>>>),- Disk(Arc<ResponseCache<DiskCache<ResponseCacheCodec>>>),+ ValkeySemantic {+ cache: Arc<ResponseCache<ValkeySemanticCache<PythonEmbedder, ResponseCacheCodec>>>,+ embedder: PythonEmbedder,+ scope: String,+ },+ RedisSemantic {+ cache: Arc<ResponseCache<RedisSemanticCache<PythonEmbedder>>>,+ embedder: PythonEmbedder,+ },+ QdrantSemantic(Arc<ResponseCache<QdrantSemanticCache<OpenAiEmbedder, ResponseCacheCodec>>>),+ Disk(Arc<ResponseCache<DiskCache<ResponseCacheCodec>>>),AzureBlob(Arc<ResponseCache<AzureBlobCache<ResponseCacheCodec>>>),}@@@ -56,48 -125,66 +128,91 @@@ impl NativeResponseCache})}- 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 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 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 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 redis_semantic(+ url: &str,+ embedder: PythonEmbedder,+ config: RedisSemanticConfig,+ ) -> Result<Self, Error> {+ let backend = RedisSemanticCache::new(url, embedder.clone(), config)?;+ Ok(Self::RedisSemantic {+ cache: Arc::new(ResponseCache::new(Arc::new(backend))),+ embedder,+ })}+ 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 fn disk(directory: &str) -> Result<Self, Error> {+ let cache = DiskCache::open(directory, ResponseCacheCodec)?;+ 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 azure_blob(account_url: &str, container: &str) -> Result<Self, Error> {let backend = AzureBlobCache::connect(account_url,@@@ -119,21 -206,90 +234,92 @@@)),Self::Memory(_)| Self::Redis { .. }- | Self::Gcs(_)+ | Self::S3(_)+ | Self::ValkeySemantic { .. }+ | Self::RedisSemantic { .. }++ | Self::QdrantSemantic(_)| Self::Disk(_)- | Self::QdrantSemantic(_) => None,+ | 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,+ }+ }+- pub(super) fn redis_semantic_request(++ pub(super) fn semantic_request(+ request: &NativeRequest,+ ) -> ResponseCacheRequest<SemanticCacheContext> {+ ResponseCacheRequest {+ key: request.key.clone(),+ controls: request.controls,+ context: SemanticCacheContext {+ input: request.input.clone(),+ messages: request.messages.clone(),+ metadata: request.metadata.clone(),+ scope: request.scope.clone(),+ 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::Disk(_) => "disk",+ Self::ValkeySemantic { .. } => "valkey-semantic",+ Self::RedisSemantic { .. } => "redis_semantic",+ Self::QdrantSemantic(_) => "qdrant_semantic",+ Self::Disk(_) => "disk",Self::AzureBlob(_) => "azure-blob",}}@@@ -142,9 -298,11 +328,12 @@@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::Disk(cache) => cache.default_ttl(),+ Self::ValkeySemantic { cache, .. } => cache.default_ttl(),+ Self::RedisSemantic { cache, .. } => cache.default_ttl(),+ Self::QdrantSemantic(_) => None,+ Self::Disk(cache) => cache.default_ttl(),Self::AzureBlob(cache) => cache.default_ttl(),}}@@@ -152,8 -338,10 +369,11 @@@pub fn namespace(&self) -> Option<&str> {match self {Self::Memory(_)- | Self::Disk(_)+ | Self::S3(_)+ | Self::ValkeySemantic { .. }+ | Self::RedisSemantic { .. }+ | Self::QdrantSemantic(_)+ | Self::Disk(_)| Self::AzureBlob(_)| Self::Gcs(_) => None,Self::Redis { cache, .. } => cache.backend().namespace(),@@@ -163,8 -351,10 +383,11 @@@pub fn topology(&self) -> Option<&RedisTopology> {match self {Self::Memory(_)- | Self::Disk(_)+ | Self::S3(_)+ | Self::ValkeySemantic { .. }+ | Self::RedisSemantic { .. }+ | Self::QdrantSemantic(_)+ | Self::Disk(_)| Self::AzureBlob(_)| Self::Gcs(_) => None,Self::Redis { cache, .. } => Some(cache.backend().topology()),@@@ -174,28 -364,26 +397,28 @@@pub fn capacity(&self) -> Option<usize> {match self {Self::Memory(cache) => Some(cache.backend().max_size_in_memory()),- Self::Redis { .. } | Self::Gcs(_) | Self::Disk(_) => None,- Self::QdrantSemantic(_) => None,- Self::AzureBlob(_) => None,+ Self::Redis { .. }+ | Self::S3(_)+ | Self::ValkeySemantic { .. }+ | Self::RedisSemantic { .. }++ | Self::QdrantSemantic(_)+ | Self::Disk(_)+ | 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::Gcs(_) | Self::Disk(_) => None,- Self::QdrantSemantic(_) => None,- Self::AzureBlob(_) => None,- }- }-- pub fn with_redis_flush_size(self, flush_size: Option<usize>) -> Self {- match self {- Self::Redis { cache, .. } => Self::Redis {- cache,- buffer: flush_size.map(|flush_size| Arc::new(WriteBuffer::new(flush_size))),- },- other => other,+ Self::Redis { .. }+ | Self::S3(_)+ | Self::ValkeySemantic { .. }+ | Self::RedisSemantic { .. }++ | Self::QdrantSemantic(_)+ | Self::Disk(_)+ | Self::AzureBlob(_)+ | Self::Gcs(_) => None,}}@@@ -204,9 -392,11 +427,12 @@@Self::Disk(cache) => Some(cache.backend().directory()),Self::Memory(_)| Self::Redis { .. }- | Self::Gcs(_)+ | Self::S3(_)+ | Self::ValkeySemantic { .. }+ | Self::RedisSemantic { .. }+ | Self::QdrantSemantic(_)- | Self::AzureBlob(_) => None,+ | Self::AzureBlob(_)+ | Self::Gcs(_) => None,}}@@@ -217,39 -421,41 +457,66 @@@}}- pub fn similarity_threshold(&self) -> Option<f32> {+ pub fn similarity_threshold(&self) -> Option<f64> {+ match self {++ Self::RedisSemantic { cache, .. } => {++ Some(f64::from(cache.backend().similarity_threshold()))++ }+ Self::QdrantSemantic(cache) => Some(cache.backend().similarity_threshold()),+ _ => None,+ }+ }+++ pub fn collection_name(&self) -> Option<&str> {++ match self {++ Self::QdrantSemantic(cache) => Some(cache.backend().collection_name()),++ _ => None,++ }++ }+++ pub fn vector_size(&self) -> Option<u64> {match self {- Self::RedisSemantic { cache, .. } => Some(cache.backend().similarity_threshold()),+ 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,}}- pub fn lookup(- &self,- request: &ResponseCacheRequest<SemanticCacheContext>,- now: Duration,- ) -> Result<Option<Value>, Error> {+ pub fn semantic_embedder(&self) -> Option<&PythonEmbedder> {match self {- 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),+ Self::RedisSemantic { embedder, .. } => Some(embedder),+ _ => None,+ }+ }++ pub fn embedder_object(&self) -> Option<&Py<PyAny>> {+ match self {+ Self::RedisSemantic { embedder, .. } => Some(embedder.object()),+ _ => 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::RedisSemantic { cache, .. } => {- cache.lookup(&Self::redis_semantic_request(request), now)++ cache.lookup(&Self::semantic_request(request), now)+ }+ Self::Gcs(cache) => cache.lookup(&Self::exact(request), now),++ Self::QdrantSemantic(cache) => cache.lookup(&Self::semantic_request(request), now),+ Self::Disk(cache) => cache.lookup(&Self::exact(request), now),+ Self::AzureBlob(cache) => cache.lookup(&Self::exact(request), now),}}@@@ -260,12 -466,18 +527,21 @@@now: Duration,) -> Result<(), Error> {match self {- 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),+ 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::RedisSemantic { cache, .. } => {- cache.store(&Self::redis_semantic_request(request), response, now)++ cache.store(&Self::semantic_request(request), response, now)+ }+ Self::Gcs(cache) => cache.store(&Self::exact(request), response, now),++ Self::QdrantSemantic(cache) => {++ cache.store(&Self::semantic_request(request), response, now)++ }+ Self::Disk(cache) => cache.store(&Self::exact(request), response, now),+ Self::AzureBlob(cache) => cache.store(&Self::exact(request), response, now),}}@@@ -276,20 -488,27 +552,27 @@@) -> Result<PartialHits, Error> {match self {Self::Memory(cache) => {- cache.lookup_batch(&requests.iter().map(exact).collect::<Vec<_>>(), now)+ let requests = requests.iter().map(Self::exact).collect::<Vec<_>>();+ cache.lookup_batch(&requests, now)}Self::Redis { cache, .. } => {- cache.lookup_batch(&requests.iter().map(exact).collect::<Vec<_>>(), now)+ 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 { .. } | Self::RedisSemantic { .. } => {++ Self::ValkeySemantic { .. } | Self::RedisSemantic { .. } | Self::QdrantSemantic(_) => {+ Err(Error::UnsupportedOperation)}Self::Gcs(cache) => {- cache.lookup_batch(&requests.iter().map(exact).collect::<Vec<_>>(), now)+ cache.lookup_batch(&requests.iter().map(Self::exact).collect::<Vec<_>>(), now)}Self::Disk(cache) => {- cache.lookup_batch(&requests.iter().map(exact).collect::<Vec<_>>(), now)+ cache.lookup_batch(&requests.iter().map(Self::exact).collect::<Vec<_>>(), now)}- Self::QdrantSemantic(_) => Err(Error::UnsupportedOperation),Self::AzureBlob(cache) => {- cache.lookup_batch(&requests.iter().map(exact).collect::<Vec<_>>(), now)+ cache.lookup_batch(&requests.iter().map(Self::exact).collect::<Vec<_>>(), now)}}}@@@ -300,12 -519,60 +583,73 @@@now: Duration,) -> Result<Option<Value>, Error> {match self {- 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,+ 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::RedisSemantic { cache, .. } => {+ cache- .async_lookup(&Self::redis_semantic_request(request), now)++ .async_lookup(&Self::semantic_request(request), now)++ .await++ }++ Self::QdrantSemantic(cache) => {++ cache++ .async_lookup(&Self::semantic_request(request), 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),+ ),+ ),+ Self::RedisSemantic { .. } => drive(+ py,+ SemanticBody::new(self.clone(), SemanticOperation::Lookup(request)),+ ),++ Self::QdrantSemantic(_) => {++ let service = self.clone();++ litellm_host_python::run_async(++ py,++ async move { service.async_lookup(&request, super::request::now()).await },++ super::cache_error,++ )++ }}}@@@ -325,13 -600,84 +677,101 @@@cache,buffer: Some(buffer),} => {- let request = exact(request);- buffer.async_store(cache, &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::RedisSemantic { cache, .. } => {+ cache- .async_store(&Self::redis_semantic_request(request), response, now)++ .async_store(&Self::semantic_request(request), response, now)++ .await++ }++ Self::QdrantSemantic(cache) => {++ cache++ .async_store(&Self::semantic_request(request), 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,+ ),+ ),+ Self::RedisSemantic { .. } => drive(+ py,+ SemanticBody::new(self.clone(), SemanticOperation::Store(request, response)),+ ),++ Self::QdrantSemantic(_) => {++ 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::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,}}@@@ -346,21 -692,31 +786,31 @@@cache.async_lookup_batch(&requests, now).await}Self::Redis { cache, .. } => {- let requests = requests.iter().map(exact).collect::<Vec<_>>();+ 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 { .. } | Self::RedisSemantic { .. } => {++ Self::ValkeySemantic { .. } | Self::RedisSemantic { .. } | Self::QdrantSemantic(_) => {+ Err(Error::UnsupportedOperation)+ }Self::Gcs(cache) => {- let requests = requests.iter().map(exact).collect::<Vec<_>>();- cache.async_lookup_batch(&requests, now).await+ cache+ .async_lookup_batch(&requests.iter().map(Self::exact).collect::<Vec<_>>(), now)+ .await}Self::Disk(cache) => {- let requests = requests.iter().map(exact).collect::<Vec<_>>();- cache.async_lookup_batch(&requests, now).await+ cache+ .async_lookup_batch(&requests.iter().map(Self::exact).collect::<Vec<_>>(), 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+ cache+ .async_lookup_batch(&requests.iter().map(Self::exact).collect::<Vec<_>>(), now)+ .await}}}@@@ -372,64 -728,107 +822,110 @@@) -> Result<(), Error> {match self {Self::Memory(cache) => {- cache- .async_store_batch(- entries- .into_iter()- .map(|(request, value)| (exact(&request), value))- .collect(),- now,- )- .await+ let entries = entries+ .into_iter()+ .map(|(request, value)| (Self::exact(&request), value))+ .collect();+ cache.async_store_batch(entries, now).await}Self::Redis { cache, .. } => {- cache- .async_store_batch(- entries- .into_iter()- .map(|(request, value)| (exact(&request), value))- .collect(),- now,- )- .await+ 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::RedisSemantic { .. } => Err(Error::UnsupportedOperation),++ Self::RedisSemantic { .. } | Self::QdrantSemantic(_) => {++ Err(Error::UnsupportedOperation)+ }Self::Gcs(cache) => {- cache- .async_store_batch(- entries- .into_iter()- .map(|(request, value)| (exact(&request), value))- .collect(),- now,- )- .await+ let entries = entries+ .into_iter()+ .map(|(request, value)| (Self::exact(&request), value))+ .collect();+ cache.async_store_batch(entries, now).await}Self::Disk(cache) => {- cache- .async_store_batch(- entries- .into_iter()- .map(|(request, value)| (exact(&request), value))- .collect(),- now,- )- .await+ let entries = entries+ .into_iter()+ .map(|(request, value)| (Self::exact(&request), value))+ .collect();+ cache.async_store_batch(entries, 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+ 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,+ ),+ )+ }+ Self::RedisSemantic { .. } => drive(+ py,+ SemanticBody::new(self.clone(), SemanticOperation::StoreBatch(entries.into())),+ ),++ Self::QdrantSemantic(_) => Err(super::cache_error(Error::UnsupportedOperation)),+ }+ }+pub async fn async_flush(&self) -> Result<(), Error> {match self {Self::Memory(cache) => cache.async_flush().await,@@@ -439,9 -838,12 +935,12 @@@}cache.async_flush().await}+ Self::S3(cache) => cache.async_flush().await,- Self::ValkeySemantic { .. } | Self::RedisSemantic { .. } => {++ Self::ValkeySemantic { .. } | Self::RedisSemantic { .. } | Self::QdrantSemantic(_) => {+ Err(Error::UnsupportedOperation)+ }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,}}@@@ -450,9 -852,11 +949,13 @@@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::RedisSemantic { .. } => Err(Error::UnsupportedOperation),++ Self::RedisSemantic { .. } | Self::QdrantSemantic(_) => {++ Err(Error::UnsupportedOperation)++ }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,}}diff --cc litellm-rust/crates/python-bridge/src/cache/semantic.rsindex 00000000000,7661598c5f9..934de01e721mode 000000,100644..100644--- a/litellm-rust/crates/python-bridge/src/cache/semantic.rs+++ b/litellm-rust/crates/python-bridge/src/cache/semantic.rs@@@ -1,0 -1,175 +1,175 @@@+ use std::collections::VecDeque;++ use litellm_cache::Error;+ use litellm_cache_redis_semantic::prompt_from_context;+ use litellm_host_python::{Execution, ExecutionBody, ExecutionStep, run_async};+ use pyo3::{+ PyTraverseError, PyVisit,+ exceptions::{PyException, PyRuntimeError},+ prelude::*,+ };+ use serde_json::Value;++ use super::{+ cache_error,+ embedder::{PythonEmbedder, with_prepared_embedding},+ native::NativeResponseCache,+ request::{NativeRequest, now},+ };++ pub(super) enum SemanticOperation {+ Lookup(NativeRequest),+ Store(NativeRequest, Value),+ StoreBatch(VecDeque<(NativeRequest, Value)>),+ }++ enum Phase {+ Start,+ AwaitingEmbedding,+ AwaitingBackend,+ }++ pub(super) struct SemanticBody {+ service: NativeResponseCache,+ operation: SemanticOperation,+ pending: Option<(NativeRequest, Option<Value>)>,+ phase: Phase,+ }++ impl SemanticBody {+ pub(super) fn new(service: NativeResponseCache, operation: SemanticOperation) -> Self {+ Self {+ service,+ operation,+ pending: None,+ phase: Phase::Start,+ }+ }++ fn backend_step(+ &mut self,+ py: Python<'_>,+ seed: Result<Vec<f32>, Error>,+ ) -> PyResult<ExecutionStep> {+ self.phase = Phase::AwaitingBackend;+ let (request, response) = self.pending.take().ok_or_else(|| {+ PyRuntimeError::new_err("semantic execution resumed without a pending operation")+ })?;+ let service = self.service.clone();+ let future = async move {+ match response {+ None => service.async_lookup(&request, now()).await,+ Some(response) => service+ .async_store(&request, response, now())+ .await+ .map(|_| None),+ }+ };+ let awaitable = run_async(py, with_prepared_embedding(seed, future), cache_error)?;+ Ok(ExecutionStep::Await(awaitable.unbind()))+ }+ }++ impl ExecutionBody for SemanticBody {+ fn resume(&mut self, mut result: Option<PyResult<Py<PyAny>>>) -> PyResult<ExecutionStep> {+ Python::attach(|py| {+ loop {+ match self.phase {+ Phase::Start => {+ if result.is_some() {+ return Err(PyRuntimeError::new_err(+ "semantic execution received a result before starting",+ ));+ }+ if self.pending.is_none() {+ match &mut self.operation {+ SemanticOperation::Lookup(request) => {+ self.pending = Some((request.clone(), None));+ }+ SemanticOperation::Store(request, response) => {+ let response = std::mem::replace(response, Value::Null);+ self.pending = Some((request.clone(), Some(response)));+ }+ SemanticOperation::StoreBatch(queue) => {+ let Some((request, response)) = queue.pop_front() else {+ return Ok(ExecutionStep::Return(py.None()));+ };+ self.pending = Some((request, Some(response)));+ }+ }+ }+ let (request, _) = self.pending.as_ref().ok_or_else(|| {+ PyRuntimeError::new_err("semantic execution has no pending operation")+ })?;- let semantic = NativeResponseCache::redis_semantic_request(request);++ let semantic = NativeResponseCache::semantic_request(request);+ let Some(prompt) = prompt_from_context(&semantic.context) else {+ return self.backend_step(py, Err(Error::Unavailable));+ };+ let embedder = self.service.semantic_embedder().ok_or_else(|| {+ PyRuntimeError::new_err(+ "semantic execution requires a redis-semantic backend",+ )+ })?;+ let coroutine = embedder.async_embedding_coroutine(+ py,+ &prompt,+ semantic.context.metadata.as_ref(),+ )?;+ self.phase = Phase::AwaitingEmbedding;+ return Ok(ExecutionStep::Await(coroutine));+ }+ Phase::AwaitingEmbedding => {+ let result = result.take().ok_or_else(|| {+ PyRuntimeError::new_err(+ "semantic execution expected an embedding result",+ )+ })?;+ let seed = match result {+ Ok(value) => PythonEmbedder::extract(value.into_bound(py))+ .map_err(|_| Error::Unavailable),+ Err(error) => {+ if !error.is_instance_of::<PyException>(py) {+ return Err(error);+ }+ Err(Error::Unavailable)+ }+ };+ return self.backend_step(py, seed);+ }+ Phase::AwaitingBackend => {+ let result = result.take().ok_or_else(|| {+ PyRuntimeError::new_err("semantic execution expected a backend result")+ })?;+ let value = match result {+ Ok(value) => value,+ Err(error) => return Err(error),+ };+ let more = matches!(+ &self.operation,+ SemanticOperation::StoreBatch(queue) if !queue.is_empty()+ );+ if more {+ self.phase = Phase::Start;+ continue;+ }+ return Ok(ExecutionStep::Return(value));+ }+ }+ }+ })+ }++ fn traverse(&self, visit: &PyVisit<'_>) -> Result<(), PyTraverseError> {+ if let Some(embedder) = self.service.semantic_embedder() {+ embedder.traverse(visit)?;+ }+ Ok(())+ }+ }++ pub(super) fn drive(py: Python<'_>, body: SemanticBody) -> PyResult<Bound<'_, PyAny>> {+ let execution = Py::new(py, Execution::new(body))?;+ py.import("litellm.rust_bridge.lifecycle")?+ .getattr("drive")?+ .call1((execution,))+ }diff --cc litellm/rust_bridge/_native.pyiindex 05a6df6d5af,c0bb93daadc..31623a53dd0--- a/litellm/rust_bridge/_native.pyi+++ b/litellm/rust_bridge/_native.pyi@@@ -93,6 -93,119 +93,133 @@@ class ResponsesWebSocketConnectiondef recv_text(self) -> Future[str | None]: ...def close(self) -> Future[None]: ...+ @final+ class _CacheTestBinding:+ @property+ def kind(self) -> str: ...+ def lookup(+ self,+ request: object,+ *,+ callback_kwargs: Mapping[str, object] | Sequence[object] | None = None,+ ) -> object: ...+ def store(+ self,+ request: object,+ response: object,+ *,+ callback_kwargs: Mapping[str, object] | None = None,+ ) -> None: ...+ def lookup_batch(+ self,+ requests: Sequence[object],+ *,+ callback_kwargs: Sequence[object] | None = None,+ ) -> object: ...+ def async_lookup(+ self,+ request: object,+ *,+ callback_kwargs: Mapping[str, object] | None = None,+ ) -> Future[object]: ...+ def async_store(+ self,+ request: object,+ response: object,+ *,+ callback_kwargs: Mapping[str, object] | None = None,+ ) -> Future[None]: ...+ def async_lookup_batch(+ self,+ requests: Sequence[object],+ *,+ callback_kwargs: Sequence[object] | None = None,+ ) -> Future[object]: ...+ def async_store_batch(+ self,+ requests: Sequence[object],+ responses: Sequence[object],+ *,+ callback_result: object = None,+ callback_kwargs: Mapping[str, object] | None = None,+ ) -> Future[object]: ...+ def async_flush(self) -> Future[None]: ...+ def ping(self) -> Future[object]: ...++ @final+ class _CacheTestHandle:+ def __new__(cls, _uninstantiable: Never, /) -> Never: ...+ @staticmethod+ def memory(+ *,+ capacity: int = 200,+ ttl_seconds: float = 600.0,+ max_entry_bytes: int = 1048576,+ ) -> _CacheTestHandle: ...+ @staticmethod+ def redis(+ url: str,+ *,+ ttl_seconds: float = 60.0,+ namespace: str | None = None,+ startup_nodes: Sequence[tuple[str, int]] | None = None,+ ) -> _CacheTestHandle: ...+ @staticmethod+ def disk(directory: str) -> _CacheTestHandle: ...+ @staticmethod++ def qdrant_semantic(++ url: str,++ *,++ collection_name: str,++ similarity_threshold: float,++ vector_size: int,++ embedding_model: str = "text-embedding-3-small",++ api_key: str | None = None,++ embedding_api_key: str | None = None,++ embedding_api_base: str | None = None,++ embedding_timeout_seconds: float | None = None,++ quantization: str = "binary",++ ) -> _CacheTestHandle: ...++ @staticmethod+ def azure_blob(account_url: str, container: str) -> _CacheTestHandle: ...+ @staticmethod+ def redis_semantic(backend: object) -> _CacheTestHandle: ...+ @staticmethod+ def valkey_semantic(+ url: str,+ similarity_threshold: float,+ index_name: str,+ embedder: object,+ ) -> _CacheTestHandle: ...+ @staticmethod+ def gcs(+ bucket_name: str,+ *,+ gcs_path: str | None = None,+ path_service_account: str | None = None,+ endpoint: str | None = None,+ token: str | None = None,+ ) -> _CacheTestHandle: ...+ @staticmethod+ def s3(+ bucket: str,+ *,+ region: str,+ endpoint_url: str | None = None,+ key_prefix: str = "",+ access_key_id: str | None = None,+ secret_access_key: str | None = None,+ session_token: str | None = None,+ ) -> _CacheTestHandle: ...+ @property+ def backend(self) -> str: ...+ def _bind_facade(self, facade: object) -> None: ...++ @final+ class _CacheTestResolver:+ def __new__(cls, namespace: object) -> _CacheTestResolver: ...+ def resolve(self) -> _CacheTestBinding: ...+@finalclass TokenCounter:def __new__(cls, tokenizer_json: str) -> TokenCounter: ...diff --cc tests/test_litellm_rust/test_cache.pyindex 1bb2849f335,45f7214ecbf..c4962b533c4--- a/tests/test_litellm_rust/test_cache.py+++ b/tests/test_litellm_rust/test_cache.py@@@ -47,71 -59,6 +60,71 @@@ def request(key: str = "key") -> dict[sreturn {"key": {"preset": key}}- def semantic_request(++def qdrant_request(+ key: str,+ messages: list[dict[str, object]],+ **kwargs: object,+) -> dict[str, object]:+ return {**request(key), "messages": messages, **kwargs}+++def embedding_vector(text: str) -> list[float]:- raw = hashlib.sha256(text.encode()).digest()[:8]++ raw: Final = hashlib.sha256(text.encode()).digest()[:8]+ values: Final = [byte / 127.5 - 1 for byte in raw]+ norm: Final = math.sqrt(sum(value * value for value in values))+ return [value / norm for value in values]+++def qdrant_url() -> str:+ value: Final[str | None] = os.environ.get("QDRANT_URL")+ if not value:+ pytest.skip("QDRANT_URL is required for Qdrant semantic cache tests")+ return value.rstrip("/")+++def fake_embedding_endpoint(monkeypatch: pytest.MonkeyPatch) -> Generator[str]:+ class EmbeddingHandler(http.server.BaseHTTPRequestHandler):+ def do_POST(self) -> None:+ length: Final = int(self.headers["Content-Length"])+ body: Final = json.loads(self.rfile.read(length))+ text: Final = body["input"]+ response: Final = {+ "object": "list",+ "data": [+ {+ "object": "embedding",+ "index": 0,+ "embedding": embedding_vector(text),+ }+ ],+ "model": body["model"],+ "usage": {"prompt_tokens": 1, "total_tokens": 1},+ }+ encoded: Final = json.dumps(response).encode()+ self.send_response(200)+ self.send_header("Content-Type", "application/json")+ self.send_header("Content-Length", str(len(encoded)))+ self.end_headers()+ self.wfile.write(encoded)++ def log_message(self, *_args: object) -> None:+ return++ server: Final = http.server.ThreadingHTTPServer(("127.0.0.1", 0), EmbeddingHandler)+ worker: Final = threading.Thread(target=server.serve_forever, daemon=True)+ worker.start()+ monkeypatch.setenv("OPENAI_API_BASE", f"http://127.0.0.1:{server.server_address[1]}")+ monkeypatch.setenv("OPENAI_API_KEY", "sk-test")+ try:+ yield f"http://127.0.0.1:{server.server_address[1]}"+ finally:+ server.shutdown()+ server.server_close()+ worker.join(timeout=5)++@pytest.fixturedef redis_url() -> Generator[str]:server: Final = fakeredis.TcpFakeServer(("127.0.0.1", 0), server_type="redis")@@@ -988,192 -1124,570 +1190,734 @@@ async def test_redis_cluster_facade_serfacade.cache.redis_client.close()- def qdrant_facade(- qdrant_url: str,- collection_name: str,- ) -> Cache:+ PARAPHRASE_MARKER: Final = " (paraphrase)"+ SEMANTIC_EMBEDDING_MODEL: Final = "semantic-test/deterministic"+ SEMANTIC_INDEX_PREFIX: Final = "litellm_test_semantic_"+ SEMANTIC_CONTEXT: Final = contextvars.ContextVar("semantic_test_context", default="unset")+++ def _normalized(vector: list[float]) -> list[float]:+ norm: Final = math.sqrt(sum(component * component for component in vector))+ return [component / norm for component in vector]+++ def _base_embedding(prompt: str) -> list[float]:+ digest: Final = hashlib.sha256(prompt.encode("utf-8")).digest()+ return _normalized([float(digest[index] + 1) for index in range(8)])+++ def _semantic_embedding(prompt: str) -> list[float]:+ if PARAPHRASE_MARKER not in prompt:+ return _base_embedding(prompt)+ base: Final = _base_embedding(prompt.replace(PARAPHRASE_MARKER, "").strip())+ pivot: Final = min(range(8), key=lambda index: abs(base[index]))+ direction: Final = _normalized(+ [+ (1.0 - base[pivot] * base[pivot]) if index == pivot else -base[index] * base[pivot]+ for index in range(8)+ ]+ )+ # Rotating an orthogonal unit direction by 0.329 produces ~0.05 cosine distance+ return _normalized([base[index] + 0.329 * direction[index] for index in range(8)])+++ class DeterministicEmbedding(litellm.CustomLLM):+ def __init__(self) -> None:+ self.calls: list[dict[str, object]] = []+ self.async_calls: list[dict[str, object]] = []+ self.entered = asyncio.Event()+ self.gate: asyncio.Event | None = None++ def _respond(+ self,+ model: str,+ input: object,+ model_response: EmbeddingResponse,+ ) -> EmbeddingResponse:+ texts: Final = cast(list[object], input if isinstance(input, list) else [input])+ self.calls.append({"model": model, "input": texts})+ model_response.model = model+ model_response.data = [+ {"object": "embedding", "index": index, "embedding": _semantic_embedding(str(text))}+ for index, text in enumerate(texts)+ ]+ return model_response++ def embedding(+ self,+ model: str,+ input: list[object],+ model_response: EmbeddingResponse,+ print_verbose: Callable[..., object],+ logging_obj: object,+ optional_params: dict[str, object],+ api_key: object = None,+ api_base: object = None,+ timeout: object = None,+ litellm_params: object = None,+ ) -> EmbeddingResponse:+ return self._respond(model, input, model_response)++ async def aembedding(+ self,+ model: str,+ input: list[object],+ model_response: EmbeddingResponse,+ print_verbose: Callable[..., object],+ logging_obj: object,+ optional_params: dict[str, object],+ api_key: object = None,+ api_base: object = None,+ timeout: object = None,+ litellm_params: object = None,+ ) -> EmbeddingResponse:+ texts: Final = cast(list[object], input if isinstance(input, list) else [input])+ self.async_calls.append(+ {+ "model": model,+ "input": texts,+ "task": asyncio.current_task(),+ "context": SEMANTIC_CONTEXT.get(),+ }+ )+ SEMANTIC_CONTEXT.set("written-in-aembedding")+ self.entered.set()+ if self.gate is not None:+ await self.gate.wait()+ return self._respond(model, input, model_response)+++ @pytest.fixture+ def semantic_embedding() -> Generator[DeterministicEmbedding]:+ handler: Final = DeterministicEmbedding()+ with ExitStack() as stack:+ stack.enter_context(+ rebound(+ litellm,+ "custom_provider_map",+ [+ *litellm.custom_provider_map,+ cast(+ CustomLLMItem,+ {"provider": "semantic-test", "custom_handler": handler},+ ),+ ],+ )+ )+ stack.enter_context(+ rebound(+ litellm,+ "_custom_providers", # pyright: ignore[reportPrivateUsage] # no public provider-registration hook+ [*litellm._custom_providers, "semantic-test"], # pyright: ignore[reportPrivateUsage] # no public provider-registration hook+ )+ )+ stack.enter_context(+ rebound(litellm, "provider_list", [*litellm.provider_list, "semantic-test"])+ )+ yield handler+++ @pytest.fixture+ def redis_stack() -> Generator[tuple[str, str]]:+ url: Final = os.environ.get("LITELLM_REDIS_STACK_URL")+ if url is None:+ pytest.skip("LITELLM_REDIS_STACK_URL is not set")+ index: Final = f"{SEMANTIC_INDEX_PREFIX}{uuid4().hex}"+ yield url, index+ client: Final = redis.Redis.from_url(url)+ try:+ client.execute_command("FT.DROPINDEX", index, "DD") # pyright: ignore[reportUnknownMemberType] # redis-py leaves execute_command partially unknown+ except redis.RedisError:+ pass+ client.close()+++ def semantic_request(key: str, prompt: str, **extra: object) -> dict[str, object]:+ return {+ "key": {"preset": key},+ "messages": [{"role": "user", "content": prompt}],+ **extra,+ }+++ def semantic_messages(prompt: str) -> list[dict[str, object]]:+ return [{"role": "user", "content": prompt}]+++ def semantic_entry_id(prompt: str, tag: str) -> str:+ return hashlib.sha256(f"{prompt}litellm_cache_key{tag}".encode()).hexdigest()+++ def semantic_facade(url: str, index: str, *, similarity_threshold: float = 0.8) -> Cache:+ facade: Final = Cache(+ type=LiteLLMCacheType.REDIS_SEMANTIC,+ redis_url=url,+ similarity_threshold=similarity_threshold,+ redis_semantic_cache_embedding_model=SEMANTIC_EMBEDDING_MODEL,+ redis_semantic_cache_index_name=index,+ )+ _CacheTestHandle.redis_semantic(facade.cache)._bind_facade(facade)+ return facade+++ def test_redis_semantic_constructor_identity_and_provenance(+ redis_stack: tuple[str, str], semantic_embedding: DeterministicEmbedding+ ) -> None:+ url, index = redis_stack+ facade: Final = semantic_facade(url, index)+ backend: Final = cast(RedisSemanticCache, facade.cache)+ assert backend.__class__.__module__ == "litellm.caching.redis_semantic_cache"+ assert type(backend) is RedisSemanticCache+ assert backend._redis_url == url # pyright: ignore[reportPrivateUsage] # provenance check needs the projected config+ assert backend._index_name == index # pyright: ignore[reportPrivateUsage] # provenance check needs the projected config+ assert backend.similarity_threshold == 0.8+ assert backend.embedding_model == SEMANTIC_EMBEDDING_MODEL+ handle: Final = cast(object, getattr(facade, "_native_cache_handle"))+ assert isinstance(handle, _CacheTestHandle)+ assert handle.backend == "redis_semantic"+ binding: Final = _CacheTestResolver(SimpleNamespace(cache=facade)).resolve()+ assert binding.kind == "native"+++ def test_redis_semantic_native_and_python_sync_entries_share_one_layout(+ redis_stack: tuple[str, str], semantic_embedding: DeterministicEmbedding+ ) -> None:+ url, index = redis_stack+ facade: Final = semantic_facade(url, index)+ binding: Final = _CacheTestResolver(SimpleNamespace(cache=facade)).resolve()+ client: Final = redis.Redis.from_url(url)+ response: Final = {"choices": [{"text": "paris"}], "usage": {"total_tokens": 2}}++ binding.store(semantic_request("geo", "what is the capital of france"), response)++ native_hash_key: Final = f"{index}:{semantic_entry_id('what is the capital of france', 'geo')}"+ stored: Final = client.hgetall(native_hash_key)+ assert set(stored) == {+ b"entry_id",+ b"prompt",+ b"response",+ b"prompt_vector",+ b"inserted_at",+ b"updated_at",+ b"litellm_cache_key",+ }, stored+ assert stored[b"entry_id"].decode() == native_hash_key.split(":", 1)[1]+ assert stored[b"prompt"] == b"what is the capital of france"+ assert stored[b"litellm_cache_key"] == b"geo"+ assert len(stored[b"prompt_vector"]) == 32+ decoded: Final = cast(dict[str, object], json.loads(stored[b"response"]))+ assert decoded["response"] == response+ assert (+ cast(RedisSemanticCache, facade.cache).get_cache( # pyright: ignore[reportUnknownMemberType] # **kwargs stays unknown on the backend class+ "geo", messages=semantic_messages("what is the capital of france")+ )+ == decoded+ )+ assert semantic_embedding.calls == [+ {"model": "deterministic", "input": ["what is the capital of france"]},+ {"model": "deterministic", "input": ["what is the capital of france"]},+ {"model": "deterministic", "input": ["dimension test"]},+ ]++ cast(RedisSemanticCache, facade.cache).set_cache( # pyright: ignore[reportUnknownMemberType] # **kwargs stays unknown on the backend class+ "math",+ json.dumps({"timestamp": 1700000000.0, "response": {"answer": 42}}),+ messages=semantic_messages("what is 6 times 7"),+ )+ python_hash_key: Final = f"{index}:{semantic_entry_id('what is 6 times 7', 'math')}"+ assert json.loads(cast(bytes, client.hget(python_hash_key, "response"))) == {+ "timestamp": 1700000000.0,+ "response": {"answer": 42},+ }+ assert binding.lookup(semantic_request("math", "what is 6 times 7")) == {"answer": 42}+ client.close()+++ async def test_redis_semantic_async_paths_and_store_batch_share_one_layout(+ redis_stack: tuple[str, str], semantic_embedding: DeterministicEmbedding+ ) -> None:+ url, index = redis_stack+ facade: Final = semantic_facade(url, index)+ binding: Final = _CacheTestResolver(SimpleNamespace(cache=facade)).resolve()+ client: Final = redis.Redis.from_url(url)++ await binding.async_store(+ semantic_request("async", "name a primary color"), {"answer": "blue"}+ )+ hash_key: Final = f"{index}:{semantic_entry_id('name a primary color', 'async')}"+ decoded: Final = cast(dict[str, object], json.loads(cast(bytes, client.hget(hash_key, "response"))))+ python_read: Final = await cast(RedisSemanticCache, facade.cache).async_get_cache( # pyright: ignore[reportUnknownMemberType] # **kwargs stays unknown on the backend class+ "async", messages=semantic_messages("name a primary color")+ )+ assert python_read == decoded++ await binding.async_store_batch(+ [+ semantic_request("batch-one", "first batch prompt"),+ semantic_request("batch-two", "second batch prompt"),+ ],+ [{"answer": 1}, {"answer": 2}],+ )+ expected: Final = {+ key: json.loads(+ cast(bytes, client.hget(f"{index}:{semantic_entry_id(prompt, key)}", "response"))+ )+ for key, prompt in (+ ("batch-one", "first batch prompt"),+ ("batch-two", "second batch prompt"),+ )+ }+ for key, prompt in (+ ("batch-one", "first batch prompt"),+ ("batch-two", "second batch prompt"),+ ):+ assert cast(RedisSemanticCache, facade.cache).get_cache( # pyright: ignore[reportUnknownMemberType] # **kwargs stays unknown on the backend class+ key, messages=semantic_messages(prompt)+ ) == expected[key], key++ cast(RedisSemanticCache, facade.cache).set_cache( # pyright: ignore[reportUnknownMemberType] # **kwargs stays unknown on the backend class+ "async-python",+ json.dumps({"timestamp": 1700000000.0, "response": {"answer": "python"}}),+ messages=semantic_messages("python written prompt"),+ )+ assert await binding.async_lookup(+ semantic_request("async-python", "python written prompt")+ ) == {"answer": "python"}+ client.close()+++ async def test_native_semantic_async_embedding_runs_inline_in_the_callers_task(+ redis_stack: tuple[str, str], semantic_embedding: DeterministicEmbedding+ ) -> None:+ url, index = redis_stack+ facade: Final = semantic_facade(url, index)+ binding: Final = _CacheTestResolver(SimpleNamespace(cache=facade)).resolve()+ assert binding.kind == "native"+ caller: Final = asyncio.current_task()+ SEMANTIC_CONTEXT.set("caller-sentinel")+ response: Final = {"choices": [{"text": "paris"}]}++ await binding.async_store(+ semantic_request("inline", "what is the capital of france"), response+ )+ assert (+ await binding.async_lookup(+ semantic_request("inline", f"what is the capital of france{PARAPHRASE_MARKER}")+ )+ == response+ )+ assert await binding.async_lookup(semantic_request("inline", "python written prompt")) is None+ assert SEMANTIC_CONTEXT.get() == "written-in-aembedding"+ assert semantic_embedding.async_calls == [+ {+ "model": "deterministic",+ "input": ["what is the capital of france"],+ "task": caller,+ "context": "caller-sentinel",+ },+ {+ "model": "deterministic",+ "input": [f"what is the capital of france{PARAPHRASE_MARKER}"],+ "task": caller,+ "context": "written-in-aembedding",+ },+ {+ "model": "deterministic",+ "input": ["python written prompt"],+ "task": caller,+ "context": "written-in-aembedding",+ },+ ], semantic_embedding.async_calls+++ async def test_native_semantic_cancellation_during_embedding_skips_the_backend(+ redis_stack: tuple[str, str], semantic_embedding: DeterministicEmbedding+ ) -> None:+ url, index = redis_stack+ facade: Final = semantic_facade(url, index)+ binding: Final = _CacheTestResolver(SimpleNamespace(cache=facade)).resolve()+ assert binding.kind == "native"+ semantic_embedding.gate = asyncio.Event()++ async def lookup() -> object:+ return await binding.async_lookup(+ semantic_request("cancel", "cancelled prompt")+ )++ task: Final = asyncio.create_task(lookup())+ await semantic_embedding.entered.wait()+ task.cancel()+ with pytest.raises(asyncio.CancelledError):+ await task+ semantic_embedding.gate.set()++ assert len(semantic_embedding.async_calls) == 1+ assert (+ await cast(RedisSemanticCache, facade.cache).async_get_cache( # pyright: ignore[reportUnknownMemberType] # **kwargs stays unknown on the backend class+ "cancel", messages=semantic_messages("cancelled prompt")+ )+ is None+ )+++ def test_redis_semantic_similarity_tag_and_threshold_boundaries(+ redis_stack: tuple[str, str], semantic_embedding: DeterministicEmbedding+ ) -> None:+ url, index = redis_stack+ facade: Final = semantic_facade(url, index)+ binding: Final = _CacheTestResolver(SimpleNamespace(cache=facade)).resolve()++ binding.store(semantic_request("sim", "tell me a joke"), {"answer": "haha"})+ paraphrase: Final = f"tell me a joke{PARAPHRASE_MARKER}"+ assert binding.lookup(semantic_request("sim", paraphrase)) == {"answer": "haha"}+ assert binding.lookup(semantic_request("sim", "an unrelated question about spreadsheets")) is None+ assert binding.lookup(semantic_request("other-key", "tell me a joke")) is None++ strict: Final = semantic_facade(url, index, similarity_threshold=0.99)+ strict_binding: Final = _CacheTestResolver(SimpleNamespace(cache=strict)).resolve()+ assert strict_binding.lookup(semantic_request("sim", paraphrase)) is None+ assert strict_binding.lookup(semantic_request("sim", "tell me a joke")) == {"answer": "haha"}+++ def test_redis_semantic_ttl_is_written_only_when_requested(+ redis_stack: tuple[str, str], semantic_embedding: DeterministicEmbedding+ ) -> None:+ url, index = redis_stack+ facade: Final = semantic_facade(url, index)+ binding: Final = _CacheTestResolver(SimpleNamespace(cache=facade)).resolve()+ client: Final = redis.Redis.from_url(url)++ binding.store(+ {**semantic_request("ttl", "ttl prompt"), "ttl_seconds": 12.0}, {"answer": 1}+ )+ expiring: Final = f"{index}:{semantic_entry_id('ttl prompt', 'ttl')}"+ assert 0 < client.ttl(expiring) <= 12++ binding.store(semantic_request("ttl-none", "untimed prompt"), {"answer": 2})+ persistent: Final = f"{index}:{semantic_entry_id('untimed prompt', 'ttl-none')}"+ assert client.ttl(persistent) == -1++ binding.store(+ {**semantic_request("ttl-fraction", "fractional prompt"), "ttl_seconds": 1.5},+ {"answer": 3},+ )+ fractional: Final = f"{index}:{semantic_entry_id('fractional prompt', 'ttl-fraction')}"+ assert client.ttl(fractional) == 2+ client.close()+++ def test_redis_semantic_malformed_response_is_a_miss_for_both_readers(+ redis_stack: tuple[str, str], semantic_embedding: DeterministicEmbedding+ ) -> None:+ url, index = redis_stack+ facade: Final = semantic_facade(url, index)+ binding: Final = _CacheTestResolver(SimpleNamespace(cache=facade)).resolve()+ client: Final = redis.Redis.from_url(url)++ binding.store(semantic_request("bad", "corrupt me"), {"answer": 1})+ hash_key: Final = f"{index}:{semantic_entry_id('corrupt me', 'bad')}"+ client.hset(hash_key, "response", b"{not json")+ assert binding.lookup(semantic_request("bad", "corrupt me")) is None+ assert (+ cast(RedisSemanticCache, facade.cache).get_cache( # pyright: ignore[reportUnknownMemberType] # **kwargs stays unknown on the backend class+ "bad", messages=semantic_messages("corrupt me")+ )+ is None+ )+ client.close()+++ async def test_redis_semantic_unsupported_operations_raise_not_implemented(+ redis_stack: tuple[str, str], semantic_embedding: DeterministicEmbedding+ ) -> None:+ url, index = redis_stack+ facade: Final = semantic_facade(url, index)+ binding: Final = _CacheTestResolver(SimpleNamespace(cache=facade)).resolve()++ with pytest.raises(NotImplementedError):+ binding.lookup_batch([semantic_request("batch", "prompt one")])+ with pytest.raises(NotImplementedError):+ await binding.async_lookup_batch([semantic_request("batch", "prompt one")])+ with pytest.raises(NotImplementedError):+ await binding.async_flush()+ with pytest.raises(NotImplementedError):+ await binding.ping()+++ def test_redis_semantic_requests_without_prompt_are_noops(+ redis_stack: tuple[str, str], semantic_embedding: DeterministicEmbedding+ ) -> None:+ url, index = redis_stack+ facade: Final = semantic_facade(url, index)+ binding: Final = _CacheTestResolver(SimpleNamespace(cache=facade)).resolve()+ client: Final = redis.Redis.from_url(url)++ binding.store(request("plain"), {"answer": 1})+ assert binding.lookup(request("plain")) is None+ assert semantic_embedding.calls == []+ assert client.keys(f"{index}:*") == []+ client.close()+++ def test_redis_semantic_scope_overrides_the_tag_and_isolates_entries(+ redis_stack: tuple[str, str], semantic_embedding: DeterministicEmbedding+ ) -> None:+ url, index = redis_stack+ facade: Final = semantic_facade(url, index)+ binding: Final = _CacheTestResolver(SimpleNamespace(cache=facade)).resolve()+ client: Final = redis.Redis.from_url(url)++ scoped: Final = {**semantic_request("scoped", "scoped prompt"), "scope": "team-a"}+ binding.store(scoped, {"answer": "kept"})+ hash_key: Final = f"{index}:{semantic_entry_id('scoped prompt', 'team-a')}"+ assert client.hget(hash_key, "litellm_cache_key") == b"team-a"+ assert binding.lookup(scoped) == {"answer": "kept"}+ assert binding.lookup(semantic_request("scoped", "scoped prompt")) is None+ assert binding.lookup({**scoped, "scope": "team-b"}) is None+ client.close()+++ def test_redis_semantic_configuration_drift_falls_back_to_python(+ redis_stack: tuple[str, str],+ semantic_embedding: DeterministicEmbedding,+ monkeypatch: pytest.MonkeyPatch,+ ) -> None:+ url, index = redis_stack+ facade: Final = semantic_facade(url, index)+ resolver: Final = _CacheTestResolver(SimpleNamespace(cache=facade))+ assert resolver.resolve().kind == "native"++ with rebound(facade.cache, "similarity_threshold", 0.5):+ assert resolver.resolve().kind == "python_callback"+ with rebound(facade, "semantic_cache_scope", "end_user"):+ assert resolver.resolve().kind == "python_callback"+ with rebound(facade.cache, "embedding_model", "other-model"):+ assert resolver.resolve().kind == "python_callback"+ with rebound(facade.cache, "_index_name", "other-index"):+ assert resolver.resolve().kind == "python_callback"+ with rebound(facade.cache, "CACHE_KEY_FIELD_NAME", "other-field"):+ assert resolver.resolve().kind == "python_callback"++ def patched_embedding(self: object, prompt: str, metadata: object = None) -> list[float]:+ return _semantic_embedding(prompt)++ monkeypatch.setattr(RedisSemanticCache, "_get_embedding", patched_embedding)+ assert resolver.resolve().kind == "python_callback"+++ def test_redis_semantic_handle_rejects_wrong_backends(+ redis_stack: tuple[str, str], semantic_embedding: DeterministicEmbedding+ ) -> None:+ url, index = redis_stack++ class CustomSemanticCache(RedisSemanticCache):+ pass++ with pytest.raises(TypeError, match="built-in RedisSemanticCache"):+ _CacheTestHandle.redis_semantic(object())+ with pytest.raises(TypeError, match="built-in RedisSemanticCache"):+ _CacheTestHandle.redis_semantic(+ CustomSemanticCache(+ redis_url=url,+ similarity_threshold=0.8,+ embedding_model=SEMANTIC_EMBEDDING_MODEL,+ index_name=f"{index}_subclass",+ )+ )++ facade: Final = semantic_facade(url, index)+ with pytest.raises(TypeError, match="backend types must match"):+ _CacheTestHandle.redis(url)._bind_facade(facade)++ subclassed_facade: Final = Cache(+ type=LiteLLMCacheType.REDIS_SEMANTIC,+ redis_url=url,+ similarity_threshold=0.8,+ redis_semantic_cache_embedding_model=SEMANTIC_EMBEDDING_MODEL,+ redis_semantic_cache_index_name=index,+ )+ subclassed_facade.cache = CustomSemanticCache( # pyright: ignore[reportAttributeAccessIssue] # facade backend slot is not declared++ redis_url=url,+ similarity_threshold=0.8,+ embedding_model=SEMANTIC_EMBEDDING_MODEL,+ index_name=index,+ )+ with pytest.raises(TypeError):+ _CacheTestHandle.redis_semantic(+ subclassed_facade.cache+ )._bind_facade(subclassed_facade)++ replacement_facade: Final = Cache(+ type=LiteLLMCacheType.REDIS_SEMANTIC,+ redis_url=url,+ similarity_threshold=0.8,+ redis_semantic_cache_embedding_model=SEMANTIC_EMBEDDING_MODEL,+ redis_semantic_cache_index_name=index,+ )+ with pytest.raises(TypeError, match="must be the native embedder"):+ _CacheTestHandle.redis_semantic(facade.cache)._bind_facade(replacement_facade)++++++def qdrant_facade(qdrant_url: str, collection_name: str) -> Cache:+ return Cache(+ type=LiteLLMCacheType.QDRANT_SEMANTIC,+ qdrant_api_base=qdrant_url,+ qdrant_collection_name=collection_name,+ similarity_threshold=0.99,+ qdrant_semantic_cache_embedding_model="text-embedding-3-small",+ qdrant_semantic_cache_vector_size=8,+ )+++def test_qdrant_semantic_facade_binds_native_and_shares_entries(- qdrant_url: str,- fake_embedding_endpoint: str,++ qdrant_url: str, fake_embedding_endpoint: str+) -> None:+ del fake_embedding_endpoint+ messages: Final = [{"role": "user", "content": "shared prompt"}]+ collection: Final = f"cache_{uuid4().hex}"+ facade: Final = qdrant_facade(qdrant_url, collection)+ facade.cache.set_cache(+ "python-key",+ {"timestamp": time.time(), "response": json.dumps({"id": "py"})},+ messages=messages,+ )+ handle: Final = _native._CacheTestHandle.qdrant_semantic(+ qdrant_url,+ collection_name=collection,+ similarity_threshold=0.99,+ vector_size=8,+ )+ handle._bind_facade(facade)+ binding: Final = _native._CacheTestResolver(SimpleNamespace(cache=facade)).resolve()+ assert binding.kind == "native"- assert binding.lookup(semantic_request("python-key", messages)) == {"id": "py"}- binding.store(semantic_request("native-key", messages), {"id": "native"})++ assert binding.lookup(qdrant_request("python-key", messages)) == {"id": "py"}++ binding.store(qdrant_request("native-key", messages), {"id": "native"})+ python_value: Final = facade.cache.get_cache("native-key", messages=messages)+ assert isinstance(python_value, dict)+ assert python_value["response"] == {"id": "native"}+ unrelated: Final = [{"role": "user", "content": "unrelated prompt"}]- assert binding.lookup(semantic_request("native-key", unrelated)) is None++ assert binding.lookup(qdrant_request("native-key", unrelated)) is None+ assert facade.cache.get_cache("native-key", messages=unrelated) is None- assert binding.lookup(semantic_request("different-key", messages)) is None++ assert binding.lookup(qdrant_request("different-key", messages)) is None+ assert facade.cache.get_cache("different-key", messages=messages) is None+++async def test_qdrant_semantic_async_parity(- qdrant_url: str,- fake_embedding_endpoint: str,++ qdrant_url: str, fake_embedding_endpoint: str+) -> None:+ del fake_embedding_endpoint+ messages: Final = [{"role": "user", "content": "async prompt"}]+ collection: Final = f"cache_{uuid4().hex}"+ facade: Final = qdrant_facade(qdrant_url, collection)+ handle: Final = _native._CacheTestHandle.qdrant_semantic(+ qdrant_url,+ collection_name=collection,+ similarity_threshold=0.99,+ vector_size=8,+ )+ handle._bind_facade(facade)+ binding: Final = _native._CacheTestResolver(SimpleNamespace(cache=facade)).resolve()+ await facade.cache.async_set_cache(+ "python-key",+ {"timestamp": time.time(), "response": json.dumps({"id": "py"})},+ messages=messages,+ )-- assert await binding.async_lookup(semantic_request("python-key", messages)) == {"id": "py"}- await binding.async_store(semantic_request("native-key", messages), {"id": "native"})++ assert await binding.async_lookup(qdrant_request("python-key", messages)) == {"id": "py"}++ await binding.async_store(qdrant_request("native-key", messages), {"id": "native"})+ python_value: Final = await facade.cache.async_get_cache("native-key", messages=messages)+ assert isinstance(python_value, dict)+ assert python_value["response"] == {"id": "native"}+++async def test_qdrant_semantic_malformed_entries_and_unsupported_operations(- qdrant_url: str,- fake_embedding_endpoint: str,++ qdrant_url: str, fake_embedding_endpoint: str+) -> None:+ del fake_embedding_endpoint+ messages: Final = [{"role": "user", "content": "malformed prompt"}]+ collection: Final = f"cache_{uuid4().hex}"+ facade: Final = qdrant_facade(qdrant_url, collection)+ handle: Final = _native._CacheTestHandle.qdrant_semantic(+ qdrant_url,+ collection_name=collection,+ similarity_threshold=0.99,+ vector_size=8,+ )+ handle._bind_facade(facade)+ binding: Final = _native._CacheTestResolver(SimpleNamespace(cache=facade)).resolve()+ key: Final = "malformed-key"+ response: Final = {+ "points": [+ {+ "id": str(uuid4()),+ "vector": embedding_vector("malformed prompt"),+ "payload": {+ "litellm_cache_key": key,+ "text": "malformed prompt",+ "response": "not json",+ },+ }+ ]+ }+ facade.cache.sync_client.put(+ url=f"{qdrant_url}/collections/{collection}/points",+ headers=facade.cache.headers,+ json=response,+ )- assert binding.lookup(semantic_request(key, messages)) is None- with pytest.raises(RuntimeError, match="does not support"):- binding.lookup_batch([semantic_request(key, messages)])- with pytest.raises(RuntimeError, match="does not support"):++ assert binding.lookup(qdrant_request(key, messages)) is None++ with pytest.raises(RuntimeError, match="operation is not supported"):++ binding.lookup_batch([qdrant_request(key, messages)])++ with pytest.raises(RuntimeError, match="operation is not supported"):+ await binding.async_flush()- with pytest.raises(RuntimeError, match="does not support"):++ with pytest.raises(RuntimeError, match="operation is not supported"):+ await binding.ping()+++def test_qdrant_semantic_ignores_request_expiry(- qdrant_url: str,- fake_embedding_endpoint: str,++ qdrant_url: str, fake_embedding_endpoint: str+) -> None:+ del fake_embedding_endpoint+ messages: Final = [{"role": "user", "content": "persistent prompt"}]+ collection: Final = f"cache_{uuid4().hex}"+ facade: Final = qdrant_facade(qdrant_url, collection)+ handle: Final = _native._CacheTestHandle.qdrant_semantic(+ qdrant_url,+ collection_name=collection,+ similarity_threshold=0.99,+ vector_size=8,+ )+ handle._bind_facade(facade)+ binding: Final = _native._CacheTestResolver(SimpleNamespace(cache=facade)).resolve()- binding.store(- semantic_request("persistent-key", messages, ttl_seconds=1.0),- {"id": "persistent"},- )++ binding.store(qdrant_request("persistent-key", messages, ttl_seconds=1.0), {"id": "persistent"})+ time.sleep(1.2)- assert binding.lookup(semantic_request("persistent-key", messages)) == {"id": "persistent"}++ assert binding.lookup(qdrant_request("persistent-key", messages)) == {"id": "persistent"}+ python_value: Final = facade.cache.get_cache("persistent-key", messages=messages)+ assert isinstance(python_value, dict)+ assert python_value["response"] == {"id": "persistent"}+++def test_qdrant_semantic_mutation_and_projection_fallback(- qdrant_url: str,- fake_embedding_endpoint: str,++ qdrant_url: str, fake_embedding_endpoint: str+) -> None:+ del fake_embedding_endpoint+ collection: Final = f"cache_{uuid4().hex}"+ facade: Final = qdrant_facade(qdrant_url, collection)+ handle: Final = _native._CacheTestHandle.qdrant_semantic(+ qdrant_url,+ collection_name=collection,+ similarity_threshold=0.99,+ vector_size=8,+ )+ handle._bind_facade(facade)+ facade.cache.qdrant_api_key = "rotated"+ assert _native._CacheTestResolver(SimpleNamespace(cache=facade)).resolve().kind == "python_callback"+ facade.cache.similarity_threshold = 0.5+ assert _native._CacheTestResolver(SimpleNamespace(cache=facade)).resolve().kind == "python_callback"+ unsupported: Final = qdrant_facade(qdrant_url, f"cache_{uuid4().hex}")+ unsupported.cache.embedding_max_input_tokens = 100+ with pytest.raises(TypeError, match="requires Python"):+ handle._bind_facade(unsupported)+ unsupported.cache.embedding_max_input_tokens = None+ unsupported.cache.qdrant_api_base = "http://127.0.0.1:7777"+ with pytest.raises(TypeError, match="gRPC"):+ handle._bind_facade(unsupported)- from litellm.caching.qdrant_semantic_cache import QdrantSemanticCache-- class CustomQdrantSemanticCache(QdrantSemanticCache):- pass-- subclass_facade: Final = qdrant_facade(qdrant_url, f"cache_{uuid4().hex}")- subclass_facade.cache = CustomQdrantSemanticCache(- qdrant_api_base=qdrant_url,- collection_name=subclass_facade.cache.collection_name,- similarity_threshold=0.99,- embedding_model="text-embedding-3-small",- vector_size=8,- )- with pytest.raises(TypeError):- handle._bind_facade(subclass_facade)