mirror of
https://github.com/BerriAI/litellm.git
synced 2026-12-02 01:28:38 +00:00
* refactor(rust): align the cache crates with Python and activate every backend The cache port had drifted: lifecycle and Redis-only operations sat on `BaseCache`, counters were pinned to `f64`, each semantic backend defined its own embedder and prompt handling, and only the in-memory backend could be selected natively. - Split `disconnect` and `test_connection` out of `BaseCache` into optional capabilities, implemented only where the Python class defines them, and give every Redis-only operation its own capability trait. - Decouple counters from the stored value type, so one backend can serve both responses and counters as Python's `RedisCache` does. - Share one `Embedder` and prompt contract in `litellm_cache::semantic`, and make the Redis and Valkey semantic backends generic over their codec. - Port the Python operations that were missing: `async_refresh_ttl`, `async_rpush_and_trim`, `async_set_cache_pipeline_with_ttls`, the DualCache pipeline, sadd, bulk delete and TTL reads, and the semantic-similarity write-back. - Take the HTTP client from the host pool in the GCS, S3 and Azure backends. - Activate all nine backends through the Rust catalog, whose rules all stay `PYTHON_ONLY`, and route the `Cache` facade's storage calls to the native runtime when one is selected. - Give every crate the same layout, move all tests to `tests/` on rstest, and add the shared `litellm-cache-testing` contract suite. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * fix: freeze native cache request kwargs and batch entries for type discipline Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> * fix: declare semantic lookup methods in the native stub Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> * refactor(rust): align the cache crates with Python and activate every backend The cache port had drifted: lifecycle and Redis-only operations sat on `BaseCache`, counters were pinned to `f64`, each semantic backend defined its own embedder and prompt handling, and only the in-memory backend could be selected natively. - Split `disconnect` and `test_connection` out of `BaseCache` into optional capabilities, implemented only where the Python class defines them, and give every Redis-only operation its own capability trait. - Decouple counters from the stored value type, so one backend can serve both responses and counters as Python's `RedisCache` does. - Share one `Embedder` and prompt contract in `litellm_cache::semantic`, and make the Redis and Valkey semantic backends generic over their codec. - Port the Python operations that were missing: `async_refresh_ttl`, `async_rpush_and_trim`, `async_set_cache_pipeline_with_ttls`, the DualCache pipeline, sadd, bulk delete and TTL reads, and the semantic-similarity write-back. - Take the HTTP client from the host pool in the GCS, S3 and Azure backends. - Activate all nine backends through the Rust catalog, whose rules all stay `PYTHON_ONLY`, and route the `Cache` facade's storage calls to the native runtime when one is selected. - Give every crate the same layout, move all tests to `tests/` on rstest, and add the shared `litellm-cache-testing` contract suite. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * fix: freeze native cache request kwargs and batch entries for type discipline Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> * fix: declare semantic lookup methods in the native stub Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> * test(rust): opt the native Messages and tokenizer suites into Rust explicitly #42517 made the Messages, token counter and tokenizer routes Python-only, so tests/test_litellm_rust silently exercised the Python path or failed outright. Each suite now prepends a RUST_OPT_IN rule for its route, keeping native coverage without changing the shipped default. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(rust): pop one at a time in the Redis 6 lpop pipeline and drop explanatory comments Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> --------- Co-authored-by: Yujong Lee <yujong@berri.ai> Co-authored-by: Claude Opus 5 <noreply@anthropic.com> Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
100 lines
3.1 KiB
Rust
100 lines
3.1 KiB
Rust
use std::sync::{Arc, Mutex};
|
|
|
|
use litellm_cache::Error;
|
|
use litellm_cache_redis::connection::ConnectionRef;
|
|
|
|
use crate::search::value_text;
|
|
|
|
/// The valkey-search index one cache writes to, with the dimension it was last ensured for.
|
|
#[derive(Clone)]
|
|
pub(crate) struct IndexState {
|
|
pub(crate) name: String,
|
|
pub(crate) prefix: String,
|
|
pub(crate) dimension: Arc<Mutex<Option<usize>>>,
|
|
pub(crate) similarity_threshold: f64,
|
|
}
|
|
|
|
/// `_ensure_index_sync` / `_ensure_index_async`: create the TAG + HNSW index once per dimension,
|
|
/// and accept an existing index unless it reports a different dimension.
|
|
pub(crate) fn ensure_index(
|
|
connection: &mut ConnectionRef<'_>,
|
|
index: &IndexState,
|
|
dimension: usize,
|
|
) -> Result<(), Error> {
|
|
if index
|
|
.dimension
|
|
.lock()
|
|
.map_err(|_| Error::Unavailable)?
|
|
.is_some_and(|existing| existing == dimension)
|
|
{
|
|
return Ok(());
|
|
}
|
|
let create = redis::cmd("FT.CREATE")
|
|
.arg(&index.name)
|
|
.arg("ON")
|
|
.arg("HASH")
|
|
.arg("PREFIX")
|
|
.arg(1)
|
|
.arg(&index.prefix)
|
|
.arg("SCHEMA")
|
|
.arg("litellm_cache_key")
|
|
.arg("TAG")
|
|
.arg("embedding")
|
|
.arg("VECTOR")
|
|
.arg("HNSW")
|
|
.arg(6)
|
|
.arg("TYPE")
|
|
.arg("FLOAT32")
|
|
.arg("DIM")
|
|
.arg(dimension)
|
|
.arg("DISTANCE_METRIC")
|
|
.arg("COSINE")
|
|
.query::<String>(connection)
|
|
.map(|_| ())
|
|
.map_err(|error| error.to_string());
|
|
if let Err(message) = create {
|
|
if !message.to_ascii_lowercase().contains("already exists") {
|
|
return Err(Error::Unavailable);
|
|
}
|
|
let info = redis::cmd("FT.INFO")
|
|
.arg(&index.name)
|
|
.query::<redis::Value>(connection)
|
|
.map_err(|_| Error::Unavailable)?;
|
|
if index_dimension_from_info(&info).is_some_and(|existing| existing != dimension) {
|
|
return Err(Error::Unavailable);
|
|
}
|
|
}
|
|
*index.dimension.lock().map_err(|_| Error::Unavailable)? = Some(dimension);
|
|
Ok(())
|
|
}
|
|
|
|
/// `_extract_index_dim`: flatten each attribute one level and read the value after
|
|
/// `dimensions`.
|
|
fn index_dimension_from_info(value: &redis::Value) -> Option<usize> {
|
|
let redis::Value::Array(values) = value else {
|
|
return None;
|
|
};
|
|
let attributes = values.windows(2).find_map(|pair| {
|
|
(value_text(&pair[0]).as_deref() == Some("attributes")).then_some(&pair[1])
|
|
})?;
|
|
let redis::Value::Array(fields) = attributes else {
|
|
return None;
|
|
};
|
|
fields.iter().find_map(|field| {
|
|
let redis::Value::Array(values) = field else {
|
|
return None;
|
|
};
|
|
let values = values
|
|
.iter()
|
|
.flat_map(|value| match value {
|
|
redis::Value::Array(values) => values.as_slice(),
|
|
_ => std::slice::from_ref(value),
|
|
})
|
|
.collect::<Vec<_>>();
|
|
values.windows(2).find_map(|pair| {
|
|
(value_text(pair[0]).as_deref() == Some("dimensions"))
|
|
.then(|| value_text(pair[1]).and_then(|value| value.parse().ok()))
|
|
.flatten()
|
|
})
|
|
})
|
|
}
|