Skip to content

The fastest, litest AI Gateway. Rust core with Python SDK. Call 100+ LLM APIs in OpenAI (or native) format with cost tracking, guardrails, load balancing, and logging [Bedrock, Azure, OpenAI, Anthropic, OpenAI, VertexAI, vLLM, Nvidia NIM]

Merge origin/main into litellm_valkey_semantic_native_cache

Yujong Leecc6ca5ee0455
diff --cc litellm-rust/crates/python-bridge/src/cache/config.rs
index 169bb5accda,5fe36f6c1fa..92df6a8b78d
--- a/litellm-rust/crates/python-bridge/src/cache/config.rs
+++ b/litellm-rust/crates/python-bridge/src/cache/config.rs
@@@ -73,14 -75,17 +75,25 @@@ pub(super) struct RedisCacheConfig
pub(super) connection: RedisConnectionConfig,
}
+ 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;
+
+#[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) enum CacheBackendConfig {
Memory(MemoryCacheConfig),
Redis(Box<RedisCacheConfig>),
@@@ -316,71 -311,128 +338,193 @@@ fn project_redis
}))
}
+ #[inline(never)]
+ fn project_standalone_client<'py>(
+ client: &Bound<'py, PyAny>,
+ ) -> PyResult<Result<RedisClientProjection<'py>, UnsupportedCacheConfig>> {
+ let pool = client.getattr("connection_pool")?;
+ if !instance_class_is(&pool, "redis.connection", "ConnectionPool")? {
+ return Ok(Err(UnsupportedCacheConfig::RedisConnection));
+ }
+ let resolved = pool.getattr("connection_kwargs")?.cast_into::<PyDict>()?;
+ if has_value(&resolved, "redis_connect_func")? {
+ return Ok(Err(UnsupportedCacheConfig::RedisCredentials));
+ }
+ let connection_class = resolved
+ .get_item("connection_class")?
+ .unwrap_or(pool.getattr("connection_class")?);
+ let tls = if class_is(&connection_class, "redis.connection", "Connection")? {
+ None
+ } else if class_is(&connection_class, "redis.connection", "SSLConnection")? {
+ Some(project_tls(&resolved)?)
+ } else {
+ return Ok(Err(UnsupportedCacheConfig::RedisConnection));
+ };
+ Ok(Ok(RedisClientProjection {
+ topology: RedisTopology::Standalone,
+ host: required_string(&resolved, "host")?,
+ port: port(required_i64(&resolved, "port")?)?,
+ pool_size: pool.getattr("max_connections")?.extract::<usize>()?,
+ resolved,
+ tls,
+ }))
+ }
+
+ #[inline(never)]
+ fn project_cluster_client<'py>(
- source: &Bound<'py, PyDict>,
++ source: &Bound<'_, PyDict>,
+ client: &Bound<'py, PyAny>,
+ ) -> PyResult<Result<RedisClientProjection<'py>, UnsupportedCacheConfig>> {
+ let Some(startup_nodes) = startup_nodes(source)? else {
+ return Ok(Err(UnsupportedCacheConfig::RedisTopology));
+ };
+ if !instance_class_is(client, "redis.cluster", "RedisCluster")? {
+ return Ok(Err(UnsupportedCacheConfig::RedisConnection));
+ }
+ let nodes = client.getattr("nodes_manager")?;
+ if !class_is(
+ &nodes.getattr("connection_pool_class")?,
+ "redis.connection",
+ "ConnectionPool",
+ )? {
+ return Ok(Err(UnsupportedCacheConfig::RedisConnection));
+ }
+ let resolved = nodes.getattr("connection_kwargs")?.cast_into::<PyDict>()?;
+ if let Some(connect) = resolved.get_item("redis_connect_func")?
+ && !connect.is_none()
+ {
+ let own_hook = connect
+ .getattr("__self__")
+ .is_ok_and(|owner| owner.is(client))
+ && connect
+ .getattr("__func__")
+ .and_then(|function| Ok(function.is(&client.get_type().getattr("on_connect")?)))
+ .unwrap_or(false);
+ if !own_hook {
+ return Ok(Err(UnsupportedCacheConfig::RedisCredentials));
+ }
+ }
+ let tls = if optional_bool(&resolved, "ssl")?.unwrap_or(false) {
+ Some(project_tls(&resolved)?)
+ } else {
+ None
+ };
+ let first = &startup_nodes[0];
+ Ok(Ok(RedisClientProjection {
+ host: first.host.clone(),
+ port: first.port,
+ pool_size: optional_i64(&resolved, "max_connections")?
+ .map(|value| {
+ usize::try_from(value).map_err(|_| PyValueError::new_err("invalid Redis pool size"))
+ })
+ .transpose()?
+ .unwrap_or(REDIS_PY_DEFAULT_MAX_CONNECTIONS),
+ topology: RedisTopology::Cluster { startup_nodes },
+ resolved,
+ tls,
+ }))
+ }
+
+ #[inline(never)]
+ fn startup_nodes(source: &Bound<'_, PyDict>) -> PyResult<Option<Vec<RedisNode>>> {
+ let Some(nodes) = source.get_item("startup_nodes")? else {
+ return Ok(None);
+ };
+ let Ok(nodes) = nodes.cast_into::<PyList>() else {
+ return Ok(None);
+ };
+ if nodes.is_empty() {
+ return Ok(None);
+ }
+ let mut parsed = Vec::with_capacity(nodes.len());
+ for node in nodes.iter() {
+ let Ok(node) = node.cast_into::<PyDict>() else {
+ return Ok(None);
+ };
+ if node.len() != 2 || !has_value(&node, "host")? || !has_value(&node, "port")? {
+ return Ok(None);
+ }
+ let (Ok(host), Ok(port)) = (
+ required_string(&node, "host"),
+ required_i64(&node, "port").and_then(port),
+ ) else {
+ return Ok(None);
+ };
+ parsed.push(RedisNode { host, port });
+ }
+ Ok(Some(parsed))
+ }
+
+ #[inline(never)]
+ fn port(value: i64) -> PyResult<u16> {
+ u16::try_from(value).map_err(|_| PyValueError::new_err("invalid Redis port"))
+ }
+
+#[inline(never)]
+fn project_valkey_semantic(
+ backend: &Bound<'_, PyAny>,
+) -> PyResult<Result<ValkeySemanticCacheConfig, UnsupportedCacheConfig>> {
+ let client = backend.getattr("sync_client")?;
+ let pool = client.getattr("connection_pool")?;
+ let Ok((resolved, is_tls)) = project_connection_pool(&pool)? else {
+ return Ok(Err(UnsupportedCacheConfig::RedisConnection));
+ };
+ for key in ["credential_provider", "redis_connect_func"] {
+ if has_value(&resolved, key)? {
+ return Ok(Err(UnsupportedCacheConfig::RedisCredentials));
+ }
+ }
+ if is_tls {
+ return Ok(Err(UnsupportedCacheConfig::RedisConnection));
+ }
+ let connection = RedisConnectionConfig {
+ host: required_string(&resolved, "host")?,
+ port: u16::try_from(required_i64(&resolved, "port")?)
+ .map_err(|_| PyValueError::new_err("invalid Redis port"))?,
+ database: optional_i64(&resolved, "db")?.unwrap_or(0),
+ username: optional_dict_string(&resolved, "username")?,
+ password: optional_dict_string(&resolved, "password")?,
+ protocol: RedisProtocol::Resp2,
+ pool_size: pool.getattr("max_connections")?.extract::<usize>()?,
+ read_timeout: None,
+ connect_timeout: None,
+ socket_keepalive: None,
+ health_check_interval: Duration::ZERO,
+ client_name: None,
+ tls: None,
+ };
+ if connection.host.is_empty() {
+ return Ok(Err(UnsupportedCacheConfig::RedisConnection));
+ }
+ Ok(Ok(ValkeySemanticCacheConfig {
+ similarity_threshold: backend.getattr("similarity_threshold")?.extract()?,
+ index_name: backend.getattr("index_name")?.extract()?,
+ embedding_model: backend.getattr("embedding_model")?.extract()?,
+ connection,
+ }))
+}
+
+#[inline(never)]
+fn project_connection_pool<'py>(
+ pool: &Bound<'py, PyAny>,
+) -> PyResult<Result<(Bound<'py, PyDict>, bool), UnsupportedCacheConfig>> {
+ if !instance_class_is(pool, "redis.connection", "ConnectionPool")? {
+ return Ok(Err(UnsupportedCacheConfig::RedisConnection));
+ }
+ let resolved = pool.getattr("connection_kwargs")?.cast_into::<PyDict>()?;
+ let connection_class = resolved
+ .get_item("connection_class")?
+ .unwrap_or(pool.getattr("connection_class")?);
+ let is_tls = if class_is(&connection_class, "redis.connection", "Connection")? {
+ false
+ } else if class_is(&connection_class, "redis.connection", "SSLConnection")? {
+ true
+ } else {
+ return Ok(Err(UnsupportedCacheConfig::RedisConnection));
+ };
+ Ok(Ok((resolved, is_tls)))
+}
+
#[inline(never)]
fn project_tls(values: &Bound<'_, PyDict>) -> PyResult<RedisTlsConfig> {
Ok(RedisTlsConfig {
diff --cc litellm-rust/crates/python-bridge/src/cache/facade.rs
index eb76d22097d,a9ce2ae7756..6474fe7c787
--- a/litellm-rust/crates/python-bridge/src/cache/facade.rs
+++ b/litellm-rust/crates/python-bridge/src/cache/facade.rs
@@@ -29,9 -30,28 +30,31 @@@ struct RedisPoolGuard
reference: Py<PyAny>,
connection_class: Py<PyAny>,
connection_kwargs: Py<PyAny>,
- max_connections: usize,
+ max_connections: Option<usize>,
+ attributes: RedisPoolAttributes,
}
++#[derive(Clone, Copy)]
+ struct RedisPoolAttributes {
+ pool: &'static str,
+ connection_class: &'static str,
+ max_connections: Option<&'static str>,
+ }
+
+ const STANDALONE_POOL: RedisPoolAttributes = RedisPoolAttributes {
+ pool: "connection_pool",
+ connection_class: "connection_class",
+ max_connections: Some("max_connections"),
+ };
+
+ const CLUSTER_POOL: RedisPoolAttributes = RedisPoolAttributes {
+ pool: "nodes_manager",
+ connection_class: "connection_pool_class",
+ max_connections: None,
+ };
+
++const VALKEY_POOL: RedisPoolAttributes = STANDALONE_POOL;
++
pub(super) struct FacadeGuard {
outer: ObjectGuard,
backend: ObjectGuard,
@@@ -141,32 -158,40 +164,47 @@@ impl ObjectGuard
}
impl RedisPoolGuard {
- fn capture(backend: &Bound<'_, PyAny>, client_name: &str) -> PyResult<Self> {
- let pool = backend.getattr(client_name)?.getattr("connection_pool")?;
- fn capture(backend: &Bound<'_, PyAny>, attributes: RedisPoolAttributes) -> PyResult<Self> {
- let pool = backend.getattr("redis_client")?.getattr(attributes.pool)?;
++ fn capture(
++ backend: &Bound<'_, PyAny>,
++ client_name: &str,
++ attributes: RedisPoolAttributes,
++ ) -> PyResult<Self> {
++ let pool = backend.getattr(client_name)?.getattr(attributes.pool)?;
Ok(Self {
reference: pool.clone().unbind(),
- connection_class: pool.getattr("connection_class")?.unbind(),
+ connection_class: pool.getattr(attributes.connection_class)?.unbind(),
connection_kwargs: pool
.getattr("connection_kwargs")?
.call_method0("copy")?
.unbind(),
- max_connections: pool.getattr("max_connections")?.extract::<usize>()?,
- max_connections: Self::max_connections(&pool, &attributes)?,
++ max_connections: attributes
++ .max_connections
++ .map(|name| pool.getattr(name)?.extract::<usize>())
++ .transpose()?,
+ attributes,
})
}
- fn max_connections(
- pool: &Bound<'_, PyAny>,
- attributes: &RedisPoolAttributes,
- ) -> PyResult<Option<usize>> {
- attributes
- .max_connections
- .map(|name| pool.getattr(name)?.extract::<usize>())
- .transpose()
- }
-
- fn matches(&self, py: Python<'_>, backend: &Bound<'_, PyAny>) -> PyResult<bool> {
+ fn matches(
+ &self,
+ py: Python<'_>,
+ backend: &Bound<'_, PyAny>,
+ client_name: &str,
+ ) -> PyResult<bool> {
- let pool = backend.getattr(client_name)?.getattr("connection_pool")?;
+ let pool = backend
- .getattr("redis_client")?
++ .getattr(client_name)?
+ .getattr(self.attributes.pool)?;
Ok(self.reference.bind(py).is(&pool)
&& self
.connection_class
.bind(py)
- .is(&pool.getattr("connection_class")?)
- && self.max_connections == pool.getattr("max_connections")?.extract::<usize>()?
+ .is(&pool.getattr(self.attributes.connection_class)?)
- && self.max_connections == Self::max_connections(&pool, &self.attributes)?
++ && self.max_connections
++ == self
++ .attributes
++ .max_connections
++ .map(|name| pool.getattr(name)?.extract::<usize>())
++ .transpose()?
&& self
.connection_kwargs
.bind(py)
@@@ -193,14 -218,15 +231,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"),
- "valkey-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", true) => (
+ "litellm.caching.redis_cluster_cache",
+ "RedisClusterCache",
+ "redis",
+ ),
++ ("valkey-semantic", false) => (
+ "litellm.caching.valkey_semantic_cache",
+ "ValkeySemanticCache",
+ "valkey-semantic",
+ ),
_ => unreachable!(),
};
let backend = facade.getattr("cache")?;
@@@ -244,32 -270,13 +288,36 @@@
"max_size_per_item",
"redis_kwargs",
"redis_flush_size",
+ "similarity_threshold",
+ "embedding_model",
+ "index_name",
+ "embedding_max_input_tokens",
+ "embedding_timeout",
],
)?,
- redis_pool: (kind == "redis" || kind == "valkey-semantic")
- .then(|| {
- RedisPoolGuard::capture(
- &backend,
- if kind == "redis" {
- "redis_client"
- } else {
- "sync_client"
- },
- )
- })
- .transpose()?,
- redis_client_name: (kind == "redis" || kind == "valkey-semantic").then_some(
- if kind == "redis" {
- "redis_client"
- } else {
- "sync_client"
- },
- ),
+ redis_pool: match (kind, cluster) {
- ("redis", false) => Some(RedisPoolGuard::capture(&backend, STANDALONE_POOL)?),
- ("redis", true) => Some(RedisPoolGuard::capture(&backend, CLUSTER_POOL)?),
++ ("redis", false) => Some(RedisPoolGuard::capture(
++ &backend,
++ "redis_client",
++ STANDALONE_POOL,
++ )?),
++ ("redis", true) => Some(RedisPoolGuard::capture(
++ &backend,
++ "redis_client",
++ CLUSTER_POOL,
++ )?),
++ ("valkey-semantic", false) => Some(RedisPoolGuard::capture(
++ &backend,
++ "sync_client",
++ VALKEY_POOL,
++ )?),
++ _ => None,
++ },
++ redis_client_name: match (kind, cluster) {
++ ("redis", _) => Some("redis_client"),
++ ("valkey-semantic", false) => Some("sync_client"),
+ _ => None,
+ },
})
}
diff --cc litellm-rust/crates/python-bridge/src/cache/native.rs
index e7c875579fd,b23038dee65..3380a914c41
--- a/litellm-rust/crates/python-bridge/src/cache/native.rs
+++ b/litellm-rust/crates/python-bridge/src/cache/native.rs
@@@ -1,55 -1,13 +1,55 @@@
use std::{sync::Arc, time::Duration};
-use litellm_cache::{CacheCodec, CacheConnectionResult, Error};
+use litellm_cache::{
+ CacheCodec, CacheConnectionResult, Error, ExactCacheContext, SemanticCacheContext,
+};
use litellm_cache_memory::InMemoryCache;
- use litellm_cache_redis::RedisCache;
+ use litellm_cache_redis::{RedisCache, RedisTopology};
use litellm_cache_response::{
- CacheEntry, PartialHits, ResponseCache, ResponseCacheCodec, ResponseCacheRequest, WriteBuffer,
+ CacheEntry, CacheKeyField, PartialHits, ResponseCache, ResponseCacheCodec,
+ ResponseCacheRequest, WriteBuffer,
};
+use litellm_cache_valkey_semantic::{ValkeySemanticCache, ValkeySemanticConfig};
use serde_json::Value;
+use super::{embedder::PythonEmbedder, request::NativeRequest};
+
+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 Some(value) = request
+ .metadata
+ .as_ref()
+ .and_then(|metadata| metadata.get(name))
+ 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 {
Memory(Arc<ResponseCache<InMemoryCache<CacheEntry>>>),
@@@ -178,6 -69,13 +180,13 @@@ impl NativeResponseCache
}
}
+ pub fn topology(&self) -> Option<&RedisTopology> {
+ match self {
- Self::Memory(_) => None,
++ Self::Memory(_) | Self::ValkeySemantic { .. } => 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()),