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 Leef24244a1a4a6
diff --cc litellm-rust/crates/cache-redis/src/cache.rsindex 6388448accc,e2e2656fcbb..35ad659dc63--- a/litellm-rust/crates/cache-redis/src/cache.rs+++ b/litellm-rust/crates/cache-redis/src/cache.rs@@@ -9,8 -9,14 +9,14 @@@ use litellm_cache::};use redis::Commands;+ use crate::topology::RedisTopology;++ mod connection;mod operations;-pub(crate) use connection::ConnectionRef;++pub use connection::ConnectionRef;+ use connection::{ClusterConnectionManager, ConnectionManager};+pub use operations::{RedisArg, RedisLpopOperation, RedisLpopResult, RedisRpushOperation, RedisScript,};@@@ -71,8 -40,9 +40,9 @@@ const CLAIM_SCRIPT: &str = concat!);const CLAIM_ATTEMPTS: usize = 8;-enum Connections<C> {+pub enum Connections<C> {Pool(r2d2::Pool<ConnectionManager>),+ Cluster(r2d2::Pool<ClusterConnectionManager>),Fixed(Mutex<C>),}@@@ -113,23 -50,7 +50,22 @@@ impl<C> Connections<CwhereC: redis::ConnectionLike + Send + 'static,{- fn execute<T>(+ pub fn pooled(url: &str, timeout: Duration, pool_size: u32) -> Result<Self, Error> {- let client = redis::Client::open(url).map_err(|_| Error::Unavailable)?;+ let pool = r2d2::Pool::builder()+ .max_size(pool_size)+ .min_idle(Some(0))+ .connection_timeout(timeout)+ .test_on_check_out(false)- .build(ConnectionManager { client, timeout })++ .build(ConnectionManager::open(url)?)+ .map_err(|_| Error::Unavailable)?;+ Ok(Self::Pool(pool))+ }++ pub fn fixed(connection: C) -> Self {+ Self::Fixed(Mutex::new(connection))+ }++ pub fn execute<T>(&self,operation: impl FnOnce(&mut ConnectionRef<'_>) -> Result<T, Error>,) -> Result<T, Error> {@@@ -262,16 -199,22 +224,24 @@@ wher}fn ttl_seconds(ttl: Duration) -> u64 {- ttl.as_secs()- .saturating_add(u64::from(ttl.subsec_nanos() > 0))- .max(1)+ ttl_seconds(ttl)}++ async fn run_blocking<T, F>(connections: Arc<Connections<C>>, operation: F) -> Result<T, Error>+ where+ T: Send + 'static,+ F: FnOnce(&mut ConnectionRef<'_>) -> Result<T, Error> + Send + 'static,+ {- tokio::task::spawn_blocking(move || connections.execute(operation))- .await- .map_err(|_| Error::Unavailable)?++ Connections::run_blocking(connections, operation).await+ }}+pub fn ttl_seconds(ttl: Duration) -> u64 {+ ttl.as_secs()+ .saturating_add(u64::from(ttl.subsec_nanos() > 0))+ .max(1)+}+fn namespaced_key(namespace: Option<&str>, key: &str) -> String {match namespace {Some(namespace) if !key.starts_with(&format!("{namespace}:")) => {diff --cc litellm-rust/crates/cache-redis/src/cache/connection.rsindex 00000000000,1834f1d94e5..013bf055f89mode 000000,100644..100644--- a/litellm-rust/crates/cache-redis/src/cache/connection.rs+++ b/litellm-rust/crates/cache-redis/src/cache/connection.rs@@@ -1,0 -1,392 +1,392 @@@+ use std::collections::HashMap;++ use litellm_cache::Error;+ use redis::{+ ConnectionAddr, ConnectionInfo, ConnectionLike, IntoConnectionInfo,+ cluster::{ClusterClient, ClusterClientBuilder, ClusterConnection, NodeAddress},+ cluster_routing::{+ MultipleNodeRoutingInfo, ResponsePolicy, RoutingInfo, SingleNodeRoutingInfo, Slot,+ },+ };++ use super::REDIS_TIMEOUT;+ use crate::topology::RedisNode;+-pub(super) struct PooledConnection<C> {++pub struct PooledConnection<C> {+ pub(super) connection: C,+ pub(super) failed: bool,+ }++ /// Pools connections without a checkout PING, which would double every operation's round trips.+ /// A timed-out command leaves its reply on the socket while redis still reports the connection+ /// open, so any connection whose operation failed is discarded instead of being reused.-pub(super) struct ConnectionManager(redis::Client);++pub struct ConnectionManager(redis::Client);++ impl ConnectionManager {+ pub(super) fn open(url: &str) -> Result<Self, Error> {+ redis::Client::open(url)+ .map(Self)+ .map_err(|_| Error::Unavailable)+ }+ }++ impl r2d2::ManageConnection for ConnectionManager {+ type Connection = PooledConnection<redis::Connection>;+ type Error = redis::RedisError;++ fn connect(&self) -> Result<Self::Connection, redis::RedisError> {+ let connection = self.0.get_connection()?;+ connection.set_read_timeout(Some(REDIS_TIMEOUT))?;+ connection.set_write_timeout(Some(REDIS_TIMEOUT))?;+ Ok(PooledConnection {+ connection,+ failed: false,+ })+ }++ fn is_valid(&self, connection: &mut Self::Connection) -> Result<(), redis::RedisError> {+ redis::cmd("PING").query::<String>(&mut connection.connection)?;+ Ok(())+ }++ fn has_broken(&self, connection: &mut Self::Connection) -> bool {+ connection.failed || !redis::ConnectionLike::is_open(&connection.connection)+ }+ }+-pub(super) struct ClusterConnectionManager(ClusterClient);++pub struct ClusterConnectionManager(ClusterClient);++ impl ClusterConnectionManager {+ pub(super) fn open(url: &str, startup_nodes: &[RedisNode]) -> Result<Self, Error> {+ if startup_nodes.is_empty() {+ return Err(Error::Unavailable);+ }+ let info = url.into_connection_info().map_err(|_| Error::Unavailable)?;+ let nodes = startup_nodes+ .iter()+ .map(|node| node_info(&info, node))+ .collect::<Result<Vec<_>, _>>()?;+ ClusterClientBuilder::new(nodes)+ .connection_timeout(REDIS_TIMEOUT)+ .response_timeout(REDIS_TIMEOUT)+ .build()+ .map(Self)+ .map_err(|_| Error::Unavailable)+ }+ }++ fn node_info(info: &ConnectionInfo, node: &RedisNode) -> Result<ConnectionInfo, Error> {+ let addr = match info.addr() {+ ConnectionAddr::Tcp(..) => ConnectionAddr::Tcp(node.host.clone(), node.port),+ ConnectionAddr::TcpTls {+ insecure,+ tls_params,+ ..+ } => ConnectionAddr::TcpTls {+ host: node.host.clone(),+ port: node.port,+ insecure: *insecure,+ tls_params: tls_params.clone(),+ },+ _ => return Err(Error::Unavailable),+ };+ Ok(info.clone().set_addr(addr))+ }++ impl r2d2::ManageConnection for ClusterConnectionManager {+ type Connection = PooledConnection<ClusterConnection>;+ type Error = redis::RedisError;++ fn connect(&self) -> Result<Self::Connection, redis::RedisError> {+ let connection = self.0.get_connection()?;+ connection.set_read_timeout(Some(REDIS_TIMEOUT))?;+ connection.set_write_timeout(Some(REDIS_TIMEOUT))?;+ Ok(PooledConnection {+ connection,+ failed: false,+ })+ }++ fn is_valid(&self, connection: &mut Self::Connection) -> Result<(), redis::RedisError> {+ redis::cmd("PING").query::<String>(&mut connection.connection)?;+ Ok(())+ }++ fn has_broken(&self, connection: &mut Self::Connection) -> bool {+ connection.failed || !redis::ConnectionLike::is_open(&connection.connection)+ }+ }+-pub(crate) enum ConnectionRef<'a> {++pub enum ConnectionRef<'a> {+ Node(&'a mut dyn redis::ConnectionLike),+ Cluster(&'a mut ClusterConnection),+ }++ impl redis::ConnectionLike for ConnectionRef<'_> {+ fn req_packed_command(&mut self, cmd: &[u8]) -> redis::RedisResult<redis::Value> {+ match self {+ Self::Node(connection) => connection.req_packed_command(cmd),+ Self::Cluster(connection) => connection.req_packed_command(cmd),+ }+ }++ fn req_packed_commands(+ &mut self,+ cmd: &[u8],+ offset: usize,+ count: usize,+ ) -> redis::RedisResult<Vec<redis::Value>> {+ match self {+ Self::Node(connection) => connection.req_packed_commands(cmd, offset, count),+ Self::Cluster(connection) => connection.req_packed_commands(cmd, offset, count),+ }+ }++ fn get_db(&self) -> i64 {+ match self {+ Self::Node(connection) => connection.get_db(),+ Self::Cluster(connection) => redis::ConnectionLike::get_db(*connection),+ }+ }++ fn supports_pipelining(&self) -> bool {+ match self {+ Self::Node(connection) => connection.supports_pipelining(),+ Self::Cluster(connection) => redis::ConnectionLike::supports_pipelining(*connection),+ }+ }++ fn check_connection(&mut self) -> bool {+ match self {+ Self::Node(connection) => connection.check_connection(),+ Self::Cluster(connection) => connection.check_connection(),+ }+ }++ fn is_open(&self) -> bool {+ match self {+ Self::Node(connection) => connection.is_open(),+ Self::Cluster(connection) => redis::ConnectionLike::is_open(*connection),+ }+ }+ }++ impl ConnectionRef<'_> {+ pub(crate) fn pipeline(+ &mut self,+ commands: Vec<redis::Cmd>,+ ) -> Result<Vec<redis::Value>, Error> {+ match self {+ Self::Node(connection) => {+ let mut pipeline = redis::pipe();+ for command in &commands {+ pipeline.add_command(command.clone());+ }+ pipeline+ .query::<Vec<redis::Value>>(*connection)+ .map_err(|_| Error::Unavailable)+ }+ Self::Cluster(connection) => {+ let mut replies: Vec<Option<redis::Value>> = vec![None; commands.len()];+ for indices in slot_groups(&commands).into_values() {+ let mut pipeline = redis::pipe();+ for index in &indices {+ pipeline.add_command(commands[*index].clone());+ }+ let values = connection+ .req_packed_commands(&pipeline.get_packed_pipeline(), 0, indices.len())+ .map_err(|_| Error::Unavailable)?;+ if values.len() != indices.len() {+ return Err(Error::Unavailable);+ }+ for (index, value) in indices.into_iter().zip(values) {+ replies[index] = Some(value);+ }+ }+ replies+ .into_iter()+ .collect::<Option<Vec<_>>>()+ .ok_or(Error::Unavailable)+ }+ }+ }++ pub(crate) fn scan(+ &mut self,+ pattern: &str,+ count: usize,+ mut visit: impl FnMut(&mut Self, Vec<String>) -> Result<bool, Error>,+ ) -> Result<(), Error> {+ let pages = match self {+ Self::Node(connection) => {+ let page = scan_command(0, pattern, count)+ .query::<ScanPage>(*connection)+ .map_err(|_| Error::Unavailable)?;+ vec![(None, page)]+ }+ Self::Cluster(connection) => connection+ .route_command(+ &scan_command(0, pattern, count),+ RoutingInfo::MultiNode((+ MultipleNodeRoutingInfo::AllMasters,+ Some(ResponsePolicy::Special),+ )),+ )+ .map_err(|_| Error::Unavailable)+ .and_then(primary_pages)?+ .into_iter()+ .map(|(node, page)| (Some(node), page))+ .collect(),+ };+ for (node, (mut cursor, mut keys)) in pages {+ loop {+ if !visit(self, keys)? {+ return Ok(());+ }+ if cursor == 0 {+ break;+ }+ (cursor, keys) = self.scan_page(node.as_ref(), cursor, pattern, count)?;+ }+ }+ Ok(())+ }++ pub(crate) fn ping(&mut self) -> Result<bool, redis::RedisError> {+ let command = redis::cmd("PING");+ match self {+ Self::Node(connection) => command+ .query::<String>(*connection)+ .map(|response| response == "PONG"),+ Self::Cluster(connection) => connection+ .route_command(+ &command,+ RoutingInfo::MultiNode((+ MultipleNodeRoutingInfo::AllNodes,+ Some(ResponsePolicy::AllSucceeded),+ )),+ )+ .map(|_| true),+ }+ }++ pub(crate) fn node_text(&mut self, command: &redis::Cmd) -> Result<String, Error> {+ match self {+ Self::Node(connection) => command.query(*connection).map_err(|_| Error::Unavailable),+ Self::Cluster(connection) => {+ let value = connection+ .route_command(+ command,+ RoutingInfo::MultiNode((+ MultipleNodeRoutingInfo::AllNodes,+ Some(ResponsePolicy::Special),+ )),+ )+ .map_err(|_| Error::Unavailable)?;+ let redis::Value::Map(entries) = value else {+ return Err(Error::Unavailable);+ };+ let mut replies = entries+ .into_iter()+ .map(|(node, reply)| {+ Ok((+ redis::from_redis_value::<String>(node)+ .map_err(|_| Error::Unavailable)?,+ redis::from_redis_value::<String>(reply)+ .map_err(|_| Error::Unavailable)?,+ ))+ })+ .collect::<Result<Vec<(String, String)>, Error>>()?;+ replies.sort();+ Ok(replies+ .into_iter()+ .map(|(_, reply)| reply)+ .collect::<Vec<_>>()+ .join("\n"))+ }+ }+ }++ pub(crate) fn flushall(&mut self) -> Result<(), Error> {+ let command = redis::cmd("FLUSHALL");+ match self {+ Self::Node(connection) => command.query(*connection).map_err(|_| Error::Unavailable),+ Self::Cluster(connection) => connection+ .route_command(+ &command,+ RoutingInfo::MultiNode((+ MultipleNodeRoutingInfo::AllMasters,+ Some(ResponsePolicy::AllSucceeded),+ )),+ )+ .map(|_| ())+ .map_err(|_| Error::Unavailable),+ }+ }++ fn scan_page(+ &mut self,+ node: Option<&NodeAddress>,+ cursor: u64,+ pattern: &str,+ count: usize,+ ) -> Result<ScanPage, Error> {+ let command = scan_command(cursor, pattern, count);+ match (self, node) {+ (Self::Node(connection), None) => {+ command.query(*connection).map_err(|_| Error::Unavailable)+ }+ (Self::Cluster(connection), Some(node)) => connection+ .route_command(+ &command,+ RoutingInfo::SingleNode(SingleNodeRoutingInfo::ByAddress {+ host: node.host().to_string(),+ port: node.port(),+ }),+ )+ .map_err(|_| Error::Unavailable)+ .and_then(|value| redis::from_redis_value(value).map_err(|_| Error::Unavailable)),+ _ => Err(Error::Unavailable),+ }+ }+ }++ type ScanPage = (u64, Vec<String>);++ fn primary_pages(value: redis::Value) -> Result<Vec<(NodeAddress, ScanPage)>, Error> {+ let redis::Value::Map(entries) = value else {+ return Err(Error::Unavailable);+ };+ entries+ .into_iter()+ .map(|(node, page)| {+ let node = redis::from_redis_value::<String>(node).map_err(|_| Error::Unavailable)?;+ let node = NodeAddress::try_from(node.as_str()).map_err(|_| Error::Unavailable)?;+ let page = redis::from_redis_value::<ScanPage>(page).map_err(|_| Error::Unavailable)?;+ Ok((node, page))+ })+ .collect()+ }++ fn scan_command(cursor: u64, pattern: &str, count: usize) -> redis::Cmd {+ let mut command = redis::cmd("SCAN");+ command+ .cursor_arg(cursor)+ .arg("MATCH")+ .arg(pattern)+ .arg("COUNT")+ .arg(count);+ command+ }++ fn slot_groups(commands: &[redis::Cmd]) -> HashMap<Slot, Vec<usize>> {+ let mut groups: HashMap<Slot, Vec<usize>> = HashMap::new();+ for (index, command) in commands.iter().enumerate() {+ let key = match command.args_iter().nth(1) {+ Some(redis::Arg::Simple(key)) => key,+ _ => b"",+ };+ groups.entry(Slot::for_key(key)).or_default().push(index);+ }+ groups+ }diff --cc litellm-rust/crates/python-bridge/src/cache/config.rsindex 85e400d89a3,5fe36f6c1fa..3c20dc6f75c--- a/litellm-rust/crates/python-bridge/src/cache/config.rs+++ b/litellm-rust/crates/python-bridge/src/cache/config.rs@@@ -73,19 -75,17 +75,30 @@@ pub(super) struct RedisCacheConfigpub(super) connection: RedisConnectionConfig,}+#[allow(+ dead_code,+ reason = "embedding settings are projected so drift falls back to Python"+)]+pub(super) struct RedisSemanticCacheConfig {+ pub(super) redis_url: String,+ pub(super) index_name: String,+ pub(super) similarity_threshold: f64,+ pub(super) embedding_model: String,+ pub(super) embedding_max_input_tokens: Option<u64>,+ pub(super) embedding_timeout: Option<f64>,+}++ struct RedisClientProjection<'py> {+ topology: RedisTopology,+ host: String,+ port: u16,+ pool_size: usize,+ resolved: Bound<'py, PyDict>,+ tls: Option<RedisTlsConfig>,+ }++ const REDIS_PY_DEFAULT_MAX_CONNECTIONS: usize = 1 << 31;+pub(super) enum CacheBackendConfig {Memory(MemoryCacheConfig),Redis(Box<RedisCacheConfig>),diff --cc litellm-rust/crates/python-bridge/src/cache/facade.rsindex a6395d086cb,a9ce2ae7756..398f46d0d1e--- a/litellm-rust/crates/python-bridge/src/cache/facade.rs+++ b/litellm-rust/crates/python-bridge/src/cache/facade.rs@@@ -192,14 -218,15 +221,20 @@@ impl FacadeGuard"only exact built-in Cache facades can be registered",));}- let (module, name, cache_kind) = match kind {- "memory" => ("litellm.caching.in_memory_cache", "InMemoryCache", "local"),- "redis" => ("litellm.caching.redis_cache", "RedisCache", "redis"),- "redis_semantic" => (+ let cluster = matches!(service.topology(), Some(RedisTopology::Cluster { .. }));+ let (module, name, cache_kind) = match (kind, cluster) {+ ("memory", _) => ("litellm.caching.in_memory_cache", "InMemoryCache", "local"),+ ("redis", false) => ("litellm.caching.redis_cache", "RedisCache", "redis"),++ ("redis_semantic", _) => (+ "litellm.caching.redis_semantic_cache",+ "RedisSemanticCache",+ "redis-semantic",+ ),+ ("redis", true) => (+ "litellm.caching.redis_cluster_cache",+ "RedisClusterCache",+ "redis",+ ),_ => unreachable!(),};let backend = facade.getattr("cache")?;@@@ -252,18 -270,13 +287,20 @@@"max_size_per_item","redis_kwargs","redis_flush_size",+ "similarity_threshold",+ "distance_threshold",+ "embedding_model",+ "embedding_max_input_tokens",+ "embedding_timeout",+ "_index_name",+ "_redis_url",],)?,- redis_pool: (kind == "redis")- .then(|| RedisPoolGuard::capture(&backend))- .transpose()?,+ redis_pool: match (kind, cluster) {+ ("redis", false) => Some(RedisPoolGuard::capture(&backend, STANDALONE_POOL)?),+ ("redis", true) => Some(RedisPoolGuard::capture(&backend, CLUSTER_POOL)?),+ _ => None,+ },})}diff --cc litellm-rust/crates/python-bridge/src/cache/handle.rsindex b61ae59bb58,2ee2b0c2c8c..7b5300b52f7--- a/litellm-rust/crates/python-bridge/src/cache/handle.rs+++ b/litellm-rust/crates/python-bridge/src/cache/handle.rs@@@ -1,15 -1,8 +1,16 @@@+ use litellm_cache_redis::{RedisNode, RedisTopology};+use litellm_cache_redis_semantic::RedisSemanticConfig;use litellm_host_python::release_gil;-use pyo3::{PyTraverseError, PyVisit, exceptions::PyRuntimeError, prelude::*};+use pyo3::{+ PyTraverseError, PyVisit,+ exceptions::{PyRuntimeError, PyTypeError},+ prelude::*,+};-use super::{cache_error, facade::FacadeGuard, native::NativeResponseCache, request::duration};+use super::{+ cache_error, config::project_redis_semantic, embedder::PythonEmbedder, facade::FacadeGuard,+ native::NativeResponseCache, request::duration,+};#[pyclass(frozen, name = "_CacheTestHandle")]pub(crate) struct CacheTestHandle {diff --cc litellm-rust/crates/python-bridge/src/cache/native.rsindex 8cd77fa8eb0,b23038dee65..182010fab02--- a/litellm-rust/crates/python-bridge/src/cache/native.rs+++ b/litellm-rust/crates/python-bridge/src/cache/native.rs@@@ -1,9 -1,8 +1,9 @@@use std::{sync::Arc, time::Duration};-use litellm_cache::{CacheCodec, CacheConnectionResult, Error};+use litellm_cache::{CacheCodec, CacheConnectionResult, Error, ExactCacheContext};use litellm_cache_memory::InMemoryCache;- use litellm_cache_redis::RedisCache;+ use litellm_cache_redis::{RedisCache, RedisTopology};+use litellm_cache_redis_semantic::{RedisSemanticCache, RedisSemanticConfig};use litellm_cache_response::{CacheEntry, PartialHits, ResponseCache, ResponseCacheCodec, ResponseCacheRequest, WriteBuffer,};@@@ -85,6 -69,13 +87,13 @@@ impl NativeResponseCache}}+ pub fn topology(&self) -> Option<&RedisTopology> {+ match self {- Self::Memory(_) => None,++ Self::Memory(_) | Self::RedisSemantic(_) => None,+ Self::Redis { cache, .. } => Some(cache.backend().topology()),+ }+ }+pub fn capacity(&self) -> Option<usize> {match self {Self::Memory(cache) => Some(cache.backend().max_size_in_memory()),diff --cc tests/test_litellm_rust/test_cache.pyindex 73a6321011b,3903ef65daa..87e9d76ccb4--- a/tests/test_litellm_rust/test_cache.py+++ b/tests/test_litellm_rust/test_cache.py@@@ -1,10 -1,8 +1,11 @@@import asyncioimport contextvarsimport gc+import hashlibimport json+ import os+import math+import osimport threadingimport timeimport weakref@@@ -22,16 -18,11 +23,17 @@@ import rediimport litellmfrom litellm.caching.caching import Cache, disable_cache, enable_cache, update_cachefrom litellm.caching.in_memory_cache import InMemoryCache+ from litellm.caching.redis_cluster_cache import RedisClusterCache+from litellm.caching.redis_semantic_cache import RedisSemanticCachefrom 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.isolation import rebound+_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@@@ -406,479 -405,62 +416,540 @@@ async def test_redis_facade_buffers_natclient.close()+ async def test_redis_cluster_facade_serves_multi_slot_batches_and_scoped_flush_natively(+ cluster_nodes: tuple[tuple[str, int], ...],+ ) -> None:+ startup_nodes: Final = [{"host": host, "port": port} for host, port in cluster_nodes]+ url: Final = f"redis://{cluster_nodes[0][0]}:{cluster_nodes[0][1]}"+ with rebound(litellm, "default_redis_ttl", 60):+ facade: Final = Cache(type=LiteLLMCacheType.REDIS, redis_startup_nodes=startup_nodes, namespace="parity")+ assert type(facade.cache) is RedisClusterCache+ with pytest.raises(TypeError, match="types must match"):+ _native._CacheTestHandle.redis(url, namespace="parity")._bind_facade(facade)+ _native._CacheTestHandle.redis(url, namespace="parity", startup_nodes=list(cluster_nodes))._bind_facade(facade)+ resolver: Final = _native._CacheTestResolver(SimpleNamespace(cache=facade))+ assert resolver.resolve().kind == "native"++ manager: Final = facade.cache.redis_client.nodes_manager+ with rebound(manager, "connection_kwargs", {**manager.connection_kwargs, "db": 1}):+ assert resolver.resolve().kind == "python_callback"+ with rebound(facade.cache, "redis_kwargs", {**facade.cache.redis_kwargs, "startup_nodes": startup_nodes[:1]}):+ assert resolver.resolve().kind == "python_callback"+ binding: Final = resolver.resolve()+ assert binding.kind == "native"++ client: Final = redis.RedisCluster(startup_nodes=[redis.cluster.ClusterNode(*node) for node in cluster_nodes])+ keys: Final = tuple(f"slot-{index}" for index in range(12))+ slots: Final = {client.keyslot(f"parity:{key}") for key in keys}+ assert len(slots) > 1, slots+ requests: Final = [request(key) for key in keys]+ values: Final = [{"index": index} for index in range(len(keys))]+ await binding.async_store_batch(requests, values)+ client.set("parity:slot-3", "not a cache entry")+ client.set("parity:slot-7", json.dumps({"timestamp": time.time(), "response": {"index": 7, "python": True}}))++ batch: Final = await binding.async_lookup_batch(requests)+ assert batch == {+ "values": [+ None if index == 3 else {"index": 7, "python": True} if index == 7 else value+ for index, value in enumerate(values)+ ],+ "missing_indices": [3],+ }+ assert facade.cache.get_cache("parity:slot-0")["response"] == {"index": 0}+ assert (await facade.cache.async_get_cache("parity:slot-11"))["response"] == {"index": 11}+ assert facade.cache.redis_client.mget_nonatomic([f"parity:{key}" for key in keys[:2]]) == [+ client.get("parity:slot-0"),+ client.get("parity:slot-1"),+ ]++ await binding.async_store({**request("pinned"), "ttl_seconds": 12.0}, {"pinned": True})+ assert 0 < client.ttl("parity:pinned") <= 12+ client.set("unscoped", "stays")++ await binding.async_flush()++ remaining: Final = tuple(sorted(key for node in client.get_primaries() for key in client.keys("parity:*", target_nodes=node)))+ assert remaining == (), remaining+ assert client.get("unscoped") == b"stays"+ client.delete("unscoped")+ client.close()+ facade.cache.redis_client.close()+++++PARAPHRASE_MARKER: Final = " (paraphrase)"+SEMANTIC_EMBEDDING_MODEL: Final = "semantic-test/deterministic"+SEMANTIC_INDEX_PREFIX: Final = "litellm_test_semantic_"+++def _normalized(vector: list[float]) -> list[float]:+ norm: Final = math.sqrt(sum(component * component for component in vector))+ return [component / norm for component in vector]+++def _base_embedding(prompt: str) -> list[float]:+ digest: Final = hashlib.sha256(prompt.encode("utf-8")).digest()+ return _normalized([float(digest[index] + 1) for index in range(8)])+++def _semantic_embedding(prompt: str) -> list[float]:+ if PARAPHRASE_MARKER not in prompt:+ return _base_embedding(prompt)+ base: Final = _base_embedding(prompt.replace(PARAPHRASE_MARKER, "").strip())+ pivot: Final = min(range(8), key=lambda index: abs(base[index]))+ direction: Final = _normalized(+ [+ (1.0 - base[pivot] * base[pivot]) if index == pivot else -base[index] * base[pivot]+ for index in range(8)+ ]+ )+ # Rotating an orthogonal unit direction by 0.329 produces ~0.05 cosine distance+ return _normalized([base[index] + 0.329 * direction[index] for index in range(8)])+++class DeterministicEmbedding(litellm.CustomLLM):+ def __init__(self) -> None:+ self.calls: list[dict[str, object]] = []++ def _respond(+ self,+ model: str,+ input: object,+ model_response: EmbeddingResponse,+ ) -> EmbeddingResponse:+ texts: Final = cast(list[object], input if isinstance(input, list) else [input])+ self.calls.append({"model": model, "input": texts})+ model_response.model = model+ model_response.data = [+ {"object": "embedding", "index": index, "embedding": _semantic_embedding(str(text))}+ for index, text in enumerate(texts)+ ]+ return model_response++ def embedding(+ self,+ model: str,+ input: list[object],+ model_response: EmbeddingResponse,+ print_verbose: Callable[..., object],+ logging_obj: object,+ optional_params: dict[str, object],+ api_key: object = None,+ api_base: object = None,+ timeout: object = None,+ litellm_params: object = None,+ ) -> EmbeddingResponse:+ return self._respond(model, input, model_response)++ async def aembedding(+ self,+ model: str,+ input: list[object],+ model_response: EmbeddingResponse,+ print_verbose: Callable[..., object],+ logging_obj: object,+ optional_params: dict[str, object],+ api_key: object = None,+ api_base: object = None,+ timeout: object = None,+ litellm_params: object = None,+ ) -> EmbeddingResponse:+ return self._respond(model, input, model_response)+++def semantic_embedding() -> Generator[DeterministicEmbedding]:+ handler: Final = DeterministicEmbedding()+ with ExitStack() as stack:+ stack.enter_context(+ rebound(+ litellm,+ "custom_provider_map",+ [+ *litellm.custom_provider_map,+ cast(+ CustomLLMItem,+ {"provider": "semantic-test", "custom_handler": handler},+ ),+ ],+ )+ )+ stack.enter_context(+ rebound(+ litellm,+ "_custom_providers", # pyright: ignore[reportPrivateUsage] # no public provider-registration hook+ [*litellm._custom_providers, "semantic-test"], # pyright: ignore[reportPrivateUsage] # no public provider-registration hook+ )+ )+ stack.enter_context(+ rebound(litellm, "provider_list", [*litellm.provider_list, "semantic-test"])+ )+ yield handler+++def redis_stack() -> Generator[tuple[str, str]]:+ url: Final = os.environ.get("LITELLM_REDIS_STACK_URL")+ if url is None:+ pytest.skip("LITELLM_REDIS_STACK_URL is not set")+ index: Final = f"{SEMANTIC_INDEX_PREFIX}{uuid4().hex}"+ yield url, index+ client: Final = redis.Redis.from_url(url)+ try:+ client.execute_command("FT.DROPINDEX", index, "DD") # pyright: ignore[reportUnknownMemberType] # redis-py leaves execute_command partially unknown+ except redis.RedisError:+ pass+ client.close()+++def semantic_request(key: str, prompt: str, **extra: object) -> dict[str, object]:+ return {+ "key": {"preset": key},+ "messages": [{"role": "user", "content": prompt}],+ **extra,+ }+++def semantic_messages(prompt: str) -> list[dict[str, object]]:+ return [{"role": "user", "content": prompt}]+++def semantic_entry_id(prompt: str, tag: str) -> str:+ return hashlib.sha256(f"{prompt}litellm_cache_key{tag}".encode()).hexdigest()+++def semantic_facade(url: str, index: str, *, similarity_threshold: float = 0.8) -> Cache:+ facade: Final = Cache(+ type=LiteLLMCacheType.REDIS_SEMANTIC,+ redis_url=url,+ similarity_threshold=similarity_threshold,+ redis_semantic_cache_embedding_model=SEMANTIC_EMBEDDING_MODEL,+ redis_semantic_cache_index_name=index,+ )+ _CacheTestHandle.redis_semantic(facade.cache)._bind_facade(facade)+ return facade+++def test_redis_semantic_constructor_identity_and_provenance(+ redis_stack: tuple[str, str], semantic_embedding: DeterministicEmbedding+) -> None:+ url, index = redis_stack+ facade: Final = semantic_facade(url, index)+ backend: Final = cast(RedisSemanticCache, facade.cache)+ assert backend.__class__.__module__ == "litellm.caching.redis_semantic_cache"+ assert type(backend) is RedisSemanticCache+ assert backend._redis_url == url # pyright: ignore[reportPrivateUsage] # provenance check needs the projected config+ assert backend._index_name == index # pyright: ignore[reportPrivateUsage] # provenance check needs the projected config+ assert backend.similarity_threshold == 0.8+ assert backend.embedding_model == SEMANTIC_EMBEDDING_MODEL+ handle: Final = cast(object, getattr(facade, "_native_cache_handle"))+ assert isinstance(handle, _CacheTestHandle)+ assert handle.backend == "redis_semantic"+ binding: Final = _CacheTestResolver(SimpleNamespace(cache=facade)).resolve()+ assert binding.kind == "native"+++def test_redis_semantic_native_and_python_sync_entries_share_one_layout(+ redis_stack: tuple[str, str], semantic_embedding: DeterministicEmbedding+) -> None:+ url, index = redis_stack+ facade: Final = semantic_facade(url, index)+ binding: Final = _CacheTestResolver(SimpleNamespace(cache=facade)).resolve()+ client: Final = redis.Redis.from_url(url)+ response: Final = {"choices": [{"text": "paris"}], "usage": {"total_tokens": 2}}++ binding.store(semantic_request("geo", "what is the capital of france"), response)++ native_hash_key: Final = f"{index}:{semantic_entry_id('what is the capital of france', 'geo')}"+ stored: Final = client.hgetall(native_hash_key)+ assert set(stored) == {+ b"entry_id",+ b"prompt",+ b"response",+ b"prompt_vector",+ b"inserted_at",+ b"updated_at",+ b"litellm_cache_key",+ }, stored+ assert stored[b"entry_id"].decode() == native_hash_key.split(":", 1)[1]+ assert stored[b"prompt"] == b"what is the capital of france"+ assert stored[b"litellm_cache_key"] == b"geo"+ assert len(stored[b"prompt_vector"]) == 32+ decoded: Final = cast(dict[str, object], json.loads(stored[b"response"]))+ assert decoded["response"] == response+ assert (+ cast(RedisSemanticCache, facade.cache).get_cache( # pyright: ignore[reportUnknownMemberType] # **kwargs stays unknown on the backend class+ "geo", messages=semantic_messages("what is the capital of france")+ )+ == decoded+ )+ assert semantic_embedding.calls == [+ {"model": "deterministic", "input": ["what is the capital of france"]},+ {"model": "deterministic", "input": ["what is the capital of france"]},+ {"model": "deterministic", "input": ["dimension test"]},+ ]++ cast(RedisSemanticCache, facade.cache).set_cache( # pyright: ignore[reportUnknownMemberType] # **kwargs stays unknown on the backend class+ "math",+ json.dumps({"timestamp": 1700000000.0, "response": {"answer": 42}}),+ messages=semantic_messages("what is 6 times 7"),+ )+ python_hash_key: Final = f"{index}:{semantic_entry_id('what is 6 times 7', 'math')}"+ assert json.loads(cast(bytes, client.hget(python_hash_key, "response"))) == {+ "timestamp": 1700000000.0,+ "response": {"answer": 42},+ }+ assert binding.lookup(semantic_request("math", "what is 6 times 7")) == {"answer": 42}+ client.close()+++async def test_redis_semantic_async_paths_and_store_batch_share_one_layout(+ redis_stack: tuple[str, str], semantic_embedding: DeterministicEmbedding+) -> None:+ url, index = redis_stack+ facade: Final = semantic_facade(url, index)+ binding: Final = _CacheTestResolver(SimpleNamespace(cache=facade)).resolve()+ client: Final = redis.Redis.from_url(url)++ await binding.async_store(+ semantic_request("async", "name a primary color"), {"answer": "blue"}+ )+ hash_key: Final = f"{index}:{semantic_entry_id('name a primary color', 'async')}"+ decoded: Final = cast(dict[str, object], json.loads(cast(bytes, client.hget(hash_key, "response"))))+ python_read: Final = await cast(RedisSemanticCache, facade.cache).async_get_cache( # pyright: ignore[reportUnknownMemberType] # **kwargs stays unknown on the backend class+ "async", messages=semantic_messages("name a primary color")+ )+ assert python_read == decoded++ await binding.async_store_batch(+ [+ semantic_request("batch-one", "first batch prompt"),+ semantic_request("batch-two", "second batch prompt"),+ ],+ [{"answer": 1}, {"answer": 2}],+ )+ expected: Final = {+ key: json.loads(+ cast(bytes, client.hget(f"{index}:{semantic_entry_id(prompt, key)}", "response"))+ )+ for key, prompt in (+ ("batch-one", "first batch prompt"),+ ("batch-two", "second batch prompt"),+ )+ }+ for key, prompt in (+ ("batch-one", "first batch prompt"),+ ("batch-two", "second batch prompt"),+ ):+ assert cast(RedisSemanticCache, facade.cache).get_cache( # pyright: ignore[reportUnknownMemberType] # **kwargs stays unknown on the backend class+ key, messages=semantic_messages(prompt)+ ) == expected[key], key++ cast(RedisSemanticCache, facade.cache).set_cache( # pyright: ignore[reportUnknownMemberType] # **kwargs stays unknown on the backend class+ "async-python",+ json.dumps({"timestamp": 1700000000.0, "response": {"answer": "python"}}),+ messages=semantic_messages("python written prompt"),+ )+ assert await binding.async_lookup(+ semantic_request("async-python", "python written prompt")+ ) == {"answer": "python"}+ client.close()+++def test_redis_semantic_similarity_tag_and_threshold_boundaries(+ redis_stack: tuple[str, str], semantic_embedding: DeterministicEmbedding+) -> None:+ url, index = redis_stack+ facade: Final = semantic_facade(url, index)+ binding: Final = _CacheTestResolver(SimpleNamespace(cache=facade)).resolve()++ binding.store(semantic_request("sim", "tell me a joke"), {"answer": "haha"})+ paraphrase: Final = f"tell me a joke{PARAPHRASE_MARKER}"+ assert binding.lookup(semantic_request("sim", paraphrase)) == {"answer": "haha"}+ assert binding.lookup(semantic_request("sim", "an unrelated question about spreadsheets")) is None+ assert binding.lookup(semantic_request("other-key", "tell me a joke")) is None++ strict: Final = semantic_facade(url, index, similarity_threshold=0.99)+ strict_binding: Final = _CacheTestResolver(SimpleNamespace(cache=strict)).resolve()+ assert strict_binding.lookup(semantic_request("sim", paraphrase)) is None+ assert strict_binding.lookup(semantic_request("sim", "tell me a joke")) == {"answer": "haha"}+++def test_redis_semantic_ttl_is_written_only_when_requested(+ redis_stack: tuple[str, str], semantic_embedding: DeterministicEmbedding+) -> None:+ url, index = redis_stack+ facade: Final = semantic_facade(url, index)+ binding: Final = _CacheTestResolver(SimpleNamespace(cache=facade)).resolve()+ client: Final = redis.Redis.from_url(url)++ binding.store(+ {**semantic_request("ttl", "ttl prompt"), "ttl_seconds": 12.0}, {"answer": 1}+ )+ expiring: Final = f"{index}:{semantic_entry_id('ttl prompt', 'ttl')}"+ assert 0 < client.ttl(expiring) <= 12++ binding.store(semantic_request("ttl-none", "untimed prompt"), {"answer": 2})+ persistent: Final = f"{index}:{semantic_entry_id('untimed prompt', 'ttl-none')}"+ assert client.ttl(persistent) == -1++ binding.store(+ {**semantic_request("ttl-fraction", "fractional prompt"), "ttl_seconds": 1.5},+ {"answer": 3},+ )+ fractional: Final = f"{index}:{semantic_entry_id('fractional prompt', 'ttl-fraction')}"+ assert client.ttl(fractional) == 2+ client.close()+++def test_redis_semantic_malformed_response_is_a_miss_for_both_readers(+ redis_stack: tuple[str, str], semantic_embedding: DeterministicEmbedding+) -> None:+ url, index = redis_stack+ facade: Final = semantic_facade(url, index)+ binding: Final = _CacheTestResolver(SimpleNamespace(cache=facade)).resolve()+ client: Final = redis.Redis.from_url(url)++ binding.store(semantic_request("bad", "corrupt me"), {"answer": 1})+ hash_key: Final = f"{index}:{semantic_entry_id('corrupt me', 'bad')}"+ client.hset(hash_key, "response", b"{not json")+ assert binding.lookup(semantic_request("bad", "corrupt me")) is None+ assert (+ cast(RedisSemanticCache, facade.cache).get_cache( # pyright: ignore[reportUnknownMemberType] # **kwargs stays unknown on the backend class+ "bad", messages=semantic_messages("corrupt me")+ )+ is None+ )+ client.close()+++async def test_redis_semantic_unsupported_operations_raise_not_implemented(+ redis_stack: tuple[str, str], semantic_embedding: DeterministicEmbedding+) -> None:+ url, index = redis_stack+ facade: Final = semantic_facade(url, index)+ binding: Final = _CacheTestResolver(SimpleNamespace(cache=facade)).resolve()++ with pytest.raises(NotImplementedError):+ binding.lookup_batch([semantic_request("batch", "prompt one")])+ with pytest.raises(NotImplementedError):+ await binding.async_lookup_batch([semantic_request("batch", "prompt one")])+ with pytest.raises(NotImplementedError):+ await binding.async_flush()+ with pytest.raises(NotImplementedError):+ await binding.ping()+++def test_redis_semantic_requests_without_prompt_are_noops(+ redis_stack: tuple[str, str], semantic_embedding: DeterministicEmbedding+) -> None:+ url, index = redis_stack+ facade: Final = semantic_facade(url, index)+ binding: Final = _CacheTestResolver(SimpleNamespace(cache=facade)).resolve()+ client: Final = redis.Redis.from_url(url)++ binding.store(request("plain"), {"answer": 1})+ assert binding.lookup(request("plain")) is None+ assert semantic_embedding.calls == []+ assert client.keys(f"{index}:*") == []+ client.close()+++def test_redis_semantic_scope_overrides_the_tag_and_isolates_entries(+ redis_stack: tuple[str, str], semantic_embedding: DeterministicEmbedding+) -> None:+ url, index = redis_stack+ facade: Final = semantic_facade(url, index)+ binding: Final = _CacheTestResolver(SimpleNamespace(cache=facade)).resolve()+ client: Final = redis.Redis.from_url(url)++ scoped: Final = {**semantic_request("scoped", "scoped prompt"), "scope": "team-a"}+ binding.store(scoped, {"answer": "kept"})+ hash_key: Final = f"{index}:{semantic_entry_id('scoped prompt', 'team-a')}"+ assert client.hget(hash_key, "litellm_cache_key") == b"team-a"+ assert binding.lookup(scoped) == {"answer": "kept"}+ assert binding.lookup(semantic_request("scoped", "scoped prompt")) is None+ assert binding.lookup({**scoped, "scope": "team-b"}) is None+ client.close()+++def test_redis_semantic_configuration_drift_falls_back_to_python(+ redis_stack: tuple[str, str],+ semantic_embedding: DeterministicEmbedding,+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ url, index = redis_stack+ facade: Final = semantic_facade(url, index)+ resolver: Final = _CacheTestResolver(SimpleNamespace(cache=facade))+ assert resolver.resolve().kind == "native"++ with rebound(facade.cache, "similarity_threshold", 0.5):+ assert resolver.resolve().kind == "python_callback"+ with rebound(facade, "semantic_cache_scope", "end_user"):+ assert resolver.resolve().kind == "python_callback"+ with rebound(facade.cache, "embedding_model", "other-model"):+ assert resolver.resolve().kind == "python_callback"+ with rebound(facade.cache, "_index_name", "other-index"):+ assert resolver.resolve().kind == "python_callback"+ with rebound(facade.cache, "CACHE_KEY_FIELD_NAME", "other-field"):+ assert resolver.resolve().kind == "python_callback"++ def patched_embedding(self: object, prompt: str, metadata: object = None) -> list[float]:+ return _semantic_embedding(prompt)++ monkeypatch.setattr(RedisSemanticCache, "_get_embedding", patched_embedding)+ assert resolver.resolve().kind == "python_callback"+++def test_redis_semantic_handle_rejects_wrong_backends(+ redis_stack: tuple[str, str], semantic_embedding: DeterministicEmbedding+) -> None:+ url, index = redis_stack++ class CustomSemanticCache(RedisSemanticCache):+ pass++ with pytest.raises(TypeError, match="built-in RedisSemanticCache"):+ _CacheTestHandle.redis_semantic(object())+ with pytest.raises(TypeError, match="built-in RedisSemanticCache"):+ _CacheTestHandle.redis_semantic(+ CustomSemanticCache(+ redis_url=url,+ similarity_threshold=0.8,+ embedding_model=SEMANTIC_EMBEDDING_MODEL,+ index_name=f"{index}_subclass",+ )+ )++ facade: Final = semantic_facade(url, index)+ with pytest.raises(TypeError, match="backend types must match"):+ _CacheTestHandle.redis(url)._bind_facade(facade)++ subclassed_facade: Final = Cache(+ type=LiteLLMCacheType.REDIS_SEMANTIC,+ redis_url=url,+ similarity_threshold=0.8,+ redis_semantic_cache_embedding_model=SEMANTIC_EMBEDDING_MODEL,+ redis_semantic_cache_index_name=index,+ )+ subclassed_facade.cache = CustomSemanticCache( # pyright: ignore[reportAttributeAccessIssue] # facade backend slot is not declared++ redis_url=url,+ similarity_threshold=0.8,+ embedding_model=SEMANTIC_EMBEDDING_MODEL,+ index_name=index,+ )+ with pytest.raises(TypeError):+ _CacheTestHandle.redis_semantic(+ subclassed_facade.cache+ )._bind_facade(subclassed_facade)++ replacement_facade: Final = Cache(+ type=LiteLLMCacheType.REDIS_SEMANTIC,+ redis_url=url,+ similarity_threshold=0.8,+ redis_semantic_cache_embedding_model=SEMANTIC_EMBEDDING_MODEL,+ redis_semantic_cache_index_name=index,+ )+ with pytest.raises(TypeError, match="must be the native embedder"):+ _CacheTestHandle.redis_semantic(facade.cache)._bind_facade(replacement_facade)