-
Notifications
You must be signed in to change notification settings - Fork 0
feat(valkey): implement Valkey vector store integration #1
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,22 @@ | ||
| [package] | ||
| name = "rig-valkey" | ||
| version = "0.1.0" | ||
| edition = { workspace = true } | ||
| license = "MIT" | ||
| readme = "README.md" | ||
| description = "Valkey vector store integration for Rig." | ||
| repository = "https://github.com/0xPlaygrounds/rig" | ||
|
|
||
| [lints] | ||
| workspace = true | ||
|
|
||
| [dependencies] | ||
| nanoid = { workspace = true } | ||
| redis = { workspace = true, features = ["tokio-comp", "aio"] } | ||
| rig-core = { path = "../rig-core", version = "0.37.0", default-features = false } | ||
| serde = { workspace = true, features = ["derive"] } | ||
| serde_json = { workspace = true } | ||
| tracing = { workspace = true } | ||
|
|
||
| [dev-dependencies] | ||
| anyhow = { workspace = true } | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,7 @@ | ||
| Copyright (c) 2024, Playgrounds Analytics Inc. | ||
|
|
||
| Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: | ||
|
|
||
| The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. | ||
|
|
||
| THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,44 @@ | ||
| # rig-valkey | ||
|
|
||
| Valkey vector store integration for [Rig](https://github.com/0xPlaygrounds/rig). | ||
|
|
||
| This crate implements the `VectorStoreIndex` and `InsertDocuments` traits from | ||
| `rig-core`, backed by Valkey's vector search capabilities (`FT.SEARCH` with KNN). | ||
|
|
||
| ## Requirements | ||
|
|
||
| - Valkey 8.0+ with the [valkey-search](https://github.com/valkey-io/valkey-search) module loaded | ||
| - A pre-existing FT index on the target keyspace | ||
|
|
||
| ## Usage | ||
|
|
||
| ```rust,no_run | ||
| use rig_valkey::{ValkeyVectorStore, ValkeyVectorStoreConfig}; | ||
| use rig_core::{providers::openai, vector_store::VectorStoreIndex, client::EmbeddingsClient}; | ||
| use rig_core::vector_store::request::VectorSearchRequest; | ||
|
|
||
| #[tokio::main] | ||
| async fn main() -> anyhow::Result<()> { | ||
| let redis_client = redis::Client::open("redis://127.0.0.1:6379")?; | ||
| let connection = redis_client.get_multiplexed_async_connection().await?; | ||
|
|
||
| let openai_client = openai::Client::from_env()?; | ||
| let model = openai_client.embedding_model(openai::TEXT_EMBEDDING_ADA_002); | ||
|
|
||
| let store = ValkeyVectorStore::new( | ||
| connection, | ||
| model, | ||
| "my_index", | ||
| ValkeyVectorStoreConfig::default(), | ||
| ).await?; | ||
|
|
||
| let req = VectorSearchRequest::builder() | ||
| .query("What is machine learning?") | ||
| .samples(5) | ||
| .build(); | ||
|
|
||
| let results = store.top_n::<serde_json::Value>(req).await?; | ||
| println!("{results:?}"); | ||
| Ok(()) | ||
| } | ||
| ``` | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 🔵 Add a 'Limitations' section noting |
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,139 @@ | ||
| //! Valkey FT.SEARCH filter expression builder. | ||
| //! | ||
| //! [`ValkeySearchFilter`] implements the [`SearchFilter`] trait, producing | ||
| //! filter strings compatible with Valkey's `FT.SEARCH` query syntax. | ||
|
|
||
| use rig_core::vector_store::request::SearchFilter; | ||
| use serde::Serialize; | ||
|
|
||
| /// A filter expression for Valkey FT.SEARCH queries. | ||
| /// | ||
| /// Wraps a string in Valkey's query filter syntax. Combine filters with | ||
| /// [`SearchFilter::and`] and [`SearchFilter::or`]. | ||
| #[derive(Clone, Debug, Serialize)] | ||
| pub struct ValkeySearchFilter(String); | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 🔴 Removing |
||
|
|
||
| impl ValkeySearchFilter { | ||
| /// Returns the raw filter expression string for use in FT.SEARCH queries. | ||
| pub fn as_str(&self) -> &str { | ||
| &self.0 | ||
| } | ||
| } | ||
|
|
||
| impl SearchFilter for ValkeySearchFilter { | ||
| type Value = serde_json::Value; | ||
|
|
||
| fn eq(key: impl AsRef<str>, value: Self::Value) -> Self { | ||
| let key = sanitize_field_name(key.as_ref()); | ||
| let expr = match &value { | ||
| serde_json::Value::Number(n) => { | ||
| format!("@{key}:[{n} {n}]") | ||
| } | ||
| serde_json::Value::String(s) => { | ||
| let escaped = escape_tag_value(s); | ||
| format!("@{key}:{{{escaped}}}") | ||
| } | ||
| other => { | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 🟡 Non-String/non-Number JSON values are stringified via |
||
| let s = other.to_string(); | ||
| let escaped = escape_tag_value(&s); | ||
| format!("@{key}:{{{escaped}}}") | ||
| } | ||
| }; | ||
| Self(expr) | ||
| } | ||
|
|
||
| fn gt(key: impl AsRef<str>, value: Self::Value) -> Self { | ||
| let key = sanitize_field_name(key.as_ref()); | ||
| let n = value_to_numeric(&value); | ||
| Self(format!("@{key}:[({n} +inf]")) | ||
| } | ||
|
|
||
| fn lt(key: impl AsRef<str>, value: Self::Value) -> Self { | ||
| let key = sanitize_field_name(key.as_ref()); | ||
| let n = value_to_numeric(&value); | ||
| Self(format!("@{key}:[-inf ({n}]")) | ||
| } | ||
|
|
||
| fn and(self, rhs: Self) -> Self { | ||
| Self(format!("({}) ({})", self.0, rhs.0)) | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 🔵 |
||
| } | ||
|
|
||
| fn or(self, rhs: Self) -> Self { | ||
| Self(format!("({}) | ({})", self.0, rhs.0)) | ||
| } | ||
| } | ||
|
|
||
| /// Strips any character that isn't alphanumeric or underscore from field names, | ||
| /// preventing query injection via the `@field:` syntax. | ||
| fn sanitize_field_name(key: &str) -> String { | ||
| key.chars() | ||
| .filter(|c| c.is_ascii_alphanumeric() || *c == '_') | ||
| .collect() | ||
| } | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 🟡 |
||
|
|
||
| /// Escapes special characters in TAG field values for FT.SEARCH syntax. | ||
| fn escape_tag_value(s: &str) -> String { | ||
| let mut out = String::with_capacity(s.len()); | ||
| for c in s.chars() { | ||
| if matches!( | ||
| c, | ||
| '\\' | ',' | ||
| | '.' | ||
| | '<' | ||
| | '>' | ||
| | '{' | ||
| | '}' | ||
| | '[' | ||
| | ']' | ||
| | '"' | ||
| | '\'' | ||
| | ':' | ||
| | ';' | ||
| | '!' | ||
| | '@' | ||
| | '#' | ||
| | '$' | ||
| | '%' | ||
| | '^' | ||
| | '&' | ||
| | '*' | ||
| | '(' | ||
| | ')' | ||
| | '-' | ||
| | '+' | ||
| | '=' | ||
| | '~' | ||
| | '|' | ||
| | '/' | ||
| | '?' | ||
| | ' ' | ||
| ) { | ||
| out.push('\\'); | ||
| } | ||
| out.push(c); | ||
| } | ||
| out | ||
| } | ||
|
|
||
| /// Extracts a validated numeric string from a JSON value for range queries. | ||
| /// Non-numeric strings are treated as 0 to prevent injection. | ||
| fn value_to_numeric(value: &serde_json::Value) -> String { | ||
| match value { | ||
| serde_json::Value::Number(n) => n.to_string(), | ||
| serde_json::Value::String(s) => s.parse::<f64>().map_or("0".to_string(), |n| n.to_string()), | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 🔴 Non-parseable strings, bools, nulls, arrays, objects all collapse to |
||
| _ => "0".to_string(), | ||
| } | ||
| } | ||
|
|
||
| impl From<rig_core::vector_store::request::Filter<serde_json::Value>> for ValkeySearchFilter { | ||
| fn from(value: rig_core::vector_store::request::Filter<serde_json::Value>) -> Self { | ||
| use rig_core::vector_store::request::Filter; | ||
| match value { | ||
| Filter::Eq(k, v) => ValkeySearchFilter::eq(k, v), | ||
| Filter::Gt(k, v) => ValkeySearchFilter::gt(k, v), | ||
| Filter::Lt(k, v) => ValkeySearchFilter::lt(k, v), | ||
| Filter::And(l, r) => Self::from(*l).and(Self::from(*r)), | ||
| Filter::Or(l, r) => Self::from(*l).or(Self::from(*r)), | ||
| } | ||
| } | ||
| } | ||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🔵
rig-valkey = 0.1.0(this file) andrig-core = 0.37.0dep at L16 — other companion crates track the 0.x.6 series and align rig-core versions accordingly. Confirm release-train alignment.