Vector store
A VectorStore keeps texts and their metadata with their vectors and finds the ones nearest a query vector. An Index embeds texts and queries, and hands the vectors to its store. Freyja ships InMemoryVectors, the default, and the freyja-sqlx crate keeps vectors in Postgres with pgvector. Write your own to keep them in another vector database, such as Qdrant, Faiss or Redis.
A store gets everything else from Index: embedding in batches of 100, dimensions, and into_tool, the search tool an agent calls, with the query's tokens charged to a Budget or Cost.
The trait
pub trait VectorStore: Send + Sync {
fn insert(&self, entries: Vec<(Document, Vec<f32>)>) -> StorageFuture<'_, ()>;
fn search<'a>(&'a self, vector: &'a [f32], k: usize) -> StorageFuture<'a, Vec<Hit>>;
fn len(&self) -> StorageFuture<'_, usize>;
fn is_empty(&self) -> StorageFuture<'_, bool> {
Box::pin(async move { Ok(self.len().await? == 0) })
}
fn delete<'a>(&'a self, filter: &'a Value) -> StorageFuture<'a, usize> {
Box::pin(async { Err("this vector store cannot delete".into()) })
}
fn search_filtered<'a>(
&'a self,
vector: &'a [f32],
k: usize,
filter: &'a Value,
) -> StorageFuture<'a, Vec<Hit>> {
Box::pin(async { Err("this vector store cannot filter a search".into()) })
}
}
It uses the future and the error a Storage does, so a failure is any boxed standard error. Index wraps it in Error::InvalidRequest under the endpoint name vector store.
Every method takes &self, because one index is shared by its clones and by the tool into_tool makes. A store that holds state of its own locks it. A store over a database client usually needs no lock, since the client is shared already.
Freyja forwards VectorStore through Arc<T>, so a caller can keep a handle to the store they pass to Index::with_store.
insert
Keeps each Document with its vector. A Document is a text and its metadata, a serde_json::Value that is an empty object unless the caller set one, such as {"source": "handbook.md"}. Keep the metadata exactly as given, nested objects and all, since search must return it unchanged. A JSON column, or the JSON text in a string field, does it. Index::add calls insert once per batch of up to 100 texts, and Index::insert once per text. A text added twice is kept twice, so a store needs no notion of identity. Store a batch whole or not at all when the database allows it, since add reports an error for the batch.
search
Returns the k texts nearest vector, nearest first, each as a Hit with its metadata and its cosine similarity, from -1.0 for the opposite direction to 1.0 for the same one. A database that reports cosine distance instead converts with 1.0 - distance. Keeping the score in that range is what lets an application set one threshold that works on any store.
k is never 0, because Index answers that itself. A k past the number of texts returns every text. An empty store returns an empty list, not an error, so the agent reads that nothing matched.
A database that filters after an approximate index scan can come back short when many vectors belong to something else, such as another collection in the same table. Ask it for an exact count of k, as PgVectorStore does with pgvector's iterative scans.
len
How many texts the store holds. Index::len and Index::is_empty call it, and nothing on the search path does, so a slow count costs nothing per query.
delete
Deletes every text whose metadata holds, for each top-level key of filter, an equal value, and returns how many it deleted. So {"source": "a.md"} deletes every chunk of a.md, and a second key narrows it further. A filter that is not an object with at least one key is an error and deletes nothing. Delete in one statement when the database allows it, so a delete is whole or not at all. Index::delete calls it.
The default refuses with an error, so a store written before delete existed keeps compiling, and a store that keeps the default cannot delete. InMemoryVectors and PgVectorStore implement it. The conformance check below does not test delete, so test it yourself if you implement it.
search_filtered
Like search, over only the texts whose metadata matches filter the same way delete matches it. So {"user": "ana"} returns the k nearest of Ana's texts, and fewer only when she has fewer. A filter that is not an object with at least one key is an error. Filter inside the database query rather than after it, since filtering the k nearest afterwards can leave none. Index::search_filtered and a tool made with into_tool(...).filter(...) call it.
The default refuses with an error, like delete, so a store without it keeps compiling. InMemoryVectors and PgVectorStore implement it, and the conformance check does not test it.
Example: a store over a vector database
VectorDb stands in for the database's own client.
use freyja::{Document, Hit, StorageFuture, VectorStore};
use serde_json::Value;
// The database's own client: Qdrant, Faiss, Redis. Each point carries a
// payload, which is where the metadata goes.
trait VectorDb: Send + Sync {
fn upsert(&self, points: Vec<(String, Value, Vec<f32>)>) -> Result<(), String>;
fn nearest(&self, vector: &[f32], k: usize) -> Result<Vec<(String, Value, f32)>, String>;
fn count(&self) -> Result<usize, String>;
}
struct DbStore<D> {
db: D,
}
impl<D: VectorDb> VectorStore for DbStore<D> {
fn insert(&self, entries: Vec<(Document, Vec<f32>)>) -> StorageFuture<'_, ()> {
let points = entries
.into_iter()
.map(|(document, vector)| (document.text, document.metadata, vector))
.collect();
Box::pin(async move { Ok(self.db.upsert(points)?) })
}
fn search<'a>(&'a self, vector: &'a [f32], k: usize) -> StorageFuture<'a, Vec<Hit>> {
Box::pin(async move {
Ok(self
.db
.nearest(vector, k)?
.into_iter()
.map(|(text, metadata, distance)| Hit::new(text, 1.0 - distance).metadata(metadata))
.collect())
})
}
fn len(&self) -> StorageFuture<'_, usize> {
Box::pin(async move { Ok(self.db.count()?) })
}
}
nearest here reports cosine distance, so the store turns it into similarity. A client that blocks, as Faiss's bindings do, runs each call on a blocking thread.
The store goes in an index like any other, and the index provides the tool:
let index = Index::with_store(client, "text-embedding-3-small", DbStore { db });
let agent = Agent::new(model).tool(index.into_tool("search_docs", "Searches the docs", 3));
A store must be searched with the model that filled it, or the distances mean nothing. The store does not record the model, so a crate that keeps several collections names each after its model, or documents the rule.
Testing it
freyja::testing::vector_store_conformance checks the rules on this page: an empty store, len after two inserts, nearest first, k, scores that are cosine similarity, and metadata that comes back unchanged and with its own text. make returns a new, empty store each time it is called, holding vectors of 3 numbers:
#[tokio::test]
async fn keeps_the_vector_store_rules() {
freyja::testing::vector_store_conformance(|| DbStore { db: TestDb::default() }).await;
}
A store over a shared database gives each call its own collection, the way freyja-sqlx does:
let run = std::process::id();
let next = AtomicUsize::new(0);
freyja::testing::vector_store_conformance(|| {
let id = next.fetch_add(1, Ordering::Relaxed);
PgVectorStore::new(pool.clone(), format!("{run}-{id}"))
})
.await;
When a tool fits better
A store answers one question: the nearest texts to a vector. A search that needs more, such as filters on metadata, a keyword search mixed in, or results that are not plain text, is a tool of your own, which decides its own arguments and output.