Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -160,6 +160,7 @@ rig-s3vectors = { path = "crates/rig-s3vectors", version = "0.2.6", optional = t
rig-scylladb = { path = "crates/rig-scylladb", version = "0.2.6", optional = true, default-features = false }
rig-sqlite = { path = "crates/rig-sqlite", version = "0.2.6", optional = true, default-features = false }
rig-surrealdb = { path = "crates/rig-surrealdb", version = "0.2.6", optional = true, default-features = false }
rig-valkey = { path = "crates/rig-valkey", version = "0.1.0", optional = true, default-features = false }
rig-vectorize = { path = "crates/rig-vectorize", version = "0.2.6", optional = true, default-features = false }
rig-vertexai = { path = "crates/rig-vertexai", version = "0.3.6", optional = true, default-features = false }

Expand Down Expand Up @@ -244,6 +245,7 @@ s3vectors = ["dep:rig-s3vectors"]
scylladb = ["dep:rig-scylladb"]
sqlite = ["dep:rig-sqlite"]
surrealdb = ["dep:rig-surrealdb"]
valkey = ["dep:rig-valkey"]
vectorize = ["dep:rig-vectorize"]
vertexai = ["dep:rig-vertexai"]
audio = ["rig-core/audio"]
Expand Down
22 changes: 22 additions & 0 deletions crates/rig-valkey/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
[package]
name = "rig-valkey"
version = "0.1.0"

Copy link
Copy Markdown

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) and rig-core = 0.37.0 dep at L16 — other companion crates track the 0.x.6 series and align rig-core versions accordingly. Confirm release-train alignment.

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 }
7 changes: 7 additions & 0 deletions crates/rig-valkey/LICENSE
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.
44 changes: 44 additions & 0 deletions crates/rig-valkey/README.md
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(())
}
```

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 Add a 'Limitations' section noting ValkeyVectorStore cannot currently be used with dynamic_context/dynamic_tools due to the missing Deserialize impl on ValkeySearchFilter (substantive issue: crates/rig-valkey/src/filter.rs:14). Until the custom sanitizing impl lands, this is the only blocker for Tool/VectorStoreIndexDyn use.

139 changes: 139 additions & 0 deletions crates/rig-valkey/src/filter.rs
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);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔴 Removing Deserialize from ValkeySearchFilter blocks both the VectorStoreIndexDyn blanket impl AND the Tool blanket impl in rig-core (both bound for<'de> Deserialize<'de> on the filter). Consequence: users cannot put ValkeyVectorStore behind dynamic_context() / dynamic_tools() in AgentBuilder. Ship a sanitizing custom Deserialize impl that re-runs sanitize_field_name/escape_tag_value on deserialized fields, or call out the limitation prominently in README.


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 => {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Non-String/non-Number JSON values are stringified via to_string() (yielding @active:{true}, @arr:{[1\,2]}). Either restrict Self::Value semantics in docs or return FilterError.

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))

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 and/or always wrap both sides in parens, producing ((a) (b)) chains. Valkey parses fine; just noisy in logs. Skip wrapping if the operand is already a single parenthesized group.

}

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()
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 sanitize_field_name silently produces "" for fully non-alphanumeric keys, which then yields @:{...} — a Valkey syntax error rather than an actionable error to the caller. Reject empty result with FilterError::Must.


/// 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()),

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔴 Non-parseable strings, bools, nulls, arrays, objects all collapse to "0" silently. lt("price", json!("abc")) becomes price < 0 with no error. Return FilterError::Expected instead of swallowing the type mismatch.

_ => "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)),
}
}
}
Loading