Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Embeddings

LangChainRust provides a unified Embeddings trait with multiple backends for generating text embedding vectors.

Supported Providers

ProviderStructDefault ModelDimensionFeature Gate
OpenAIOpenAIEmbeddingstext-embedding-ada-0021536always
DeepSeekDeepSeekEmbeddingsdeepseek-embedding1536always
QwenQwenEmbeddingstext-embedding-v11536always
CohereCohereEmbeddingsembed-english-v3.01024always
FastEmbedFastEmbedEmbeddingsBGESmallENV15384fastembed
BagOfWordsBagOfWordsEmbeddingslocal-bowconfigurablealways
MockMockEmbeddingsmock-embeddingsconfigurablealways

Embeddings Trait

#![allow(unused)]
fn main() {
#[async_trait]
pub trait Embeddings: Send + Sync {
    async fn embed_query(&self, text: &str) -> Result<Vec<f32>, EmbeddingError>;
    async fn embed_documents(&self, texts: &[&str]) -> Result<Vec<Vec<f32>>, EmbeddingError>;
    fn dimension(&self) -> usize;
    fn model_name(&self) -> &str;
}
}

OpenAI Embeddings

#![allow(unused)]
fn main() {
use langchainrust::{OpenAIEmbeddings, OpenAIEmbeddingsConfig};

// From environment (OPENAI_API_KEY)
let embedder = OpenAIEmbeddings::from_env_result()?;

// Explicit config
let embedder = OpenAIEmbeddings::new(
    OpenAIEmbeddingsConfig::new("sk-...")
        .with_model("text-embedding-3-small")
        .with_base_url("https://api.openai.com/v1"),
);

let vec = embedder.embed_query("What is Rust?").await?;
let vecs = embedder.embed_documents(&["doc1 text", "doc2 text"]).await?;
}

FastEmbed (Local ONNX)

#![allow(unused)]
fn main() {
use langchainrust::FastEmbedEmbeddings;
use fastembed::EmbeddingModel;

// Default model (BGESmallENV15, 384-dim)
let embedder = FastEmbedEmbeddings::default_model()?;

// Specific model
let embedder = FastEmbedEmbeddings::with_model(EmbeddingModel::BGESmallENV15)?;
let vec = embedder.embed_query("hello world").await?;
}

BagOfWords & Mock

#![allow(unused)]
fn main() {
use langchainrust::{BagOfWordsEmbeddings, MockEmbeddings};

// BagOfWords (no API needed, FNV-1a hash based)
let embedder = BagOfWordsEmbeddings::default_dim(); // 256-dim
let embedder = BagOfWordsEmbeddings::new(128);

// Mock (deterministic pseudo-random for testing)
let embedder = MockEmbeddings::new(1536);
}

Cosine Similarity

#![allow(unused)]
fn main() {
use langchainrust::cosine_similarity;

let sim = cosine_similarity(&vec_a, &vec_b)?;
// Returns f64 in range [-1.0, 1.0]
}