Skip to main content

Retrieval

Retrieval gives an agent facts it was never trained on, such as your help docs or a customer's order history. You add the texts to an Index once. When a question comes in, the index finds the texts closest to it in meaning, and the agent answers from those. It is built on embeddings.

An index​

Index::new takes an embedder and an embedding model. add embeds the texts and keeps them, and search returns the k closest to a query, closest first.

use freyja::{Client, EndpointPreset, Index};

let embedder = Client::from_env(EndpointPreset::OpenAi)?;
let index = Index::new(embedder, "text-embedding-3-small");

index.add([
"Refunds take five business days.",
"We ship to the EU and the US.",
"Support is open 9 to 5 on weekdays.",
]).await?;

for hit in index.search("how long until I get my money back?", 2).await? {
println!("{:.2} {}", hit.score, hit.text);
}

Each Hit holds the text as it was added, its metadata, and a score, the cosine similarity to the query, where 1.0 means the same direction.

add sends texts 100 to a request, which Gemini requires, and returns the input tokens the provider reports. If a request fails, the texts from the requests before it stay in the index.

Splitting documents​

Split long documents before adding them. One embedding covers one text, so a page about refunds, shipping and support hours matches all three questions weakly. A paragraph each matches one strongly.

Freyja has no splitter of its own, because add takes any iterator of strings and any splitter plugs in. The text-splitter crate is a good one. It splits at the largest boundary that fits, paragraphs before sentences before words, and its Markdown and code modes keep headings and functions whole. It is a separate crate, so add it yourself:

text-splitter = { version = "0.33", features = ["markdown"] }
use text_splitter::MarkdownSplitter;

let handbook = std::fs::read_to_string("handbook.md")?;
index.add(MarkdownSplitter::new(1000).chunks(&handbook)).await?;

1000 is the most characters in a chunk. A few hundred to a couple of thousand characters suits most embedding models.

Metadata​

A chunk on its own does not say where it came from. A Document carries a text and metadata, a JSON value kept with the text and returned with every hit for it. The metadata is never embedded, so it does not change what a search finds.

use freyja::Document;
use serde_json::json;

let splitter = MarkdownSplitter::new(1000);
let chunks = splitter.chunks(&handbook);
index
.add(chunks.map(|text| Document::new(text).metadata(json!({"source": "handbook.md"}))))
.await?;

let hits = index.search("how long do refunds take?", 3).await?;
println!("{} (from {})", hits[0].text, hits[0].metadata["source"]);

Plain strings and Documents mix freely, and a plain string gets an empty object. Put whatever your app needs to act on a hit in the metadata: a file name, a URL to link to, a page number, a document id to find its chunks again.

Deleting​

delete deletes every text whose metadata matches a filter, and returns how many it deleted. Each top-level key of the filter must hold an equal value, so {"source": "handbook.md"} deletes every chunk of that file, and a second key narrows it further.

use serde_json::json;

let deleted = index.delete(&json!({"source": "handbook.md"})).await?;
println!("deleted {deleted} chunks");

A filter that is not an object with at least one key is an error and deletes nothing. InMemoryVectors and PgVectorStore can delete, and a store of your own returns an error until it implements delete. To replace a changed file, see Update and delete documents.

Searching some of the texts​

search_filtered searches only the texts whose metadata matches a filter, matched the way delete matches. One index can then hold every user's documents, and each search stays inside one user's.

use serde_json::json;

let hits = index
.search_filtered("how long do refunds take?", 3, &json!({"user": "ana"}))
.await?;

InMemoryVectors and PgVectorStore can filter, and a store of your own returns an error until it implements search_filtered. In Postgres the HNSW index keeps scanning until it finds k matching texts, up to pgvector's hnsw.max_scan_tuples of 20,000 by default, so a filter that matches very few of many texts can come back short.

Giving the search to an agent​

into_tool(name, description, k) turns the index into a tool. The model calls it with a query and reads back the k closest texts, numbered, each followed by its metadata, so it can cite a source:

1. Refunds are paid within five days.
page: 4
source: handbook.md

Keys come in alphabetical order, the same from every store. The model sees every key, so keep values it should not read, such as internal ids, out of the metadata of a searched index.

use freyja::Agent;

let agent = Agent::new(Client::from_env(EndpointPreset::Anthropic)?)
.system("Answer from the help docs. Search them before answering.")
.tool(index.clone().into_tool("search_docs", "Searches the help docs", 3));

let run = agent.ask("Do you ship to Canada?").await?;

The model decides when to search and what to search for, so it can rephrase the question or search twice. A system prompt that says to search first makes it more reliable.

filter on the tool searches only matching texts. The model never sees the filter and cannot change it, so it keeps an agent inside one user's documents:

let tool = index
.clone()
.into_tool("search_notes", "Searches this user's notes", 3)
.filter(json!({"user": user_id}));

The index and the tool share their texts, so texts added after into_tool are searched too. The tokens spent embedding each query count in the run's usage, and are charged to a Budget or a Cost in the context.

The example chats with Claude and embeds with OpenAI. The two never need to match, but the index must embed every text and every query with the same model, since vectors from different models do not compare.

Keeping an index across restarts​

Index::new keeps its vectors in memory, so the index is empty again after a restart. Index::with_store keeps them in a VectorStore instead, and starts from whatever the store already holds, so a later process searches without paying to embed again.

The freyja-sqlx crate's PgVectorStore keeps them in Postgres with the pgvector extension, 0.8 or later:

[dependencies]
freyja-sqlx = { version = "0.7", features = ["pgvector"] }
sqlx = { version = "0.9", features = ["runtime-tokio"] }
use freyja_sqlx::PgVectorStore;

let pool = sqlx::PgPool::connect(&database_url).await?;
PgVectorStore::migrate(&pool, 1536).await?;

let store = PgVectorStore::new(pool.clone(), "help-pages");
let index = Index::with_store(embedder, "text-embedding-3-small", store);
if index.is_empty().await? {
index.add(pages).await?;
}

migrate enables the extension, and creates one freyja_vectors table with an HNSW index for vectors of the size it is given, the 1536 numbers text-embedding-3-small returns here, or the dimensions you set. It refuses a table made earlier for another size, since the index holds one size only. Collections share the table, told apart by the name given to new, and a search returns k texts of its own collection however many others there are. clear deletes one collection.

A collection must be searched with the model that filled it. The store does not record the model, so name a collection after its model, or keep one model per database.

For another vector database, implement VectorStore. See Vector store.

insert keeps a text with a vector you made earlier, and embeds nothing. search_vector searches with a vector you already have, for a query embedded elsewhere with the same model. Both reach the store, so they are async, like len and is_empty.

Shorter vectors​

dimensions(n) embeds every text and query at n numbers. Set it before adding anything, since vectors of different lengths do not compare.

let index = Index::new(embedder, "gemini-embedding-001").dimensions(256);

Scale​

In memory, search compares the query with every text. That is quick for thousands of texts and slow for millions. PgVectorStore searches through an HNSW index instead, which stays quick at millions. A keyword search mixed in, or a filter beyond equal values, such as a date range, is a tool of your own, and Hit::new(text, score) turns its results into the same Hits an Index returns. See Tool calling.

Testing​

Embedder is the trait Client implements for embeddings. Implement it for a test double, and an index runs without a network. Build its answer with Embeddings::new.

use freyja::{EmbedFuture, EmbedRequest, Embedder, Embeddings};

struct Fixed;

impl Embedder for Fixed {
fn embed<'a>(&'a self, request: &'a EmbedRequest) -> EmbedFuture<'a> {
Box::pin(async move {
Ok(Embeddings::new(vec![vec![1.0, 0.0]; request.inputs.len()], None))
})
}
}

let index = Index::new(Fixed, "test");

See also​

  • Embeddings, for Client::embed and cosine_similarity
  • Testing, for scripting the agent's model
  • Vector store, for keeping vectors in another database