Embedder
An Embedder turns text into vectors. Index uses one to embed the texts it stores and the queries it searches with, and a search tool of your own can use one to embed a query before asking a vector database. Client is an embedder for every provider with an embeddings endpoint. Write your own to embed in your process, with fastembed, candle or ONNX Runtime, or to reach an embedding service Freyja does not speak.
The trait
pub type EmbedFuture<'a> = Pin<Box<dyn Future<Output = Result<Embeddings, Error>> + Send + 'a>>;
pub trait Embedder: Send + Sync {
fn embed<'a>(&'a self, request: &'a EmbedRequest) -> EmbedFuture<'a>;
}
Index keeps its embedder as Arc<dyn Embedder>, and Freyja forwards Embedder through Arc<T>, so one embedder can serve an index and a tool at once.
embed
Embeds every input of the request and returns one vector per input, in the same order. Index pairs the vectors with its texts by position, so a missing vector silently drops a text, and a reordered one files a text under another text's vector. Index::add sends up to 100 inputs in one request.
The request carries three fields:
| Field | Meaning |
|---|---|
model | The embedding model to use. An embedder with one model can ignore it. |
inputs | The texts to embed, possibly many at once |
dimensions | The vector length the caller asked for, or None for the model's own |
Every vector from one embedder and model must have the same length, and a query must be embedded the same way as the texts it is compared with. An embedder that cannot produce the length in dimensions returns an error rather than a vector of another length, which would fail later inside a search, far from the cause.
Embeddings::new(vectors, usage) builds the result. Pass the token usage if the backend reports it, and None otherwise.
Errors are freyja::Error, as with Model, with the embedder's name in endpoint.
Example: an embedder in your process
Hashed makes a vector from the words of a text by hashing each word into one of a fixed number of slots. It is not a real model, since it knows nothing of meaning, but it has the shape of one: no network, a fixed length, and the same text always gives the same vector. A crate wrapping a local model replaces vector with a call into the model.
use freyja::{EmbedFuture, EmbedRequest, Embedder, Embeddings, Error};
use std::collections::hash_map::DefaultHasher;
use std::hash::{Hash, Hasher};
struct Hashed {
dimensions: usize,
}
impl Hashed {
fn vector(&self, text: &str) -> Vec<f32> {
let mut vector = vec![0.0; self.dimensions];
for word in text.split_whitespace() {
let mut hasher = DefaultHasher::new();
word.to_lowercase().hash(&mut hasher);
vector[hasher.finish() as usize % self.dimensions] += 1.0;
}
let length = vector.iter().map(|x| x * x).sum::<f32>().sqrt();
if length > 0.0 {
vector.iter_mut().for_each(|x| *x /= length);
}
vector
}
}
impl Embedder for Hashed {
fn embed<'a>(&'a self, request: &'a EmbedRequest) -> EmbedFuture<'a> {
Box::pin(async move {
if let Some(asked) = request.dimensions
&& asked as usize != self.dimensions
{
return Err(Error::InvalidRequest {
endpoint: "hashed".into(),
message: format!("this embedder makes {} dimensions, not {asked}", self.dimensions),
});
}
let vectors = request.inputs.iter().map(|text| self.vector(text)).collect();
Ok(Embeddings::new(vectors, None))
})
}
}
An Index takes it in place of a Client:
let index = Index::new(Hashed { dimensions: 256 }, "hashed");
index.add(["Refunds take five days.", "We ship to the EU and the US."]).await?;
let hits = index.search("how many days do refunds take", 1).await?;
A real local model does CPU or GPU work that does not await. Run it on a blocking thread, with tokio::task::spawn_blocking or your runtime's equivalent, and embed the inputs as one batch, which is much faster than one text at a time on most models.
Testing it
An embedder is tested by calling it. Check the count, the length and that the same text gives the same vector:
#[tokio::test]
async fn one_vector_per_input_in_order() {
let embedder = Hashed { dimensions: 64 };
let request = EmbedRequest::new("hashed", ["refunds take five days", "we ship to the EU"]);
let embeddings = embedder.embed(&request).await.unwrap();
assert_eq!(embeddings.vectors.len(), 2);
assert!(embeddings.vectors.iter().all(|v| v.len() == 64));
assert_eq!(embeddings.vectors[0], embedder.vector("refunds take five days"));
}
For a real model, also check that two texts with similar meaning score closer with cosine_similarity than two unrelated ones. That catches a model loaded with the wrong weights or the wrong pooling, which still returns vectors of the right length.
Stability
Embedder stays usable as dyn Embedder. A method added to it later comes with a default, so an implementation written today keeps compiling.
See also
- Embeddings for embedding with a
Client - Retrieval for
Index, which takes any embedder - Tool for a search over a vector database that uses an embedder