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 remote-tracking branch 'origin/main' into litellm_native_redis_semantic_cache
Yujong Leec31fa2ae7a38
diff --cc litellm-rust/Cargo.lockindex 29e661dea9c,c02f460f22e..66270501312--- a/litellm-rust/Cargo.lock+++ b/litellm-rust/Cargo.lock@@@ -2848,8 -2958,9 +2973,10 @@@ dependencies ="litellm-cache-gcs","litellm-cache-memory","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",diff --cc litellm-rust/Cargo.tomlindex 3e28c11347b,be86240ac46..4e370c13766--- a/litellm-rust/Cargo.toml+++ b/litellm-rust/Cargo.toml@@@ -33,9 -33,9 +33,10 @@@ 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-token-counter = { path = "crates/token-counter" }litellm-token-counter-fast = { path = "crates/token-counter-fast" }diff --cc litellm-rust/crates/cache-redis-semantic/src/cache.rsindex 4181ce719e3,00000000000..e0ac31f3630mode 100644,000000..100644--- a/litellm-rust/crates/cache-redis-semantic/src/cache.rs+++ b/litellm-rust/crates/cache-redis-semantic/src/cache.rs@@@ -1,615 -1,0 +1,618 @@@+use std::{+ future::Future,+ sync::{Arc, OnceLock},+ time::{Duration, SystemTime, UNIX_EPOCH},+};++use litellm_cache::{+ BaseCache, CacheCodec, CacheConnectionResult, CacheConnectionStatus, Error,+ SemanticCacheContext,+};- use litellm_cache_redis::connection::{ConnectionRef, Connections, ttl_seconds};++use litellm_cache_redis::{++ RedisTopology,++ connection::{ConnectionRef, Connections},++};+use litellm_cache_response::{CacheEntry, ResponseCacheCodec};+use serde_json::Value;+use sha2::{Digest, Sha256};++use crate::prompt::prompt_from_context;+- const REDIS_TIMEOUT: Duration = Duration::from_secs(5);- const REDIS_POOL_SIZE: u32 = 16;+const CACHE_KEY_FIELD: &str = "litellm_cache_key";+const VECTOR_FIELD: &str = "prompt_vector";++pub trait Embedder: Send + Sync + 'static {- fn embed(- &self,- prompt: &str,- metadata: &serde_json::Map<String, Value>,- ) -> Result<Vec<f32>, Error>;++ fn embed(&self, prompt: &str, metadata: Option<&Value>) -> Result<Vec<f32>, Error>;++ fn async_embed(+ &self,+ prompt: &str,- metadata: &serde_json::Map<String, Value>,++ metadata: Option<&Value>,+ ) -> impl Future<Output = Result<Vec<f32>, Error>> + Send;+}++#[derive(Clone, Debug)]+pub struct RedisSemanticConfig {+ pub index_name: String,+ pub similarity_threshold: f32,+}++struct Inner {+ index_name: String,+ distance_threshold: f64,+ resolved_index: OnceLock<String>,+ codec: ResponseCacheCodec,+ clock: fn() -> f64,+}++impl Inner {+ fn new(config: RedisSemanticConfig) -> Self {+ Self {+ index_name: config.index_name,+ distance_threshold: 1.0 - f64::from(config.similarity_threshold),+ resolved_index: OnceLock::new(),+ codec: ResponseCacheCodec,+ clock: timestamp,+ }+ }++ fn ensure_index(+ &self,+ connection: &mut ConnectionRef<'_>,+ dims: usize,+ ) -> Result<String, Error> {+ if let Some(name) = self.resolved_index.get() {+ return Ok(name.clone());+ }+ let name = match index_compatible(connection, &self.index_name, dims)? {+ Some(true) => self.index_name.clone(),+ Some(false) => self.isolated_index(connection, dims)?,+ None => match create_index(connection, &self.index_name, dims) {+ Ok(()) => self.index_name.clone(),+ Err(_) => match index_compatible(connection, &self.index_name, dims)? {+ Some(true) => self.index_name.clone(),+ Some(false) => self.isolated_index(connection, dims)?,+ None => return Err(Error::Unavailable),+ },+ },+ };+ let _ = self.resolved_index.set(name.clone());+ Ok(name)+ }++ fn isolated_index(+ &self,+ connection: &mut ConnectionRef<'_>,+ dims: usize,+ ) -> Result<String, Error> {+ let name = format!("{}_isolated", self.index_name);+ match index_compatible(connection, &name, dims)? {+ Some(true) => Ok(name),+ Some(false) => {+ redis::cmd("FT.DROPINDEX")+ .arg(&name)+ .query::<()>(connection)+ .map_err(|_| Error::Unavailable)?;+ create_index(connection, &name, dims)?;+ Ok(name)+ }+ None => {+ create_index(connection, &name, dims)?;+ Ok(name)+ }+ }+ }++ fn store(+ &self,+ connection: &mut ConnectionRef<'_>,+ tag: &str,+ value: &CacheEntry,+ prompt: &str,+ vector: &[f32],+ ttl: Option<Duration>,+ ) -> Result<(), Error> {+ let index = self.ensure_index(connection, vector.len())?;+ let entry_id = entry_id(prompt, tag);+ let hash_key = format!("{index}:{entry_id}");+ let response = self.codec.encode(value)?;+ redis::cmd("HSET")+ .arg(&hash_key)+ .arg("entry_id")+ .arg(&entry_id)+ .arg("prompt")+ .arg(prompt)+ .arg("response")+ .arg(response)+ .arg(VECTOR_FIELD)+ .arg(vector_buffer(vector))+ .arg("inserted_at")+ .arg(format!("{}", (self.clock)()))+ .arg("updated_at")+ .arg(format!("{}", (self.clock)()))+ .arg(CACHE_KEY_FIELD)+ .arg(tag)+ .query::<()>(connection)+ .map_err(|_| Error::Unavailable)?;+ if let Some(ttl) = ttl {+ redis::cmd("EXPIRE")+ .arg(&hash_key)+ .arg(ttl_seconds(ttl))+ .query::<()>(connection)+ .map_err(|_| Error::Unavailable)?;+ }+ Ok(())+ }++ fn lookup(+ &self,+ connection: &mut ConnectionRef<'_>,+ tag: &str,+ vector: &[f32],+ ) -> Result<Option<CacheEntry>, Error> {+ let index = self.ensure_index(connection, vector.len())?;+ let query = format!(+ "(@{CACHE_KEY_FIELD}:{{{}}})=>[KNN 1 @{VECTOR_FIELD} $vector AS vector_distance]",+ escape_tag(tag)+ );+ let result = redis::cmd("FT.SEARCH")+ .arg(&index)+ .arg(query)+ .arg("RETURN")+ .arg(8)+ .arg("entry_id")+ .arg("prompt")+ .arg("response")+ .arg("inserted_at")+ .arg("updated_at")+ .arg("metadata")+ .arg(CACHE_KEY_FIELD)+ .arg("vector_distance")+ .arg("SORTBY")+ .arg("vector_distance")+ .arg("ASC")+ .arg("DIALECT")+ .arg(2)+ .arg("LIMIT")+ .arg(0)+ .arg(1)+ .arg("PARAMS")+ .arg(2)+ .arg("vector")+ .arg(vector_buffer(vector))+ .query::<redis::Value>(connection)+ .map_err(|_| Error::Unavailable)?;+ let Some(fields) = first_document(&result) else {+ return Ok(None);+ };+ if string_field(fields, CACHE_KEY_FIELD).as_deref() != Some(tag) {+ return Ok(None);+ }+ if number_field(fields, "vector_distance")+ .is_none_or(|distance| distance > self.distance_threshold)+ {+ return Ok(None);+ }+ let Some(response) = bytes_field(fields, "response") else {+ return Ok(None);+ };+ self.codec.decode(&response).map(Some)+ }+}++pub struct RedisSemanticCache<E: Embedder, C = redis::Connection> {+ connections: Arc<Connections<C>>,+ embedder: E,+ inner: Arc<Inner>,+}++impl<E: Embedder> RedisSemanticCache<E> {+ pub fn new(url: &str, embedder: E, config: RedisSemanticConfig) -> Result<Self, Error> {+ Ok(Self {- connections: Arc::new(Connections::pooled(url, REDIS_TIMEOUT, REDIS_POOL_SIZE)?),++ connections: Arc::new(Connections::open(url, &RedisTopology::Standalone)?),+ embedder,+ inner: Arc::new(Inner::new(config)),+ })+ }+}++impl<E: Embedder, C: redis::ConnectionLike + Send + 'static> RedisSemanticCache<E, C> {+ pub fn with_connection(connection: C, embedder: E, config: RedisSemanticConfig) -> Self {+ Self {+ connections: Arc::new(Connections::fixed(connection)),+ embedder,+ inner: Arc::new(Inner::new(config)),+ }+ }++ pub fn with_clock(self, clock: fn() -> f64) -> Self {+ Self {+ inner: Arc::new(Inner {+ index_name: self.inner.index_name.clone(),+ distance_threshold: self.inner.distance_threshold,+ resolved_index: OnceLock::new(),+ codec: self.inner.codec,+ clock,+ }),+ ..self+ }+ }++ pub fn embedder(&self) -> &E {+ &self.embedder+ }++ pub fn index_name(&self) -> &str {+ &self.inner.index_name+ }++ pub fn similarity_threshold(&self) -> f32 {+ (1.0 - self.inner.distance_threshold) as f32+ }++ fn tag<'a>(key: &'a str, context: &'a SemanticCacheContext) -> &'a str {+ context.scope.as_deref().unwrap_or(key)+ }+}++impl<E: Embedder, C: redis::ConnectionLike + Send + 'static> BaseCache+ for RedisSemanticCache<E, C>+{+ type Value = CacheEntry;+ type Context = SemanticCacheContext;++ fn get_ttl(&self, context: &Self::Context) -> Option<Duration> {+ context.ttl+ }++ fn set_cache(+ &self,+ key: &str,+ value: Self::Value,+ context: &Self::Context,+ ) -> Result<(), Error> {+ let Some(prompt) = prompt_from_context(context) else {+ return Ok(());+ };- let vector = self.embedder.embed(&prompt, &context.metadata)?;++ let vector = self.embedder.embed(&prompt, context.metadata.as_ref())?;+ let tag = Self::tag(key, context).to_string();+ self.connections.execute(|connection| {+ self.inner+ .store(connection, &tag, &value, &prompt, &vector, context.ttl)+ })+ }++ fn get_cache(&self, key: &str, context: &Self::Context) -> Result<Option<Self::Value>, Error> {+ let Some(prompt) = prompt_from_context(context) else {+ return Ok(None);+ };- let vector = self.embedder.embed(&prompt, &context.metadata)?;++ let vector = self.embedder.embed(&prompt, context.metadata.as_ref())?;+ let tag = Self::tag(key, context).to_string();+ self.connections+ .execute(|connection| self.inner.lookup(connection, &tag, &vector))+ }++ async fn async_set_cache(+ &self,+ key: &str,+ value: Self::Value,+ context: Self::Context,+ ) -> Result<(), Error> {+ let Some(prompt) = prompt_from_context(&context) else {+ return Ok(());+ };+ let vector = self+ .embedder- .async_embed(&prompt, &context.metadata)++ .async_embed(&prompt, context.metadata.as_ref())+ .await?;+ let tag = Self::tag(key, &context).to_string();+ let inner = Arc::clone(&self.inner);+ Connections::run_blocking(Arc::clone(&self.connections), move |connection| {+ inner.store(connection, &tag, &value, &prompt, &vector, context.ttl)+ })+ .await+ }++ async fn async_get_cache(+ &self,+ key: &str,+ context: &Self::Context,+ ) -> Result<Option<Self::Value>, Error> {+ let Some(prompt) = prompt_from_context(context) else {+ return Ok(None);+ };+ let vector = self+ .embedder- .async_embed(&prompt, &context.metadata)++ .async_embed(&prompt, context.metadata.as_ref())+ .await?;+ let tag = Self::tag(key, context).to_string();+ let inner = Arc::clone(&self.inner);+ Connections::run_blocking(Arc::clone(&self.connections), move |connection| {+ inner.lookup(connection, &tag, &vector)+ })+ .await+ }++ async fn disconnect(&self) -> Result<(), Error> {+ Ok(())+ }++ async fn test_connection(&self) -> Result<CacheConnectionResult, Error> {+ match Connections::run_blocking(Arc::clone(&self.connections), |connection| {+ Ok(match redis::cmd("PING").query::<String>(connection) {+ Ok(_) => CacheConnectionResult {+ status: CacheConnectionStatus::Success,+ message: "Redis cache connection test successful".into(),+ error: None,+ },+ Err(error) => CacheConnectionResult {+ status: CacheConnectionStatus::Failed,+ message: format!("Redis connection failed: {error}"),+ error: Some(error.to_string()),+ },+ })+ })+ .await+ {+ Ok(result) => Ok(result),+ Err(error) => Ok(CacheConnectionResult {+ status: CacheConnectionStatus::Failed,+ message: format!("Redis connection failed: {error}"),+ error: Some(error.to_string()),+ }),+ }+ }+}++fn timestamp() -> f64 {+ SystemTime::now()+ .duration_since(UNIX_EPOCH)+ .map(|duration| duration.as_secs_f64())+ .unwrap_or_default()+}++fn entry_id(prompt: &str, tag: &str) -> String {+ let mut digest = Sha256::new();+ digest.update(prompt.as_bytes());+ digest.update(CACHE_KEY_FIELD.as_bytes());+ digest.update(tag.as_bytes());+ format!("{:x}", digest.finalize())+}++fn vector_buffer(vector: &[f32]) -> Vec<u8> {+ vector+ .iter()+ .flat_map(|component| component.to_le_bytes())+ .collect()+}++fn escape_tag(value: &str) -> String {+ value+ .chars()+ .flat_map(|ch| {+ if matches!(+ ch,+ ',' | '.'+ | '<'+ | '>'+ | '{'+ | '}'+ | '['+ | ']'+ | '\\'+ | '"'+ | '\''+ | ':'+ | ';'+ | '!'+ | '@'+ | '#'+ | '$'+ | '%'+ | '^'+ | '&'+ | '*'+ | '('+ | ')'+ | '-'+ | '+'+ | '='+ | '~'+ | '|'+ | '/'+ | ' '+ | '?'+ ) {+ vec!['\\', ch]+ } else {+ vec![ch]+ }+ })+ .collect()+}++fn create_index(connection: &mut ConnectionRef<'_>, name: &str, dims: usize) -> Result<(), Error> {+ redis::cmd("FT.CREATE")+ .arg(name)+ .arg("ON")+ .arg("HASH")+ .arg("PREFIX")+ .arg(1)+ .arg(name)+ .arg("SCORE")+ .arg(1.0)+ .arg("SCHEMA")+ .arg("prompt")+ .arg("TEXT")+ .arg("WEIGHT")+ .arg(1)+ .arg("response")+ .arg("TEXT")+ .arg("WEIGHT")+ .arg(1)+ .arg("inserted_at")+ .arg("NUMERIC")+ .arg("updated_at")+ .arg("NUMERIC")+ .arg(VECTOR_FIELD)+ .arg("VECTOR")+ .arg("FLAT")+ .arg(6)+ .arg("TYPE")+ .arg("FLOAT32")+ .arg("DIM")+ .arg(dims)+ .arg("DISTANCE_METRIC")+ .arg("COSINE")+ .arg(CACHE_KEY_FIELD)+ .arg("TAG")+ .arg("SEPARATOR")+ .arg(",")+ .query::<()>(connection)+ .map_err(|_| Error::Unavailable)+}++fn index_compatible(+ connection: &mut ConnectionRef<'_>,+ name: &str,+ dims: usize,+) -> Result<Option<bool>, Error> {+ let info = match redis::cmd("FT.INFO")+ .arg(name)+ .query::<redis::Value>(connection)+ {+ Ok(info) => info,+ Err(error) if unknown_index(&error) => return Ok(None),+ Err(_) => return Err(Error::Unavailable),+ };+ Ok(Some(schema_compatible(&info, dims)))+}++fn unknown_index(error: &redis::RedisError) -> bool {+ let message = error.to_string().to_lowercase();+ message.contains("unknown") && message.contains("index")+}++fn schema_compatible(info: &redis::Value, dims: usize) -> bool {+ let redis::Value::Array(entries) = info else {+ return false;+ };+ let attributes = entries+ .as_chunks::<2>()+ .0+ .iter()+ .find(|pair| string_value(&pair[0]).as_deref() == Some("attributes"))+ .map(|pair| &pair[1]);+ let Some(redis::Value::Array(attributes)) = attributes else {+ return false;+ };+ let fields = attributes+ .iter()+ .map(|attribute| {+ let redis::Value::Array(attribute) = attribute else {+ return (None, None, None, None, None);+ };+ let mut name = None;+ let mut field_type = None;+ let mut dim = None;+ let mut data_type = None;+ let mut distance_metric = None;+ for pair in attribute.as_chunks::<2>().0 {+ match string_value(&pair[0]).as_deref() {+ Some("identifier") => name = string_value(&pair[1]),+ Some("type") => field_type = string_value(&pair[1]),+ Some("dim") => dim = number_value(&pair[1]),+ Some("data_type") => data_type = string_value(&pair[1]),+ Some("distance_metric") => distance_metric = string_value(&pair[1]),+ _ => {}+ }+ }+ (name, field_type, dim, data_type, distance_metric)+ })+ .collect::<Vec<_>>();+ let has_field = |name: &str, field_type: &str| {+ fields+ .iter()+ .any(|(n, t, ..)| n.as_deref() == Some(name) && t.as_deref() == Some(field_type))+ };+ has_field("prompt", "TEXT")+ && has_field("response", "TEXT")+ && has_field("inserted_at", "NUMERIC")+ && has_field("updated_at", "NUMERIC")+ && has_field(CACHE_KEY_FIELD, "TAG")+ && fields.iter().any(|(n, t, d, data, metric)| {+ n.as_deref() == Some(VECTOR_FIELD)+ && t.as_deref() == Some("VECTOR")+ && *d == Some(dims as f64)+ && data+ .as_deref()+ .is_some_and(|data| data.eq_ignore_ascii_case("float32"))+ && metric+ .as_deref()+ .is_some_and(|metric| metric.eq_ignore_ascii_case("cosine"))+ })+}++fn string_value(value: &redis::Value) -> Option<String> {+ match value {+ redis::Value::BulkString(bytes) => String::from_utf8(bytes.clone()).ok(),+ redis::Value::SimpleString(text) => Some(text.clone()),+ redis::Value::VerbatimString { text, .. } => Some(text.clone()),+ _ => None,+ }+}++fn number_value(value: &redis::Value) -> Option<f64> {+ match value {+ redis::Value::Int(number) => Some(*number as f64),+ redis::Value::Double(number) => Some(*number),+ _ => string_value(value).and_then(|text| text.parse().ok()),+ }+}++fn first_document(result: &redis::Value) -> Option<&[redis::Value]> {+ let redis::Value::Array(items) = result else {+ return None;+ };+ let [count, _document_id, fields, ..] = items.as_slice() else {+ return None;+ };+ if !matches!(count, redis::Value::Int(count) if *count > 0) {+ return None;+ }+ match fields {+ redis::Value::Array(fields) => Some(fields.as_slice()),+ _ => None,+ }+}++fn field_value<'a>(fields: &'a [redis::Value], name: &str) -> Option<&'a redis::Value> {+ fields+ .as_chunks::<2>()+ .0+ .iter()+ .find(|pair| string_value(&pair[0]).as_deref() == Some(name))+ .map(|pair| &pair[1])+}++fn string_field(fields: &[redis::Value], name: &str) -> Option<String> {+ field_value(fields, name).and_then(string_value)+}++fn number_field(fields: &[redis::Value], name: &str) -> Option<f64> {+ field_value(fields, name).and_then(number_value)+}++fn bytes_field(fields: &[redis::Value], name: &str) -> Option<Vec<u8>> {+ match field_value(fields, name)? {+ redis::Value::BulkString(bytes) => Some(bytes.clone()),+ redis::Value::SimpleString(text) => Some(text.clone().into_bytes()),+ _ => None,+ }+}++++fn ttl_seconds(ttl: Duration) -> u64 {++ ttl.as_secs()++ .saturating_add(u64::from(ttl.subsec_nanos() > 0))++ .max(1)++}diff --cc litellm-rust/crates/cache-redis-semantic/src/prompt.rsindex fc99898d847,00000000000..b9c38e98d77mode 100644,000000..100644--- a/litellm-rust/crates/cache-redis-semantic/src/prompt.rs+++ b/litellm-rust/crates/cache-redis-semantic/src/prompt.rs@@@ -1,95 -1,0 +1,97 @@@+use litellm_cache::SemanticCacheContext;+use serde_json::Value;++pub fn prompt_from_context(context: &SemanticCacheContext) -> Option<String> {- if !context.messages.is_empty() {- return Some(messages_text(&context.messages));++ if let Some(messages) = context.messages.as_ref().and_then(Value::as_array)++ && !messages.is_empty()++ {++ return Some(messages_text(messages));+ }+ let input = context.input.as_ref()?;+ let mut parts = Vec::new();+ collect_input_text(input, &mut parts);+ let prompt = parts.join("\n").trim().to_string();+ (!prompt.is_empty()).then_some(prompt)+}++fn messages_text(messages: &[Value]) -> String {+ let mut text = String::new();+ for message in messages {+ let Some(message) = message.as_object() else {+ continue;+ };+ match message.get("content") {+ Some(Value::String(content)) => text.push_str(content),+ Some(Value::Array(parts)) => {+ for part in parts {+ if let Some(text_content) = part.get("text").and_then(Value::as_str) {+ text.push_str(text_content);+ }+ }+ }+ _ => {}+ }+ text.push_str(&search_results_text(message.get("search_results")));+ }+ text+}++fn search_results_text(search_results: Option<&Value>) -> String {+ let Some(Value::Array(results)) = search_results else {+ return String::new();+ };+ let mut text = String::new();+ for result in results {+ let Some(result) = result.as_object() else {+ continue;+ };+ for key in ["source", "title"] {+ if let Some(value) = result.get(key).and_then(Value::as_str) {+ text.push_str(value);+ }+ }+ if let Some(Value::Array(content)) = result.get("content") {+ for block in content {+ if let Some(value) = block.get("text").and_then(Value::as_str) {+ text.push_str(value);+ }+ }+ }+ if let Some(citations) = result.get("citations") {+ text.push_str(&citations.to_string());+ }+ }+ text+}++fn collect_input_text(value: &Value, parts: &mut Vec<String>) {+ match value {+ Value::String(text) => {+ let trimmed = text.trim();+ if !trimmed.is_empty() {+ parts.push(trimmed.to_string());+ }+ }+ Value::Array(items) => {+ for item in items {+ collect_input_text(item, parts);+ }+ }+ Value::Object(map) => {+ if let Some(content) = map.get("content").filter(|content| !content.is_null()) {+ collect_input_text(content, parts);+ return;+ }+ for key in ["text", "output", "input_text", "output_text"] {+ if let Some(Value::String(text)) = map.get(key) {+ let trimmed = text.trim();+ if !trimmed.is_empty() {+ parts.push(trimmed.to_string());+ return;+ }+ }+ }+ }+ _ => {}+ }+}diff --cc litellm-rust/crates/cache-redis-semantic/tests/cache.rsindex fc37cf9f97f,00000000000..233b87ec52fmode 100644,000000..100644--- a/litellm-rust/crates/cache-redis-semantic/tests/cache.rs+++ b/litellm-rust/crates/cache-redis-semantic/tests/cache.rs@@@ -1,1007 -1,0 +1,1003 @@@+use std::{+ collections::HashMap,+ sync::{Arc, Mutex},+ time::Duration,+};++use litellm_cache::{BaseCache, CacheCodec, Error, SemanticCacheContext};+use litellm_cache_redis_semantic::{Embedder, RedisSemanticCache, RedisSemanticConfig};+use litellm_cache_response::{CacheEntry, ResponseCacheCodec};+use redis_test::{MockCmd, MockRedisConnection};+use serde_json::{Value, json};+use sha2::{Digest, Sha256};++const INDEX: &str = "litellm_semantic_cache_index";++struct FakeEmbedder {+ vectors: HashMap<String, Vec<f32>>,+ calls: Arc<Mutex<Vec<String>>>,+}++impl FakeEmbedder {+ fn new(vectors: &[(&str, &[f32])]) -> (Self, Arc<Mutex<Vec<String>>>) {+ let calls = Arc::new(Mutex::new(Vec::new()));+ (+ Self {+ vectors: vectors+ .iter()+ .map(|(prompt, vector)| (prompt.to_string(), vector.to_vec()))+ .collect(),+ calls: Arc::clone(&calls),+ },+ calls,+ )+ }+}++impl Embedder for FakeEmbedder {- fn embed(&self, prompt: &str, _: &serde_json::Map<String, Value>) -> Result<Vec<f32>, Error> {++ fn embed(&self, prompt: &str, _: Option<&Value>) -> Result<Vec<f32>, Error> {+ self.calls.lock().unwrap().push(prompt.to_string());++ Ok(self+ .vectors+ .get(prompt)+ .cloned()+ .unwrap_or_else(|| vec![0.1, 0.2, 0.3]))+ }+- async fn async_embed(- &self,- prompt: &str,- metadata: &serde_json::Map<String, Value>,- ) -> Result<Vec<f32>, Error> {++ async fn async_embed(&self, prompt: &str, metadata: Option<&Value>) -> Result<Vec<f32>, Error> {+ self.embed(prompt, metadata)+ }+}++fn config() -> RedisSemanticConfig {+ RedisSemanticConfig {+ index_name: INDEX.into(),+ similarity_threshold: 0.9,+ }+}++fn messages_context(messages: Vec<Value>) -> SemanticCacheContext {+ SemanticCacheContext {- messages,++ messages: Some(Value::Array(messages)),+ ..Default::default()+ }+}++fn entry() -> CacheEntry {+ CacheEntry {+ timestamp: Some(1.0),+ response: json!({"answer": "yes"}),+ }+}++fn encoded(entry: &CacheEntry) -> Vec<u8> {+ ResponseCacheCodec.encode(entry).unwrap()+}++fn vector_bytes(vector: &[f32]) -> Vec<u8> {+ vector+ .iter()+ .flat_map(|component| component.to_le_bytes())+ .collect()+}++fn entry_id(prompt: &str, tag: &str) -> String {+ let mut digest = Sha256::new();+ digest.update(prompt.as_bytes());+ digest.update(b"litellm_cache_key");+ digest.update(tag.as_bytes());+ format!("{:x}", digest.finalize())+}++fn s(value: &str) -> redis::Value {+ redis::Value::BulkString(value.as_bytes().to_vec())+}++fn unknown_index_error() -> redis::RedisError {+ redis::RedisError::from((redis::ErrorKind::Extension, "Unknown index name"))+}++fn attribute(name: &str, field_type: &str, extra: Vec<redis::Value>) -> redis::Value {+ let mut parts = vec![+ s("identifier"),+ s(name),+ s("attribute"),+ s(name),+ s("type"),+ s(field_type),+ ];+ parts.extend(extra);+ redis::Value::Array(parts)+}++fn index_info(attributes: Vec<redis::Value>) -> redis::Value {+ redis::Value::Array(vec![+ s("index_name"),+ s(INDEX),+ s("attributes"),+ redis::Value::Array(attributes),+ ])+}++fn vector_attribute_with(dims: i64, data_type: &str, distance_metric: &str) -> redis::Value {+ attribute(+ "prompt_vector",+ "VECTOR",+ vec![+ s("algorithm"),+ s("FLAT"),+ s("data_type"),+ s(data_type),+ s("dim"),+ redis::Value::Int(dims),+ s("distance_metric"),+ s(distance_metric),+ ],+ )+}++fn vector_attribute(dims: i64) -> redis::Value {+ vector_attribute_with(dims, "FLOAT32", "COSINE")+}++fn info_with_vector(vector: redis::Value) -> redis::Value {+ index_info(vec![+ attribute("prompt", "TEXT", vec![]),+ attribute("response", "TEXT", vec![]),+ attribute("inserted_at", "NUMERIC", vec![]),+ attribute("updated_at", "NUMERIC", vec![]),+ vector,+ attribute("litellm_cache_key", "TAG", vec![]),+ ])+}++fn compatible_info(dims: i64) -> redis::Value {+ info_with_vector(vector_attribute(dims))+}++fn unscoped_info(dims: i64) -> redis::Value {+ index_info(vec![+ attribute("prompt", "TEXT", vec![]),+ attribute("response", "TEXT", vec![]),+ attribute("inserted_at", "NUMERIC", vec![]),+ attribute("updated_at", "NUMERIC", vec![]),+ vector_attribute(dims),+ ])+}++fn create_index_command(name: &str, dims: usize) -> redis::Cmd {+ let mut command = redis::cmd("FT.CREATE");+ command+ .arg(name)+ .arg("ON")+ .arg("HASH")+ .arg("PREFIX")+ .arg(1)+ .arg(name)+ .arg("SCORE")+ .arg(1.0)+ .arg("SCHEMA")+ .arg("prompt")+ .arg("TEXT")+ .arg("WEIGHT")+ .arg(1)+ .arg("response")+ .arg("TEXT")+ .arg("WEIGHT")+ .arg(1)+ .arg("inserted_at")+ .arg("NUMERIC")+ .arg("updated_at")+ .arg("NUMERIC")+ .arg("prompt_vector")+ .arg("VECTOR")+ .arg("FLAT")+ .arg(6)+ .arg("TYPE")+ .arg("FLOAT32")+ .arg("DIM")+ .arg(dims)+ .arg("DISTANCE_METRIC")+ .arg("COSINE")+ .arg("litellm_cache_key")+ .arg("TAG")+ .arg("SEPARATOR")+ .arg(",");+ command+}++fn search_command(index: &str, tag: &str, vector: &[f32]) -> redis::Cmd {+ let mut command = redis::cmd("FT.SEARCH");+ command+ .arg(index)+ .arg(format!(+ "(@litellm_cache_key:{{{tag}}})=>[KNN 1 @prompt_vector $vector AS vector_distance]"+ ))+ .arg("RETURN")+ .arg(8)+ .arg("entry_id")+ .arg("prompt")+ .arg("response")+ .arg("inserted_at")+ .arg("updated_at")+ .arg("metadata")+ .arg("litellm_cache_key")+ .arg("vector_distance")+ .arg("SORTBY")+ .arg("vector_distance")+ .arg("ASC")+ .arg("DIALECT")+ .arg(2)+ .arg("LIMIT")+ .arg(0)+ .arg(1)+ .arg("PARAMS")+ .arg(2)+ .arg("vector")+ .arg(vector_bytes(vector));+ command+}++fn hit_fields(tag: &str, distance: &str, response: Vec<u8>) -> redis::Value {+ redis::Value::Array(vec![+ s("entry_id"),+ s("stored-id"),+ s("prompt"),+ s("hello prompt"),+ s("response"),+ redis::Value::BulkString(response),+ s("inserted_at"),+ s("1700000000.5"),+ s("updated_at"),+ s("1700000000.5"),+ s("litellm_cache_key"),+ s(tag),+ s("vector_distance"),+ s(distance),+ ])+}++fn search_result(fields: redis::Value) -> redis::Value {+ redis::Value::Array(vec![+ redis::Value::Int(1),+ s("litellm_semantic_cache_index:stored-id"),+ fields,+ ])+}++fn empty_result() -> redis::Value {+ redis::Value::Array(vec![redis::Value::Int(0)])+}++#[test]+fn store_creates_index_and_writes_hash_with_expire() {+ let vector = vec![0.1f32, 0.2, 0.3];+ let prompt = "hello prompt";+ let tag = "key1";+ let hash_key = format!("{INDEX}:{}", entry_id(prompt, tag));+ let value = entry();+ let connection = MockRedisConnection::new([+ MockCmd::new(+ redis::cmd("FT.INFO").arg(INDEX),+ Err::<redis::Value, _>(unknown_index_error()),+ ),+ MockCmd::new(create_index_command(INDEX, 3), Ok("OK")),+ MockCmd::new(+ redis::cmd("HSET")+ .arg(&hash_key)+ .arg("entry_id")+ .arg(entry_id(prompt, tag))+ .arg("prompt")+ .arg(prompt)+ .arg("response")+ .arg(encoded(&value))+ .arg("prompt_vector")+ .arg(vector_bytes(&vector))+ .arg("inserted_at")+ .arg("1700000000.5")+ .arg("updated_at")+ .arg("1700000000.5")+ .arg("litellm_cache_key")+ .arg(tag),+ Ok(7),+ ),+ MockCmd::new(redis::cmd("EXPIRE").arg(&hash_key).arg(5), Ok(1)),+ ])+ .assert_all_commands_consumed();+ let (embedder, _) = FakeEmbedder::new(&[(prompt, &vector)]);+ let cache = RedisSemanticCache::with_connection(connection, embedder, config())+ .with_clock(|| 1700000000.5);++ let context = SemanticCacheContext {+ ttl: Some(Duration::from_secs(5)),+ ..messages_context(vec![json!({"role": "user", "content": prompt})])+ };+ cache.set_cache(tag, value, &context).unwrap();+}++#[test]+fn store_without_ttl_skips_expire() {+ let prompt = "hello prompt";+ let connection = MockRedisConnection::new([+ MockCmd::new(redis::cmd("FT.INFO").arg(INDEX), Ok(compatible_info(3))),+ MockCmd::new(+ redis::cmd("HSET")+ .arg(format!("{INDEX}:{}", entry_id(prompt, "key1")))+ .arg("entry_id")+ .arg(entry_id(prompt, "key1"))+ .arg("prompt")+ .arg(prompt)+ .arg("response")+ .arg(encoded(&entry()))+ .arg("prompt_vector")+ .arg(vector_bytes(&[0.1f32, 0.2, 0.3]))+ .arg("inserted_at")+ .arg("1700000000.5")+ .arg("updated_at")+ .arg("1700000000.5")+ .arg("litellm_cache_key")+ .arg("key1"),+ Ok(7),+ ),+ ])+ .assert_all_commands_consumed();+ let (embedder, _) = FakeEmbedder::new(&[]);+ let cache = RedisSemanticCache::with_connection(connection, embedder, config())+ .with_clock(|| 1700000000.5);++ cache+ .set_cache(+ "key1",+ entry(),+ &messages_context(vec![json!({"role": "user", "content": prompt})]),+ )+ .unwrap();+}++#[test]+fn lookup_returns_hit_below_distance_threshold() {+ let vector = vec![0.1f32, 0.2, 0.3];+ let value = entry();+ let connection = MockRedisConnection::new([+ MockCmd::new(redis::cmd("FT.INFO").arg(INDEX), Ok(compatible_info(3))),+ MockCmd::new(+ search_command(INDEX, "key1", &vector),+ Ok(search_result(hit_fields("key1", "0.05", encoded(&value)))),+ ),+ ])+ .assert_all_commands_consumed();+ let (embedder, _) = FakeEmbedder::new(&[]);+ let cache = RedisSemanticCache::with_connection(connection, embedder, config());++ let hit = cache+ .get_cache(+ "key1",+ &messages_context(vec![json!({"role": "user", "content": "hello prompt"})]),+ )+ .unwrap();+ assert_eq!(hit, Some(value));+}++#[test]+fn lookup_misses_above_distance_threshold_and_on_tag_mismatch() {+ let vector = vec![0.1f32, 0.2, 0.3];+ let connection = MockRedisConnection::new([+ MockCmd::new(redis::cmd("FT.INFO").arg(INDEX), Ok(compatible_info(3))),+ MockCmd::new(+ search_command(INDEX, "key1", &vector),+ Ok(search_result(hit_fields("key1", "0.5", encoded(&entry())))),+ ),+ MockCmd::new(+ search_command(INDEX, "key1", &vector),+ Ok(search_result(hit_fields(+ "other",+ "0.05",+ encoded(&entry()),+ ))),+ ),+ ])+ .assert_all_commands_consumed();+ let (embedder, _) = FakeEmbedder::new(&[]);+ let cache = RedisSemanticCache::with_connection(connection, embedder, config());+ let context = messages_context(vec![json!({"role": "user", "content": "hello prompt"})]);++ assert_eq!(cache.get_cache("key1", &context).unwrap(), None);+ assert_eq!(cache.get_cache("key1", &context).unwrap(), None);+}++#[test]+fn lookup_returns_invalid_entry_on_malformed_response() {+ let vector = vec![0.1f32, 0.2, 0.3];+ let connection = MockRedisConnection::new([+ MockCmd::new(redis::cmd("FT.INFO").arg(INDEX), Ok(compatible_info(3))),+ MockCmd::new(+ search_command(INDEX, "key1", &vector),+ Ok(search_result(hit_fields(+ "key1",+ "0.05",+ b"not json!".to_vec(),+ ))),+ ),+ ])+ .assert_all_commands_consumed();+ let (embedder, _) = FakeEmbedder::new(&[]);+ let cache = RedisSemanticCache::with_connection(connection, embedder, config());++ assert_eq!(+ cache+ .get_cache(+ "key1",+ &messages_context(vec![json!({"role": "user", "content": "hello prompt"})])+ )+ .unwrap_err(),+ Error::InvalidEntry+ );+}++#[test]+fn missing_prompt_is_noop_and_never_embeds() {+ let connection = MockRedisConnection::new(Vec::<MockCmd>::new()).assert_all_commands_consumed();+ let (embedder, calls) = FakeEmbedder::new(&[]);+ let cache = RedisSemanticCache::with_connection(connection, embedder, config());++ let context = SemanticCacheContext::default();+ cache.set_cache("key1", entry(), &context).unwrap();+ assert_eq!(cache.get_cache("key1", &context).unwrap(), None);+ assert!(calls.lock().unwrap().is_empty());+}++#[test]+fn scope_overrides_key_as_filter_tag() {+ let vector = vec![0.1f32, 0.2, 0.3];+ let prompt = "hello prompt";+ let value = entry();+ let connection = MockRedisConnection::new([+ MockCmd::new(redis::cmd("FT.INFO").arg(INDEX), Ok(compatible_info(3))),+ MockCmd::new(+ redis::cmd("HSET")+ .arg(format!("{INDEX}:{}", entry_id(prompt, "scope-a")))+ .arg("entry_id")+ .arg(entry_id(prompt, "scope-a"))+ .arg("prompt")+ .arg(prompt)+ .arg("response")+ .arg(encoded(&value))+ .arg("prompt_vector")+ .arg(vector_bytes(&vector))+ .arg("inserted_at")+ .arg("1700000000.5")+ .arg("updated_at")+ .arg("1700000000.5")+ .arg("litellm_cache_key")+ .arg("scope-a"),+ Ok(7),+ ),+ MockCmd::new(+ search_command(INDEX, "scope\\-a", &vector),+ Ok(search_result(hit_fields(+ "scope-a",+ "0.05",+ encoded(&value),+ ))),+ ),+ ])+ .assert_all_commands_consumed();+ let (embedder, _) = FakeEmbedder::new(&[]);+ let cache = RedisSemanticCache::with_connection(connection, embedder, config())+ .with_clock(|| 1700000000.5);+ let context = SemanticCacheContext {+ scope: Some("scope-a".into()),+ ..messages_context(vec![json!({"role": "user", "content": prompt})])+ };++ cache.set_cache("key1", value.clone(), &context).unwrap();+ assert_eq!(cache.get_cache("key1", &context).unwrap(), Some(value));+}++#[test]+fn incompatible_schema_falls_back_to_isolated_index() {+ let prompt = "hello prompt";+ let tag = "key1";+ let isolated = format!("{INDEX}_isolated");+ let connection = MockRedisConnection::new([+ MockCmd::new(redis::cmd("FT.INFO").arg(INDEX), Ok(unscoped_info(3))),+ MockCmd::new(+ redis::cmd("FT.INFO").arg(&isolated),+ Err::<redis::Value, _>(unknown_index_error()),+ ),+ MockCmd::new(create_index_command(&isolated, 3), Ok("OK")),+ MockCmd::new(+ redis::cmd("HSET")+ .arg(format!("{isolated}:{}", entry_id(prompt, tag)))+ .arg("entry_id")+ .arg(entry_id(prompt, tag))+ .arg("prompt")+ .arg(prompt)+ .arg("response")+ .arg(encoded(&entry()))+ .arg("prompt_vector")+ .arg(vector_bytes(&[0.1f32, 0.2, 0.3]))+ .arg("inserted_at")+ .arg("1700000000.5")+ .arg("updated_at")+ .arg("1700000000.5")+ .arg("litellm_cache_key")+ .arg(tag),+ Ok(7),+ ),+ ])+ .assert_all_commands_consumed();+ let (embedder, _) = FakeEmbedder::new(&[]);+ let cache = RedisSemanticCache::with_connection(connection, embedder, config())+ .with_clock(|| 1700000000.5);++ cache+ .set_cache(+ tag,+ entry(),+ &messages_context(vec![json!({"role": "user", "content": prompt})]),+ )+ .unwrap();+}++#[test]+fn create_index_race_rechecks_schema_and_stores() {+ let prompt = "hello prompt";+ let tag = "key1";+ let connection = MockRedisConnection::new([+ MockCmd::new(+ redis::cmd("FT.INFO").arg(INDEX),+ Err::<redis::Value, _>(unknown_index_error()),+ ),+ MockCmd::new(+ create_index_command(INDEX, 3),+ Err::<&str, _>(redis::RedisError::from((+ redis::ErrorKind::Extension,+ "Index already exists",+ ))),+ ),+ MockCmd::new(redis::cmd("FT.INFO").arg(INDEX), Ok(compatible_info(3))),+ MockCmd::new(+ redis::cmd("HSET")+ .arg(format!("{INDEX}:{}", entry_id(prompt, tag)))+ .arg("entry_id")+ .arg(entry_id(prompt, tag))+ .arg("prompt")+ .arg(prompt)+ .arg("response")+ .arg(encoded(&entry()))+ .arg("prompt_vector")+ .arg(vector_bytes(&[0.1f32, 0.2, 0.3]))+ .arg("inserted_at")+ .arg("1700000000.5")+ .arg("updated_at")+ .arg("1700000000.5")+ .arg("litellm_cache_key")+ .arg(tag),+ Ok(7),+ ),+ ])+ .assert_all_commands_consumed();+ let (embedder, _) = FakeEmbedder::new(&[]);+ let cache = RedisSemanticCache::with_connection(connection, embedder, config())+ .with_clock(|| 1700000000.5);++ cache+ .set_cache(+ tag,+ entry(),+ &messages_context(vec![json!({"role": "user", "content": prompt})]),+ )+ .unwrap();+}++#[test]+fn wrong_distance_metric_falls_back_to_isolated_index() {+ let prompt = "hello prompt";+ let tag = "key1";+ let isolated = format!("{INDEX}_isolated");+ let connection = MockRedisConnection::new([+ MockCmd::new(+ redis::cmd("FT.INFO").arg(INDEX),+ Ok(info_with_vector(vector_attribute_with(3, "FLOAT32", "L2"))),+ ),+ MockCmd::new(+ redis::cmd("FT.INFO").arg(&isolated),+ Err::<redis::Value, _>(unknown_index_error()),+ ),+ MockCmd::new(create_index_command(&isolated, 3), Ok("OK")),+ MockCmd::new(+ redis::cmd("HSET")+ .arg(format!("{isolated}:{}", entry_id(prompt, tag)))+ .arg("entry_id")+ .arg(entry_id(prompt, tag))+ .arg("prompt")+ .arg(prompt)+ .arg("response")+ .arg(encoded(&entry()))+ .arg("prompt_vector")+ .arg(vector_bytes(&[0.1f32, 0.2, 0.3]))+ .arg("inserted_at")+ .arg("1700000000.5")+ .arg("updated_at")+ .arg("1700000000.5")+ .arg("litellm_cache_key")+ .arg(tag),+ Ok(7),+ ),+ ])+ .assert_all_commands_consumed();+ let (embedder, _) = FakeEmbedder::new(&[]);+ let cache = RedisSemanticCache::with_connection(connection, embedder, config())+ .with_clock(|| 1700000000.5);++ cache+ .set_cache(+ tag,+ entry(),+ &messages_context(vec![json!({"role": "user", "content": prompt})]),+ )+ .unwrap();+}++#[test]+fn tag_special_characters_are_escaped_in_search_filter() {+ let vector = vec![0.1f32, 0.2, 0.3];+ let tag = "a:b, c|d";+ let connection = MockRedisConnection::new([+ MockCmd::new(redis::cmd("FT.INFO").arg(INDEX), Ok(compatible_info(3))),+ MockCmd::new(+ search_command(INDEX, "a\\:b\\,\\ c\\|d", &vector),+ Ok(empty_result()),+ ),+ ])+ .assert_all_commands_consumed();+ let (embedder, _) = FakeEmbedder::new(&[]);+ let cache = RedisSemanticCache::with_connection(connection, embedder, config());++ assert_eq!(+ cache+ .get_cache(+ tag,+ &messages_context(vec![json!({"role": "user", "content": "hello prompt"})])+ )+ .unwrap(),+ None+ );+}++#[test]+fn prompt_extraction_matches_python_message_and_input_shapes() {+ let vector = vec![0.1f32, 0.2, 0.3];+ let lookups = 5;+ let mut commands = vec![MockCmd::new(+ redis::cmd("FT.INFO").arg(INDEX),+ Ok(compatible_info(3)),+ )];+ for _ in 0..lookups {+ commands.push(MockCmd::new(+ search_command(INDEX, "key1", &vector),+ Ok(empty_result()),+ ));+ }+ let connection = MockRedisConnection::new(commands).assert_all_commands_consumed();+ let (embedder, calls) = FakeEmbedder::new(&[]);+ let cache = RedisSemanticCache::with_connection(connection, embedder, config());++ cache+ .get_cache(+ "key1",+ &messages_context(vec![+ json!({"role": "user", "content": [{"type": "text", "text": "first"}, {"type": "text", "text": "second"}]}),+ json!({"role": "assistant", "content": "reply"}),+ ]),+ )+ .unwrap();+ cache+ .get_cache(+ "key1",+ &SemanticCacheContext {+ input: Some(json!(" plain input ")),+ ..Default::default()+ },+ )+ .unwrap();+ cache+ .get_cache(+ "key1",+ &SemanticCacheContext {+ input: Some(+ json!([{"content": [{"type": "input_text", "text": "nested"}]}, "tail"]),+ ),+ ..Default::default()+ },+ )+ .unwrap();+ cache+ .get_cache(+ "key1",+ &SemanticCacheContext {+ input: Some(json!({"output_text": " result text "})),+ ..Default::default()+ },+ )+ .unwrap();+ cache+ .get_cache(+ "key1",+ &messages_context(vec![json!({+ "role": "user",+ "content": "question",+ "search_results": [{"source": "src", "title": "t", "content": [{"text": "found"}], "citations": {"a": 1}}],+ })]),+ )+ .unwrap();++ assert_eq!(+ *calls.lock().unwrap(),+ vec![+ "firstsecondreply",+ "plain input",+ "nested\ntail",+ "result text",+ "questionsrctfound{\"a\":1}",+ ]+ );+}++#[test]+fn ttl_passes_through_context_only() {+ let (embedder, _) = FakeEmbedder::new(&[]);+ let cache = RedisSemanticCache::with_connection(+ MockRedisConnection::new(Vec::<MockCmd>::new()),+ embedder,+ config(),+ );+ assert_eq!(cache.get_ttl(&SemanticCacheContext::default()), None);+ assert_eq!(+ cache.get_ttl(&SemanticCacheContext {+ ttl: Some(Duration::from_secs(9)),+ ..Default::default()+ }),+ Some(Duration::from_secs(9))+ );+}++#[tokio::test]+async fn async_paths_embed_then_run_blocking_redis_work() {+ let vector = vec![0.1f32, 0.2, 0.3];+ let prompt = "hello prompt";+ let tag = "key1";+ let hash_key = format!("{INDEX}:{}", entry_id(prompt, tag));+ let value = entry();+ let connection = MockRedisConnection::new([+ MockCmd::new(redis::cmd("FT.INFO").arg(INDEX), Ok(compatible_info(3))),+ MockCmd::new(+ redis::cmd("HSET")+ .arg(&hash_key)+ .arg("entry_id")+ .arg(entry_id(prompt, tag))+ .arg("prompt")+ .arg(prompt)+ .arg("response")+ .arg(encoded(&value))+ .arg("prompt_vector")+ .arg(vector_bytes(&vector))+ .arg("inserted_at")+ .arg("1700000000.5")+ .arg("updated_at")+ .arg("1700000000.5")+ .arg("litellm_cache_key")+ .arg(tag),+ Ok(7),+ ),+ MockCmd::new(+ search_command(INDEX, tag, &vector),+ Ok(search_result(hit_fields(tag, "0.05", encoded(&value)))),+ ),+ ])+ .assert_all_commands_consumed();+ let (embedder, _) = FakeEmbedder::new(&[]);+ let cache = RedisSemanticCache::with_connection(connection, embedder, config())+ .with_clock(|| 1700000000.5);+ let context = messages_context(vec![json!({"role": "user", "content": prompt})]);++ cache+ .async_set_cache(tag, value.clone(), context.clone())+ .await+ .unwrap();+ assert_eq!(+ cache.async_get_cache(tag, &context).await.unwrap(),+ Some(value)+ );+}++#[test]+fn shared_base_index_across_dimensions_replaces_the_isolated_index() {+ // Pins parity with Python's `_isolated` + overwrite=True flow.+ let prompt = "shared prompt";+ let tag = "key1";+ let isolated = format!("{INDEX}_isolated");+ let value = entry();+ let context = || messages_context(vec![json!({"role": "user", "content": prompt})]);+ let store_hash = |index: &str, vector: &[f32]| {+ MockCmd::new(+ redis::cmd("HSET")+ .arg(format!("{index}:{}", entry_id(prompt, tag)))+ .arg("entry_id")+ .arg(entry_id(prompt, tag))+ .arg("prompt")+ .arg(prompt)+ .arg("response")+ .arg(encoded(&value))+ .arg("prompt_vector")+ .arg(vector_bytes(vector))+ .arg("inserted_at")+ .arg("1700000000.5")+ .arg("updated_at")+ .arg("1700000000.5")+ .arg("litellm_cache_key")+ .arg(tag),+ Ok(7),+ )+ };++ let vector_a = vec![0.1f32; 8];+ let connection_a = MockRedisConnection::new([+ MockCmd::new(+ redis::cmd("FT.INFO").arg(INDEX),+ Err::<redis::Value, _>(unknown_index_error()),+ ),+ MockCmd::new(create_index_command(INDEX, 8), Ok("OK")),+ store_hash(INDEX, &vector_a),+ ])+ .assert_all_commands_consumed();+ let (embedder_a, _) = FakeEmbedder::new(&[(prompt, &vector_a)]);+ let worker_a = RedisSemanticCache::with_connection(connection_a, embedder_a, config())+ .with_clock(|| 1700000000.5);+ worker_a.set_cache(tag, value.clone(), &context()).unwrap();++ let vector_b = vec![0.2f32; 4];+ let connection_b = MockRedisConnection::new([+ MockCmd::new(redis::cmd("FT.INFO").arg(INDEX), Ok(compatible_info(8))),+ MockCmd::new(+ redis::cmd("FT.INFO").arg(&isolated),+ Err::<redis::Value, _>(unknown_index_error()),+ ),+ MockCmd::new(create_index_command(&isolated, 4), Ok("OK")),+ store_hash(&isolated, &vector_b),+ MockCmd::new(+ search_command(&isolated, tag, &vector_b),+ Ok(search_result(hit_fields(tag, "0.0", encoded(&value)))),+ ),+ MockCmd::new(+ search_command(&isolated, tag, &vector_b),+ Err::<redis::Value, _>(redis::RedisError::from((+ redis::ErrorKind::Extension,+ "Vector dimension mismatch",+ ))),+ ),+ ])+ .assert_all_commands_consumed();+ let (embedder_b, _) = FakeEmbedder::new(&[(prompt, &vector_b)]);+ let worker_b = RedisSemanticCache::with_connection(connection_b, embedder_b, config())+ .with_clock(|| 1700000000.5);+ worker_b.set_cache(tag, value.clone(), &context()).unwrap();+ assert_eq!(+ worker_b.get_cache(tag, &context()).unwrap(),+ Some(value.clone())+ );++ let vector_c = vec![0.3f32; 16];+ let connection_c = MockRedisConnection::new([+ MockCmd::new(redis::cmd("FT.INFO").arg(INDEX), Ok(compatible_info(8))),+ MockCmd::new(redis::cmd("FT.INFO").arg(&isolated), Ok(compatible_info(4))),+ MockCmd::new(redis::cmd("FT.DROPINDEX").arg(&isolated), Ok("OK")),+ MockCmd::new(create_index_command(&isolated, 16), Ok("OK")),+ store_hash(&isolated, &vector_c),+ ])+ .assert_all_commands_consumed();+ let (embedder_c, _) = FakeEmbedder::new(&[(prompt, &vector_c)]);+ let worker_c = RedisSemanticCache::with_connection(connection_c, embedder_c, config())+ .with_clock(|| 1700000000.5);+ worker_c.set_cache(tag, value.clone(), &context()).unwrap();++ assert_eq!(+ worker_b.get_cache(tag, &context()).unwrap_err(),+ Error::Unavailable+ );+}++#[test]+fn live_shared_index_is_replaced_across_dimensions() {+ let Ok(url) = std::env::var("LITELLM_REDIS_STACK_URL") else {+ return;+ };+ // Pins parity with Python's `_isolated` + overwrite=True flow.+ let base = format!("rust_semantic_shared_{}", std::process::id());+ let isolated = format!("{base}_isolated");+ let prompt = "shared live prompt";+ let tag = "key1";+ let context = || messages_context(vec![json!({"role": "user", "content": prompt})]);+ let value = entry();+ let worker = |vector: Vec<f32>| {+ let (embedder, _) = FakeEmbedder::new(&[(prompt, vector.as_slice())]);+ RedisSemanticCache::new(+ &url,+ embedder,+ RedisSemanticConfig {+ index_name: base.clone(),+ similarity_threshold: 0.9,+ },+ )+ .unwrap()+ };++ let worker_a = worker(vec![0.1f32; 8]);+ worker_a.set_cache(tag, value.clone(), &context()).unwrap();++ let worker_b = worker(vec![0.2f32; 4]);+ worker_b.set_cache(tag, value.clone(), &context()).unwrap();+ assert_eq!(+ worker_b.get_cache(tag, &context()).unwrap(),+ Some(value.clone())+ );++ let worker_c = worker(vec![0.3f32; 16]);+ worker_c.set_cache(tag, value.clone(), &context()).unwrap();++ assert_eq!(+ worker_b.get_cache(tag, &context()).unwrap_err(),+ Error::Unavailable+ );++ let mut connection = redis::Client::open(url).unwrap().get_connection().unwrap();+ for index in [&base, &isolated] {+ let _: Result<(), _> = redis::cmd("FT.DROPINDEX")+ .arg(index)+ .arg("DD")+ .query(&mut connection);+ }+}++#[test]+fn live_store_lookup_and_ttl_against_redis_stack() {+ let Ok(url) = std::env::var("LITELLM_REDIS_STACK_URL") else {+ return;+ };+ let vector = vec![0.1f32, 0.2, 0.3, 0.4];+ let prompt = "rust semantic cache live prompt";+ let tag = "live-key";+ let index_name = format!("rust_semantic_test_{}", std::process::id());+ let (embedder, _) = FakeEmbedder::new(&[(prompt, &vector)]);+ let cache = RedisSemanticCache::new(+ &url,+ embedder,+ RedisSemanticConfig {+ index_name: index_name.clone(),+ similarity_threshold: 0.9,+ },+ )+ .unwrap();+ let context = SemanticCacheContext {+ ttl: Some(Duration::from_secs(120)),+ ..messages_context(vec![json!({"role": "user", "content": prompt})])+ };+ let value = entry();++ cache.set_cache(tag, value.clone(), &context).unwrap();+ assert_eq!(cache.get_cache(tag, &context).unwrap(), Some(value));+ assert_eq!(cache.get_cache("other-key", &context).unwrap(), None);++ let mut connection = redis::Client::open(url).unwrap().get_connection().unwrap();+ let ttl: i64 = redis::Commands::ttl(+ &mut connection,+ format!("{index_name}:{}", entry_id(prompt, tag)),+ )+ .unwrap();+ assert!(+ ttl > 0,+ "expected stored hash to carry an expiry, got {ttl}"+ );+}diff --cc litellm-rust/crates/cache/tests/caching.rsindex 33171f36f46,9180ee9d0dc..36307ac9b33--- a/litellm-rust/crates/cache/tests/caching.rs+++ b/litellm-rust/crates/cache/tests/caching.rs@@@ -127,24 -126,6 +127,24 @@@ fn associated_context_preserves_backend);}+#[test]+fn semantic_context_with_ttl_preserves_lookup_inputs() {+ let context = SemanticCacheContext {+ input: Some(serde_json::json!("text")),- messages: vec![serde_json::json!({"role": "user", "content": "hi"})],- metadata: serde_json::Map::from_iter([("key".into(), serde_json::json!("value"))]),++ messages: Some(serde_json::json!([{"role": "user", "content": "hi"}])),++ metadata: Some(serde_json::json!({"key": "value"})),+ scope: Some("scope".into()),+ ttl: None,+ };+ let updated = context.with_ttl(Some(Duration::from_secs(30)));+ assert_eq!(updated.ttl(), Some(Duration::from_secs(30)));+ assert_eq!(updated.input, context.input);+ assert_eq!(updated.messages, context.messages);+ assert_eq!(updated.metadata, context.metadata);+ assert_eq!(updated.scope, context.scope);+ assert_eq!(context.with_ttl(None).ttl(), None);+}+#[tokio::test]async fn default_batch_operations_use_async_writes_and_stop_on_failure() {let cache = TestCache {diff --cc litellm-rust/crates/python-bridge/Cargo.tomlindex 0080a972481,d07a9839ebf..bbe727f9345--- a/litellm-rust/crates/python-bridge/Cargo.toml+++ b/litellm-rust/crates/python-bridge/Cargo.toml@@@ -24,12 -24,14 +24,15 @@@ 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-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@@@ -41,8 -43,9 +44,9 @@@ litellm-host-python.workspace = trulitellm-token-counter = { path = "../token-counter", default-features = false }pyo3.workspace = truepyo3-async-runtimes.workspace = true+ redis = { version = "1.7.0", features = ["tls-rustls"] }serde_json.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 3a7ae5d618f,9bc666c4f2d..ef2a03ac9ba--- a/litellm-rust/crates/python-bridge/src/cache/config.rs+++ b/litellm-rust/crates/python-bridge/src/cache/config.rs@@@ -115,13 -99,27 +117,23 @@@ 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 AzureBlobCacheConfig {- pub(super) account_url: String,- pub(super) container: String,-}-pub(super) enum CacheBackendConfig {Memory(MemoryCacheConfig),Redis(Box<RedisCacheConfig>),+ S3(Box<S3CacheConfig>),Gcs(GcsCacheConfig),+ ValkeySemantic(Box<ValkeySemanticCacheConfig>),Disk(DiskCacheConfig),AzureBlob(AzureBlobCacheConfig),+ RedisSemantic(Box<RedisSemanticCacheConfig>),}#[allow(dead_code, reason = "consumed by the cache activation follow-up")]@@@ -212,17 -230,9 +244,15 @@@ impl NativeCacheConfigbackend: CacheBackendConfig::AzureBlob(backend),}))}),- Some(CacheType::RedisSemantic | CacheType::QdrantSemantic) | 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::ValkeySemantic | CacheType::S3 | CacheType::QdrantSemantic) | None => {- Ok(CacheConfigProjection::Unsupported(- UnsupportedCacheConfig::Backend,- ))- }++ Some(CacheType::QdrantSemantic) | None => Ok(CacheConfigProjection::Unsupported(++ UnsupportedCacheConfig::Backend,++ )),}}@@@ -230,12 -240,15 +260,16 @@@let default_ttl = match &self.backend {CacheBackendConfig::Memory(config) => Some(config.default_ttl),CacheBackendConfig::Redis(config) => Some(config.default_ttl),+ CacheBackendConfig::S3(_) => None,+ CacheBackendConfig::ValkeySemantic(_) => Some(Duration::ZERO),CacheBackendConfig::Disk(_)| CacheBackendConfig::AzureBlob(_)- | CacheBackendConfig::Gcs(_) => None,+ | CacheBackendConfig::Gcs(_)+ | CacheBackendConfig::RedisSemantic(_) => None,};- if service.default_ttl() != default_ttl {+ if !matches!(self.backend, CacheBackendConfig::ValkeySemantic(_))+ && service.default_ttl() != default_ttl+ {return Some("facade and native backend default TTLs must match");}match &self.backend {diff --cc litellm-rust/crates/python-bridge/src/cache/embedder.rsindex 99c3de34e05,3de0ceb3b67..10ccf396510--- a/litellm-rust/crates/python-bridge/src/cache/embedder.rs+++ b/litellm-rust/crates/python-bridge/src/cache/embedder.rs@@@ -1,118 -1,63 +1,158 @@@-use std::{future::Future, sync::Arc};+use std::future::Future;use litellm_cache::Error;- use litellm_cache_redis_semantic::Embedder;-use litellm_cache_valkey_semantic::Embedder;use litellm_host_python::to_py;-use pyo3::{PyTraverseError, PyVisit, prelude::*};+use pyo3::{PyTraverseError, PyVisit, prelude::*, types::PyDict};- use serde_json::{Map, Value};+ use serde_json::Value;-#[derive(Clone)]-pub(super) struct PythonEmbedder {- sync_embed: Arc<Py<PyAny>>,- async_embed_callable: Arc<Py<PyAny>>,+tokio::task_local! {+ static PREPARED_EMBEDDING: Result<Vec<f32>, Error>;+}++pub(super) fn with_prepared_embedding<F: Future>(+ vector: Result<Vec<f32>, Error>,+ future: F,+) -> impl Future<Output = F::Output> {+ PREPARED_EMBEDDING.scope(vector, future)+}++pub(super) struct PythonEmbedder(Py<PyAny>);+++impl Clone for PythonEmbedder {++ fn clone(&self) -> Self {++ Python::attach(|py| Self(self.0.clone_ref(py)))++ }+ }+impl PythonEmbedder {+ pub(super) fn new(object: Py<PyAny>) -> Self {+ Self(object)+ }++ pub(super) fn from_backend(backend: &Bound<'_, PyAny>) -> PyResult<Self> {- Ok(Self {- sync_embed: Arc::new(backend.getattr("_get_embedding")?.unbind()),- async_embed_callable: Arc::new(backend.getattr("_get_async_embedding")?.unbind()),- })++ Ok(Self(backend.clone().unbind()))++ }+++ pub(super) fn object(&self) -> &Py<PyAny> {+ &self.0+ }++ pub(super) fn traverse(&self, visit: &PyVisit<'_>) -> Result<(), PyTraverseError> {+ visit.call(&self.0)}+ pub(super) fn async_embed_awaitable<'py>(+ &self,+ py: Python<'py>,+ prompt: &str,+ metadata: &Option<Value>,+ ) -> PyResult<Bound<'py, PyAny>> {+ let metadata = to_py(py, metadata)?;- self.async_embed_callable.bind(py).call1((prompt, metadata))++ self.0++ .bind(py)++ .call_method1("_get_async_embedding", (prompt, metadata))+ }+- pub(super) fn traverse(&self, visit: &PyVisit<'_>) -> Result<(), PyTraverseError> {- visit.call(&*self.sync_embed)?;- visit.call(&*self.async_embed_callable)+ fn metadata_kwargs<'py>(+ py: Python<'py>,- metadata: &Map<String, Value>,++ metadata: Option<&Value>,+ ) -> PyResult<Bound<'py, PyDict>> {+ let kwargs = PyDict::new(py);- if metadata.is_empty() {- kwargs.set_item("metadata", py.None())?;- } else {- kwargs.set_item("metadata", to_py(py, metadata)?)?;- }++ kwargs.set_item("metadata", to_py(py, &metadata)?)?;+ Ok(kwargs)+ }++ pub(super) fn async_embedding_coroutine(+ &self,+ py: Python<'_>,+ prompt: &str,- metadata: &Map<String, Value>,++ metadata: Option<&Value>,+ ) -> PyResult<Py<PyAny>> {+ let kwargs = Self::metadata_kwargs(py, metadata)?;+ self.0+ .bind(py)+ .call_method("_get_async_embedding", (prompt,), Some(&kwargs))+ .map(Bound::unbind)+ }++ pub(super) fn extract(vector: Bound<'_, PyAny>) -> PyResult<Vec<f32>> {+ Ok(vector+ .extract::<Vec<f64>>()?+ .into_iter()+ .map(|value| value as f32)+ .collect())}}--impl Embedder for PythonEmbedder {- fn embed(&self, prompt: &str, metadata: &Map<String, Value>) -> Result<Vec<f32>, Error> {++impl litellm_cache_valkey_semantic::Embedder for PythonEmbedder {+ fn embed(&self, prompt: &str, metadata: Option<&Value>) -> Result<Vec<f32>, Error> {+ let result = Python::attach(|py| -> PyResult<Vec<f64>> {+ let metadata = to_py(py, &metadata)?;- self.sync_embed++ self.0+ .bind(py)- .call1((prompt, metadata))?++ .call_method1("_get_embedding", (prompt, metadata))?+ .extract()+ })+ .map_err(|_| Error::Unavailable)?;+ Ok(result.into_iter().map(|value| value as f32).collect())+ }+- #[expect(- clippy::manual_async_fn,- reason = "the shared Embedder trait uses an impl Future return"- )]+ fn async_embed(+ &self,+ _prompt: &str,+ _metadata: Option<&Value>,+ ) -> impl Future<Output = Result<Vec<f32>, Error>> + Send {- async { Err(Error::Unavailable) }++ let seeded = PREPARED_EMBEDDING++ .try_with(Clone::clone)++ .unwrap_or(Err(Error::Unavailable));++ std::future::ready(seeded)++ }++}++++impl litellm_cache_redis_semantic::Embedder for PythonEmbedder {++ fn embed(&self, prompt: &str, metadata: Option<&Value>) -> Result<Vec<f32>, Error> {+ Python::attach(|py| {+ let kwargs = Self::metadata_kwargs(py, metadata)?;+ Self::extract(self.0.bind(py).call_method(+ "_get_embedding",+ (prompt,),+ Some(&kwargs),+ )?)+ })+ .map_err(|_| Error::Unavailable)+ }++ fn async_embed(+ &self,+ _prompt: &str,- _metadata: &Map<String, Value>,++ _metadata: Option<&Value>,+ ) -> impl Future<Output = Result<Vec<f32>, Error>> + Send {+ let seeded = PREPARED_EMBEDDING+ .try_with(Clone::clone)+ .unwrap_or(Err(Error::Unavailable));+ std::future::ready(seeded)+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[tokio::test]+ async fn async_embed_returns_the_seeded_vector_or_unavailable() {- Python::initialize();- let embedder = Python::attach(|py| PythonEmbedder::new(py.None()));- let metadata = Map::new();- let embedder_ref = &embedder;- let metadata_ref = &metadata;- assert_eq!(- with_prepared_embedding(Ok(vec![0.5f32, 0.25]), async move {- embedder_ref.async_embed("prompt", metadata_ref).await- })- .await,- Ok(vec![0.5, 0.25])- );- assert_eq!(- embedder.async_embed("prompt", &metadata).await,- Err(Error::Unavailable)- );++ let object = Python::attach(|py| {++ Python::initialize();++ py.None()++ });++ let embedder = PythonEmbedder::new(object);++ let scoped_embedder = embedder.clone();++ let scoped = with_prepared_embedding(Ok(vec![0.25]), async move {++ litellm_cache_redis_semantic::Embedder::async_embed(&scoped_embedder, "prompt", None)++ .await++ });++ assert_eq!(scoped.await, Ok(vec![0.25]));++ let unscoped =++ litellm_cache_redis_semantic::Embedder::async_embed(&embedder, "prompt", None).await;++ assert_eq!(unscoped, Err(Error::Unavailable));}}diff --cc litellm-rust/crates/python-bridge/src/cache/facade.rsindex c4be7a9254a,4b4e3255cb4..f1389b745e9--- a/litellm-rust/crates/python-bridge/src/cache/facade.rs+++ b/litellm-rust/crates/python-bridge/src/cache/facade.rs@@@ -388,12 -425,10 +439,17 @@@ impl FacadeGuard"redis_kwargs","redis_flush_size","similarity_threshold",+ "distance_threshold",+ "embedding_model",+ "embedding_max_input_tokens",+ "embedding_timeout",+ "_index_name",+ "_redis_url",++ "similarity_threshold",+ "embedding_model",+ "index_name",+ "embedding_max_input_tokens",+ "embedding_timeout","bucket_name","key_prefix","path_service_account",diff --cc litellm-rust/crates/python-bridge/src/cache/handle.rsindex 8c64e5bbb19,769ad3548be..e6edf48d72f--- a/litellm-rust/crates/python-bridge/src/cache/handle.rs+++ b/litellm-rust/crates/python-bridge/src/cache/handle.rs@@@ -1,17 -1,13 +1,18 @@@+ use litellm_auth_aws::AwsAuthConfig;+ use litellm_cache_gcs::{DEFAULT_ENDPOINT, GcsConfig};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::*};+use pyo3::{+ PyTraverseError, PyVisit,+ exceptions::{PyRuntimeError, PyTypeError},+ prelude::*,+};- use litellm_cache_gcs::{DEFAULT_ENDPOINT, GcsConfig};-use super::{- cache_error, embedder::PythonEmbedder, facade::FacadeGuard, native::NativeResponseCache,- request::duration,+ cache_error, config::project_redis_semantic, embedder::PythonEmbedder, facade::FacadeGuard,+ native::NativeResponseCache, request::duration,};#[pyclass(frozen, name = "_CacheTestHandle")]diff --cc litellm-rust/crates/python-bridge/src/cache/mod.rsindex cd772d571cb,278d3da1ff9..fa028518559--- a/litellm-rust/crates/python-bridge/src/cache/mod.rs+++ b/litellm-rust/crates/python-bridge/src/cache/mod.rs@@@ -8,7 -8,7 +8,8 @@@ mod handlemod native;mod request;mod resolver;+mod semantic;+ mod semantic_step;use litellm_cache::Error;use pyo3::{diff --cc litellm-rust/crates/python-bridge/src/cache/native.rsindex d2bced66f2c,575dae45833..acc457d8c9c--- a/litellm-rust/crates/python-bridge/src/cache/native.rs+++ b/litellm-rust/crates/python-bridge/src/cache/native.rs@@@ -6,14 -8,69 +8,71 @@@ use litellm_cache_disk::DiskCacheuse litellm_cache_gcs::{GcsCache, GcsConfig, StaticTokenSource};use litellm_cache_memory::InMemoryCache;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 pyo3::{Py, PyAny, PyTraverseError, PyVisit};+ use litellm_cache_s3::{S3Cache, S3CacheConfig};+ use litellm_cache_valkey_semantic::{ValkeySemanticCache, ValkeySemanticConfig};-use pyo3::prelude::*;++use pyo3::{PyTraverseError, PyVisit, prelude::*};use serde_json::Value;- use super::{embedder::PythonEmbedder, request::CacheRequest};+ use super::{+ 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 {@@@ -22,10 -79,15 +81,19 @@@cache: Arc<ResponseCache<RedisCache<ResponseCacheCodec>>>,buffer: Option<Arc<WriteBuffer>>,},+ S3(Arc<ResponseCache<S3Cache<ResponseCacheCodec>>>),Gcs(Arc<ResponseCache<GcsCache<ResponseCacheCodec>>>),+ ValkeySemantic {+ cache: Arc<ResponseCache<ValkeySemanticCache<PythonEmbedder, ResponseCacheCodec>>>,+ embedder: PythonEmbedder,+ scope: String,+ },++ RedisSemantic {++ cache: Arc<ResponseCache<RedisSemanticCache<PythonEmbedder>>>,++ embedder: PythonEmbedder,++ },Disk(Arc<ResponseCache<DiskCache<ResponseCacheCodec>>>),AzureBlob(Arc<ResponseCache<AzureBlobCache<ResponseCacheCodec>>>),- RedisSemantic(Arc<ResponseCache<RedisSemanticCache<PythonEmbedder>>>),}impl NativeResponseCache {@@@ -56,20 -118,41 +124,53 @@@buffer: None,})}- pub fn disk(directory: &str) -> Result<Self, Error> {- let cache = DiskCache::open(directory, ResponseCacheCodec)?;- Ok(Self::Disk(Arc::new(ResponseCache::new(Arc::new(cache)))))++ pub async fn s3(config: S3CacheConfig) -> Self {+ let runtime = tokio::runtime::Handle::current();+ Self::S3(Arc::new(ResponseCache::new(Arc::new(S3Cache::new(+ config,+ ResponseCacheCodec,+ runtime,+ )))))+ }++ pub fn valkey_semantic(+ url: &str,+ similarity_threshold: f64,+ index_name: String,+ embedder: PythonEmbedder,+ ) -> Result<Self, Error> {+ let backend = ValkeySemanticCache::new(+ url,+ embedder.clone(),+ ResponseCacheCodec,+ ValkeySemanticConfig {+ similarity_threshold,+ index_name,+ },+ )?;+ Ok(Self::ValkeySemantic {+ cache: Arc::new(ResponseCache::new(Arc::new(backend))),+ embedder,+ scope: String::from("key"),+ })}+ pub fn redis_semantic(+ url: &str,+ embedder: PythonEmbedder,+ config: RedisSemanticConfig,+ ) -> Result<Self, Error> {- let backend = RedisSemanticCache::new(url, embedder, config)?;- Ok(Self::RedisSemantic(Arc::new(ResponseCache::new(Arc::new(- backend,- )))))++ let backend = RedisSemanticCache::new(url, embedder.clone(), config)?;++ Ok(Self::RedisSemantic {++ cache: Arc::new(ResponseCache::new(Arc::new(backend))),++ embedder,++ })++ }+++ 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> {@@@ -105,21 -188,71 +206,90 @@@)),Self::Memory(_)| Self::Redis { .. }+ | Self::S3(_)+ | Self::ValkeySemantic { .. }++ | Self::RedisSemantic { .. }| Self::Disk(_)- | Self::Gcs(_)- | Self::RedisSemantic(_) => 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(++ 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::ValkeySemantic { .. } => "valkey-semantic",++ Self::RedisSemantic { .. } => "redis_semantic",Self::Disk(_) => "disk",- Self::RedisSemantic(_) => "redis_semantic",Self::AzureBlob(_) => "azure-blob",}}@@@ -128,28 -261,62 +298,65 @@@match self {Self::Memory(cache) => cache.default_ttl(),Self::Redis { cache, .. } => cache.default_ttl(),+ Self::S3(cache) => cache.default_ttl(),Self::Gcs(cache) => cache.default_ttl(),+ Self::ValkeySemantic { cache, .. } => cache.default_ttl(),++ Self::RedisSemantic { cache, .. } => cache.default_ttl(),Self::Disk(cache) => cache.default_ttl(),- Self::RedisSemantic(cache) => cache.default_ttl(),Self::AzureBlob(cache) => cache.default_ttl(),}}+ pub fn bucket(&self) -> Option<&str> {+ match self {+ Self::S3(cache) => Some(cache.backend().bucket()),+ _ => None,+ }+ }++ pub fn key_prefix(&self) -> Option<&str> {+ match self {+ Self::S3(cache) => Some(cache.backend().key_prefix()),+ _ => None,+ }+ }++ pub fn region(&self) -> Option<&str> {+ match self {+ Self::S3(cache) => Some(cache.backend().region()),+ _ => None,+ }+ }++ pub fn endpoint(&self) -> Option<&str> {+ match self {+ Self::S3(cache) => cache.backend().endpoint(),+ _ => None,+ }+ }+pub fn namespace(&self) -> Option<&str> {match self {- Self::Memory(_) | Self::Disk(_) | Self::AzureBlob(_) | Self::RedisSemantic(_) => None,+ Self::Memory(_)+ | Self::S3(_)+ | Self::ValkeySemantic { .. }++ | Self::RedisSemantic { .. }+ | Self::Disk(_)+ | Self::AzureBlob(_)+ | Self::Gcs(_) => None,Self::Redis { cache, .. } => cache.backend().namespace(),- Self::Gcs(_) => None,}}pub fn topology(&self) -> Option<&RedisTopology> {match self {Self::Memory(_)+ | Self::S3(_)+ | Self::ValkeySemantic { .. }++ | Self::RedisSemantic { .. }| Self::Disk(_)| Self::AzureBlob(_)- | Self::Gcs(_)- | Self::RedisSemantic(_) => None,+ | Self::Gcs(_) => None,Self::Redis { cache, .. } => Some(cache.backend().topology()),}}@@@ -158,10 -325,11 +365,12 @@@match self {Self::Memory(cache) => Some(cache.backend().max_size_in_memory()),Self::Redis { .. }+ | Self::S3(_)+ | Self::ValkeySemantic { .. }++ | Self::RedisSemantic { .. }| Self::Disk(_)| Self::AzureBlob(_)- | Self::Gcs(_)- | Self::RedisSemantic(_) => None,+ | Self::Gcs(_) => None,}}@@@ -169,97 -337,47 +378,84 @@@match self {Self::Memory(cache) => cache.backend().max_entry_bytes(),Self::Redis { .. }+ | Self::S3(_)+ | Self::ValkeySemantic { .. }++ | Self::RedisSemantic { .. }| Self::Disk(_)| Self::AzureBlob(_)- | Self::Gcs(_)- | Self::RedisSemantic(_) => None,- }- }-- pub fn index_name(&self) -> Option<&str> {- match self {- Self::RedisSemantic(cache) => Some(cache.backend().index_name()),- Self::Memory(_)- | Self::Redis { .. }- | Self::AzureBlob(_)- | Self::Disk(_)| Self::Gcs(_) => None,}}- pub fn similarity_threshold(&self) -> Option<f32> {+ pub fn directory(&self) -> Option<&Path> {match self {- Self::RedisSemantic(cache) => Some(cache.backend().similarity_threshold()),+ Self::Disk(cache) => Some(cache.backend().directory()),Self::Memory(_)| Self::Redis { .. }+ | Self::S3(_)+ | Self::ValkeySemantic { .. }++ | Self::RedisSemantic { .. }| Self::AzureBlob(_)- | Self::Disk(_)| Self::Gcs(_) => None,}}- pub fn semantic_embedder(&self) -> Option<&PythonEmbedder> {+ pub fn semantic_config(&self) -> Option<(f64, &str)> {match self {- Self::RedisSemantic(cache) => Some(cache.backend().embedder()),- Self::Memory(_)- | Self::Redis { .. }- | Self::AzureBlob(_)- | Self::Disk(_)- | Self::Gcs(_) => None,+ Self::ValkeySemantic { cache, .. } => Some((+ cache.backend().similarity_threshold(),+ cache.backend().index_name(),+ )),++ Self::RedisSemantic { cache, .. } => Some((++ f64::from(cache.backend().similarity_threshold()),++ cache.backend().index_name(),++ )),++ _ => None,+ }+ }+- pub fn embedder_object(&self) -> Option<&Py<PyAny>> {++ pub fn index_name(&self) -> Option<&str> {+ match self {- Self::RedisSemantic(cache) => Some(cache.backend().embedder().object()),- Self::Memory(_)- | Self::Redis { .. }- | Self::AzureBlob(_)- | Self::Disk(_)- | Self::Gcs(_) => None,++ Self::RedisSemantic { cache, .. } => Some(cache.backend().index_name()),++ _ => None,+ }+ }+- pub fn traverse(&self, visit: &PyVisit<'_>) -> Result<(), PyTraverseError> {- if let Self::RedisSemantic(cache) = self {- cache.backend().embedder().traverse(visit)?;++ pub fn similarity_threshold(&self) -> Option<f32> {++ match self {++ Self::RedisSemantic { cache, .. } => Some(cache.backend().similarity_threshold()),++ _ => None,+ }- Ok(())+ }+- pub fn with_redis_flush_size(self, flush_size: Option<usize>) -> Self {++ pub fn semantic_embedder(&self) -> Option<&PythonEmbedder> {+ match self {- Self::Redis { cache, .. } => Self::Redis {- cache,- buffer: flush_size.map(|flush_size| Arc::new(WriteBuffer::new(flush_size))),- },- other => other,++ Self::RedisSemantic { embedder, .. } => Some(embedder),++ _ => None,+ }+ }+- pub fn directory(&self) -> Option<&Path> {++ pub fn embedder_object(&self) -> Option<&Py<PyAny>> {+ match self {- Self::Disk(cache) => Some(cache.backend().directory()),- Self::Memory(_)- | Self::Redis { .. }- | Self::AzureBlob(_)- | Self::Gcs(_)- | Self::RedisSemantic(_) => None,++ Self::RedisSemantic { embedder, .. } => Some(embedder.object()),+ _ => None,}}- fn exact_requests(requests: &[CacheRequest]) -> Vec<ResponseCacheRequest<ExactCacheContext>> {- requests.iter().map(CacheRequest::exact).collect()- }-- pub fn lookup(&self, request: &CacheRequest, now: Duration) -> Result<Option<Value>, Error> {+ pub fn lookup(&self, request: &NativeRequest, now: Duration) -> Result<Option<Value>, Error> {match self {- Self::Memory(cache) => cache.lookup(&request.exact(), now),- Self::Redis { cache, .. } => cache.lookup(&request.exact(), now),- Self::Gcs(cache) => cache.lookup(&request.exact(), now),- Self::Disk(cache) => cache.lookup(&request.exact(), now),- Self::AzureBlob(cache) => cache.lookup(&request.exact(), now),- Self::RedisSemantic(cache) => cache.lookup(&request.semantic(), now),+ 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)++ }+ Self::Gcs(cache) => cache.lookup(&Self::exact(request), now),+ Self::Disk(cache) => cache.lookup(&Self::exact(request), now),+ Self::AzureBlob(cache) => cache.lookup(&Self::exact(request), now),}}@@@ -270,12 -388,15 +466,18 @@@now: Duration,) -> Result<(), Error> {match self {- Self::Memory(cache) => cache.store(&request.exact(), response, now),- Self::Redis { cache, .. } => cache.store(&request.exact(), response, now),- Self::Gcs(cache) => cache.store(&request.exact(), response, now),- Self::Disk(cache) => cache.store(&request.exact(), response, now),- Self::AzureBlob(cache) => cache.store(&request.exact(), response, now),- Self::RedisSemantic(cache) => cache.store(&request.semantic(), 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)++ }+ Self::Gcs(cache) => cache.store(&Self::exact(request), response, now),+ Self::Disk(cache) => cache.store(&Self::exact(request), response, now),+ Self::AzureBlob(cache) => cache.store(&Self::exact(request), response, now),}}@@@ -285,12 -406,27 +487,29 @@@now: Duration,) -> Result<PartialHits, Error> {match self {- Self::Memory(cache) => cache.lookup_batch(&Self::exact_requests(requests), now),- Self::Redis { cache, .. } => cache.lookup_batch(&Self::exact_requests(requests), now),- Self::Gcs(cache) => cache.lookup_batch(&Self::exact_requests(requests), now),- Self::Disk(cache) => cache.lookup_batch(&Self::exact_requests(requests), now),- Self::AzureBlob(cache) => cache.lookup_batch(&Self::exact_requests(requests), now),- Self::RedisSemantic(_) => Err(Error::UnsupportedOperation),+ Self::Memory(cache) => {+ let requests = requests.iter().map(Self::exact).collect::<Vec<_>>();+ cache.lookup_batch(&requests, now)+ }+ Self::Redis { cache, .. } => {+ let requests = requests.iter().map(Self::exact).collect::<Vec<_>>();+ cache.lookup_batch(&requests, now)+ }+ Self::S3(cache) => {+ cache.lookup_batch(&requests.iter().map(Self::exact).collect::<Vec<_>>(), now)+ }- Self::ValkeySemantic { .. } => Err(Error::UnsupportedOperation),++ Self::ValkeySemantic { .. } | Self::RedisSemantic { .. } => {++ Err(Error::UnsupportedOperation)++ }+ Self::Gcs(cache) => {+ cache.lookup_batch(&requests.iter().map(Self::exact).collect::<Vec<_>>(), now)+ }+ Self::Disk(cache) => {+ cache.lookup_batch(&requests.iter().map(Self::exact).collect::<Vec<_>>(), now)+ }+ Self::AzureBlob(cache) => {+ cache.lookup_batch(&requests.iter().map(Self::exact).collect::<Vec<_>>(), now)+ }}}@@@ -300,12 -436,51 +519,60 @@@now: Duration,) -> Result<Option<Value>, Error> {match self {- Self::Memory(cache) => cache.async_lookup(&request.exact(), now).await,- Self::Redis { cache, .. } => cache.async_lookup(&request.exact(), now).await,- Self::Gcs(cache) => cache.async_lookup(&request.exact(), now).await,- Self::Disk(cache) => cache.async_lookup(&request.exact(), now).await,- Self::AzureBlob(cache) => cache.async_lookup(&request.exact(), now).await,- Self::RedisSemantic(cache) => cache.async_lookup(&request.semantic(), 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)++ .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)),++ ),}}@@@ -326,37 -509,100 +601,111 @@@buffer: Some(buffer),} => {buffer- .async_store(cache, &request.exact(), response, now)+ .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)++ .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::Gcs(cache) => cache.async_store(&request.exact(), response, now).await,- Self::Disk(cache) => cache.async_store(&request.exact(), response, now).await,- Self::AzureBlob(cache) => cache.async_store(&request.exact(), response, now).await,- Self::RedisSemantic(cache) => {- cache.async_store(&request.semantic(), 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)),++ ),+ }+ }+pub async fn async_lookup_batch(&self,- requests: &[CacheRequest],+ requests: &[NativeRequest],now: Duration,) -> Result<PartialHits, Error> {match self {Self::Memory(cache) => {- cache- .async_lookup_batch(&Self::exact_requests(requests), now)- .await+ let requests = requests.iter().map(Self::exact).collect::<Vec<_>>();+ cache.async_lookup_batch(&requests, now).await}Self::Redis { cache, .. } => {+ let requests = requests.iter().map(Self::exact).collect::<Vec<_>>();+ cache.async_lookup_batch(&requests, now).await+ }+ Self::S3(cache) => {cache- .async_lookup_batch(&Self::exact_requests(requests), now)+ .async_lookup_batch(&requests.iter().map(Self::exact).collect::<Vec<_>>(), now).await}- Self::ValkeySemantic { .. } => Err(Error::UnsupportedOperation),++ Self::ValkeySemantic { .. } | Self::RedisSemantic { .. } => {++ Err(Error::UnsupportedOperation)++ }Self::Gcs(cache) => {cache- .async_lookup_batch(&Self::exact_requests(requests), now)+ .async_lookup_batch(&requests.iter().map(Self::exact).collect::<Vec<_>>(), now).await}Self::Disk(cache) => {@@@ -380,71 -625,99 +728,104 @@@) -> Result<(), Error> {match self {Self::Memory(cache) => {- cache- .async_store_batch(- entries- .into_iter()- .map(|(request, value)| (request.exact(), 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)| (request.exact(), 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::Gcs(cache) => {- cache- .async_store_batch(- entries- .into_iter()- .map(|(request, value)| (request.exact(), 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)| (request.exact(), 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::AzureBlob(cache) => {- cache- .async_store_batch(- entries- .into_iter()- .map(|(request, value)| (request.exact(), 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::RedisSemantic(cache) => {- cache- .async_store_batch(- entries- .into_iter()- .map(|(request, value)| (request.semantic(), value))- .collect(),- 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())),++ ),}}@@@ -457,9 -730,10 +838,12 @@@}cache.async_flush().await}+ Self::S3(cache) => cache.async_flush().await,- Self::ValkeySemantic { .. } => Err(Error::UnsupportedOperation),++ Self::ValkeySemantic { .. } | Self::RedisSemantic { .. } => {++ Err(Error::UnsupportedOperation)++ }Self::Gcs(cache) => cache.async_flush().await,Self::Disk(cache) => cache.async_flush().await,- Self::RedisSemantic(_) => Err(Error::UnsupportedOperation),Self::AzureBlob(cache) => cache.async_flush().await,}}@@@ -468,13 -742,14 +852,24 @@@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::Gcs(cache) => cache.test_connection().await,Self::Disk(cache) => cache.test_connection().await,- Self::RedisSemantic(_) => Err(Error::UnsupportedOperation),Self::AzureBlob(cache) => cache.test_connection().await,}}++ pub(super) fn traverse(&self, visit: &PyVisit<'_>) -> Result<(), PyTraverseError> {++ match self {++ Self::ValkeySemantic { embedder, .. } => embedder.traverse(visit)?,++ Self::RedisSemantic { embedder, .. } => embedder.traverse(visit)?,++ _ => {}++ }++ Ok(())++ }++pub fn gcs_backend(&self) -> Option<&GcsCache<ResponseCacheCodec>> {match self {Self::Gcs(cache) => Some(cache.backend()),@@@ -482,3 -757,79 +877,80 @@@}}}++ #[cfg(test)]+ mod tests {+ use litellm_cache_response::{CacheControls, CacheKeyInput, cache_key};+ use serde_json::json;+ use sha2::{Digest, Sha256};++ use super::*;++ fn native_request(key: CacheKeyInput, metadata: Value) -> NativeRequest {+ NativeRequest {+ key,+ controls: CacheControls::default(),+ ttl: None,+ max_age: None,+ messages: Some(json!([{"role": "user", "content": "prompt"}])),+ input: None,+ metadata: Some(metadata),+ litellm_metadata: None,+ litellm_params: None,++ scope: None,+ }+ }++ #[test]+ fn semantic_key_matches_python_scope_material() {+ let key = CacheKeyInput {+ fields: vec![+ CacheKeyField {+ name: "model".to_owned(),+ value: Some("gpt-4.1".to_owned()),+ api_parameter: true,+ internal_parameter: false,+ },+ CacheKeyField {+ name: "messages".to_owned(),+ value: Some("prompt".to_owned()),+ api_parameter: true,+ internal_parameter: false,+ },+ ],+ ..Default::default()+ };+ let request = native_request(+ key,+ json!({"user_api_key": "k1", "user_api_key_team_id": null}),+ );+ let expected = format!("{:x}", Sha256::digest(b"model: gpt-4.1user_api_key: k1"));+ assert_eq!(cache_key(&semantic_key(&request, "key")), expected);++ let end_user_request = native_request(+ request.key.clone(),+ json!({"user_api_key": "k1", "user_api_key_end_user_id": "u1"}),+ );+ let expected = format!(+ "{:x}",+ Sha256::digest(b"model: gpt-4.1user_api_key: k1user_api_key_end_user_id: u1")+ );+ assert_eq!(+ cache_key(&semantic_key(&end_user_request, "end_user")),+ expected+ );++ let preset_request = native_request(+ CacheKeyInput {+ preset: Some("preset-key".to_owned()),+ ..Default::default()+ },+ json!({"user_api_key": "k1"}),+ );+ assert_eq!(+ semantic_key(&preset_request, "end_user").preset.as_deref(),+ Some("preset-key")+ );+ assert!(semantic_key(&preset_request, "end_user").fields.is_empty());+ }+ }diff --cc litellm-rust/crates/python-bridge/src/cache/request.rsindex b06087bcc83,036951891a1..3b4b910c1f0--- a/litellm-rust/crates/python-bridge/src/cache/request.rs+++ b/litellm-rust/crates/python-bridge/src/cache/request.rs@@@ -14,65 -14,44 +14,48 @@@ struct RequestInputcontrols: Option<CacheControls>,ttl_seconds: Option<f64>,max_age_seconds: Option<f64>,+ messages: Option<Value>,input: Option<Value>,- messages: Option<Vec<Value>>,- metadata: Option<Map<String, Value>>,+ metadata: Option<Value>,+ litellm_metadata: Option<Value>,+ litellm_params: Option<Value>,+ scope: Option<String>,}+#[derive(Clone)]- pub(super) struct CacheRequest {- key: CacheKeyInput,- controls: CacheControls,- ttl: Option<Duration>,- max_age: Option<Duration>,- input: Option<Value>,- messages: Vec<Value>,- metadata: Map<String, Value>,- scope: Option<String>,- }-- impl CacheRequest {- pub(super) fn exact(&self) -> ResponseCacheRequest<ExactCacheContext> {- let mut request = ResponseCacheRequest::new(self.key.clone());- request.controls = self.controls;- request.context.ttl = self.ttl;- request.max_age = self.max_age;- request- }-- pub(super) fn semantic(&self) -> ResponseCacheRequest<SemanticCacheContext> {- ResponseCacheRequest {- key: self.key.clone(),- controls: self.controls,- context: SemanticCacheContext {- input: self.input.clone(),- messages: self.messages.clone(),- metadata: self.metadata.clone(),- scope: self.scope.clone(),- ttl: self.ttl,- },- max_age: self.max_age,- }- }+ pub(super) struct NativeRequest {+ pub(super) key: CacheKeyInput,+ pub(super) controls: CacheControls,+ pub(super) ttl: Option<Duration>,+ pub(super) max_age: Option<Duration>,+ pub(super) messages: Option<Value>,+ pub(super) input: Option<Value>,+ pub(super) metadata: Option<Value>,+ pub(super) litellm_metadata: Option<Value>,+ pub(super) litellm_params: Option<Value>,++ pub(super) scope: Option<String>,}- pub(super) fn request(value: &Bound<'_, PyAny>) -> PyResult<CacheRequest> {+ pub(super) fn request(value: &Bound<'_, PyAny>) -> PyResult<NativeRequest> {let input: RequestInput = from_py(value)?;request_input(input)}- fn request_input(input: RequestInput) -> PyResult<CacheRequest> {- let defaults = ResponseCacheRequest::<ExactCacheContext>::new(input.key.clone());- Ok(CacheRequest {+ fn request_input(input: RequestInput) -> PyResult<NativeRequest> {+ let controls = input.controls.unwrap_or_else(|| {+ ResponseCacheRequest::<ExactCacheContext>::new(input.key.clone()).controls+ });+ Ok(NativeRequest {key: input.key,- controls: input.controls.unwrap_or(defaults.controls),+ controls,ttl: input.ttl_seconds.map(duration).transpose()?,max_age: input.max_age_seconds.map(duration).transpose()?,+ messages: input.messages,input: input.input,- messages: input.messages.unwrap_or_default(),- metadata: input.metadata.unwrap_or_default(),+ metadata: input.metadata,+ litellm_metadata: input.litellm_metadata,+ litellm_params: input.litellm_params,+ scope: input.scope,})}diff --cc litellm-rust/crates/python-bridge/src/cache/semantic.rsindex f0f75de1edf,00000000000..7661598c5f9mode 100644,000000..100644--- a/litellm-rust/crates/python-bridge/src/cache/semantic.rs+++ b/litellm-rust/crates/python-bridge/src/cache/semantic.rs@@@ -1,176 -1,0 +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::{CacheRequest, now},++ request::{NativeRequest, now},+};++pub(super) enum SemanticOperation {- Lookup(CacheRequest),- Store(CacheRequest, Value),- StoreBatch(VecDeque<(CacheRequest, Value)>),++ Lookup(NativeRequest),++ Store(NativeRequest, Value),++ StoreBatch(VecDeque<(NativeRequest, Value)>),+}++enum Phase {+ Start,+ AwaitingEmbedding,+ AwaitingBackend,+}++pub(super) struct SemanticBody {+ service: NativeResponseCache,+ operation: SemanticOperation,- pending: Option<(CacheRequest, Option<Value>)>,++ 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 = request.semantic();++ let semantic = NativeResponseCache::redis_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,++ 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> {- self.service.traverse(visit)++ if let Some(embedder) = self.service.semantic_embedder() {++ embedder.traverse(visit)?;++ }++ Ok(())+ }+}+- pub(super) fn drive(- py: Python<'_>,- service: NativeResponseCache,- operation: SemanticOperation,- ) -> PyResult<Bound<'_, PyAny>> {- let execution = Py::new(py, Execution::new(SemanticBody::new(service, operation)))?;++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 f823dcfb135,978e770b4be..c0bb93daadc--- a/litellm/rust_bridge/_native.pyi+++ b/litellm/rust_bridge/_native.pyi@@@ -114,6 -167,15 +167,17 @@@ class _CacheTestHandle@staticmethoddef disk(directory: str) -> _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: ...+ @staticmethoddef gcs(bucket_name: str,*,diff --cc tests/test_litellm_rust/test_cache.pyindex c11a43abc80,e0d92a2e957..45f7214ecbf--- a/tests/test_litellm_rust/test_cache.py+++ b/tests/test_litellm_rust/test_cache.py@@@ -9,14 -7,16 +9,18 @@@ import threadinimport timeimport uuidimport weakref-from collections.abc import Generator+from collections.abc import Callable, Generator+from contextlib import ExitStack+ from datetime import datetimefrom pathlib import Pathfrom types import SimpleNamespacefrom typing import Final, Protocol, cast+ from unittest.mock import Mockfrom urllib.parse import urlparse+from uuid import uuid4+ import boto3+ import botocore.configimport diskcacheimport fakeredisimport pytest@@@ -26,21 -26,17 +30,23 @@@ from azure.storage.blob import Containeimport litellmfrom litellm.caching.azure_blob_cache import AzureBlobCachefrom litellm.caching.caching import Cache, disable_cache, enable_cache, update_cache- from litellm.caching.gcs_cache import GCSCachefrom litellm.caching.disk_cache import DiskCache+ from litellm.caching.gcs_cache import GCSCachefrom litellm.caching.in_memory_cache import InMemoryCachefrom litellm.caching.redis_cluster_cache import RedisClusterCache+from litellm.caching.redis_semantic_cache import RedisSemanticCache+ from litellm.caching.s3_cache import S3Cachefrom litellm.rust_bridge import _nativefrom litellm.types.caching import LiteLLMCacheType+from litellm.types.llms.custom_llm import CustomLLMItem+from litellm.types.utils import EmbeddingResponsefrom tests.test_litellm_rust.support.fake_gcs import FakeGcsfrom tests.test_litellm_rust.support.isolation import rebound+ from tests.test_litellm_rust.support.s3_stub import S3Stub+_CacheTestHandle: Final = _native._CacheTestHandle # pyright: ignore[reportPrivateUsage] # test-only handle has no public module name+_CacheTestResolver: Final = _native._CacheTestResolver # pyright: ignore[reportPrivateUsage] # test-only resolver has no public module name+pytestmark: Final = pytest.mark.requires_rust_extension