lc_embeddings/lib.rs
1#![warn(missing_docs)]
2// lc-embeddings/src/lib.rs
3//! Embedding model implementations for LangChainRust.
4//!
5//! Provides embedding generation via multiple backends:
6//! - OpenAI (`text-embedding-ada-002`, `text-embedding-3-small/large`)
7//! - DeepSeek
8//! - Qwen (Alibaba Cloud / DashScope)
9//! - Local: `BagOfWordsEmbeddings` (always available) and `LocalEmbeddings` (ONNX, feature-gated)
10//! - `MockEmbeddings` for testing
11//!
12//! Multimodal (image+text shared space) backends live behind
13//! [`VisionEmbeddings`]: Cohere Embed v4 and DashScope `multimodal-embedding-v1`.
14
15mod cohere;
16mod deepseek;
17mod local;
18mod mock;
19mod openai;
20pub mod openai_compat;
21mod qwen;
22mod retry;
23pub mod token_level;
24mod vision;
25mod vision_cohere;
26mod vision_qwen;
27
28#[cfg(test)]
29mod test_support;
30
31#[cfg(feature = "fastembed")]
32mod fastembed_emb;
33
34#[cfg(feature = "local-candle")]
35mod candle_emb;
36
37pub use cohere::{
38 CohereEmbedInputType, CohereEmbeddings, CohereEmbeddingsConfig, COHERE_EMBED_BASE_URL,
39 COHERE_EMBED_MODEL,
40};
41pub use deepseek::{DeepSeekEmbeddings, DeepSeekEmbeddingsConfig, DEEPSEEK_EMBED_MODEL};
42pub use local::BagOfWordsEmbeddings;
43// As of 1.0, `LocalEmbeddings` is not available without the `local-embeddings` feature (the
44// old fallback alias was removed); users must explicitly choose — `BagOfWordsEmbeddings` or
45// the ONNX version via the feature.
46#[cfg(feature = "local-embeddings")]
47pub use local::{LocalEmbeddings, LocalEmbeddingsBuilder};
48pub use mock::MockEmbeddings;
49pub use openai::{OpenAIEmbeddings, OpenAIEmbeddingsConfig};
50pub use qwen::{QwenEmbeddings, QwenEmbeddingsConfig, QWEN_EMBED_MODEL};
51pub use token_level::{
52 char_spans_to_byte_spans, LocalTokenLevelEmbeddings, TokenEmbedding, TokenLevelEmbeddings,
53 TokenSpan,
54};
55// B7 (v0.22.4): cross-modal vision embeddings — trait, mock, and the Cohere
56// Embed v4 / DashScope multimodal-embedding-v1 backends.
57pub use vision::{ImageInput, MockVisionEmbeddings, VisionEmbeddings};
58pub use vision_cohere::{
59 CohereVisionEmbeddings, CohereVisionEmbeddingsConfig, COHERE_VISION_DIMENSION,
60 COHERE_VISION_EMBED_MODEL,
61};
62pub use vision_qwen::{
63 QwenVisionEmbeddings, QwenVisionEmbeddingsConfig, QWEN_VISION_BASE_URL, QWEN_VISION_DIMENSION,
64 QWEN_VISION_EMBED_MODEL,
65};
66
67#[cfg(feature = "fastembed")]
68pub use fastembed_emb::FastEmbedEmbeddings;
69
70#[cfg(feature = "local-candle")]
71pub use candle_emb::CandleEmbeddings;
72
73use async_trait::async_trait;
74
75/// Embedding error type
76#[derive(Debug, thiserror::Error)]
77#[non_exhaustive]
78pub enum EmbeddingError {
79 /// HTTP request error
80 #[error("HTTP error: {0}")]
81 HttpError(String),
82
83 /// API error
84 #[error("API error: {0}")]
85 ApiError(String),
86
87 /// Parse error
88 #[error("Parse error: {0}")]
89 ParseError(String),
90
91 /// Configuration error (e.g. empty API key, unknown model dimension) — fails fast at construction.
92 #[error("Configuration error: {0}")]
93 Config(String),
94
95 /// Empty input
96 #[error("Input is empty")]
97 EmptyInput,
98
99 /// Batch embedding misalignment: for N requested texts, the provider returned a vector
100 /// count or index outside the expected range (a chunk missing entries / out of order).
101 ///
102 /// P0-1: reject silently misaligned data — never treat a missing vector as "dissimilar".
103 #[error("Embedding batch mismatch: expected {expected} vectors, got position {actual}")]
104 BatchMismatch {
105 /// The expected number of vectors
106 expected: usize,
107 /// The position index where the misalignment occurred
108 actual: usize,
109 },
110
111 /// Some text in a batch got no vector (the provider returned fewer embeddings than requested).
112 ///
113 /// P0-1: reject silently empty vectors — a missing vector is an explicit error, not a zero vector.
114 #[error("Embedding batch contains an empty vector (provider returned fewer embeddings than requested)")]
115 EmptyVectorInBatch,
116}
117
118/// Embedding model trait
119///
120/// Defines the interface for generating text embedding vectors.
121///
122/// # Normalization contract (P2-8)
123///
124/// All returned vectors are **L2-normalized** unit vectors (except zero vectors),
125/// regardless of whether the provider normalizes internally. This guarantees downstream
126/// cosine, dot-product, or L2-distance results do not drift across providers. HTTP
127/// providers call [`l2_normalize`] uniformly before returning.
128#[async_trait]
129pub trait Embeddings: Send + Sync {
130 /// Generate an embedding vector for a single text.
131 ///
132 /// # Arguments
133 /// * `text` - Input text
134 ///
135 /// # Returns
136 /// Embedding vector (typically 1536 dimensions or higher)
137 async fn embed_query(&self, text: &str) -> Result<Vec<f32>, EmbeddingError>;
138
139 /// Generate embedding vectors for multiple documents.
140 ///
141 /// # Arguments
142 /// * `texts` - List of input texts
143 ///
144 /// # Returns
145 /// List of embedding vectors
146 ///
147 /// # Semantic contract (P1-1)
148 ///
149 /// - Any empty or all-whitespace text (`trim().is_empty()`) → `Err(EmbeddingError::EmptyInput)`;
150 /// - An empty slice `&[]` is treated as "no text to embed" → `Ok(vec![])` (nothing to do is not an error).
151 ///
152 /// The default implementation loops over [`Self::embed_query`] with a uniform emptiness
153 /// check up front; providers that override it must follow the same contract and not diverge.
154 async fn embed_documents(&self, texts: &[&str]) -> Result<Vec<Vec<f32>>, EmbeddingError> {
155 if texts.iter().any(|t| t.trim().is_empty()) {
156 return Err(EmbeddingError::EmptyInput);
157 }
158 let mut embeddings = Vec::new();
159 for text in texts {
160 embeddings.push(self.embed_query(text).await?);
161 }
162 Ok(embeddings)
163 }
164
165 /// Get the embedding vector dimension.
166 fn dimension(&self) -> usize;
167
168 /// Get the model name.
169 fn model_name(&self) -> &str;
170}
171
172/// Compute cosine similarity between two vectors.
173///
174/// Re-exported from [`lc_core::math::cosine_similarity`].
175pub use lc_core::math::cosine_similarity;
176
177/// In-place L2 normalization: scale `vec` to unit length.
178///
179/// P2-8: providers normalize returned vectors differently (OpenAI normalizes, BOW
180/// self-normalizes, remote providers such as Cohere may not); downstream results using
181/// dot-product/L2 distance instead of cosine would drift across providers. This function
182/// is the **single** normalization implementation; HTTP providers call it uniformly before
183/// returning, ensuring `Embeddings` always produces unit-length vectors.
184///
185/// A zero vector stays zero (no NaN is produced).
186pub fn l2_normalize(vec: &mut [f32]) {
187 let norm: f32 = vec.iter().map(|x| x * x).sum::<f32>().sqrt();
188 if norm > 0.0 {
189 for v in vec.iter_mut() {
190 *v /= norm;
191 }
192 }
193}
194
195/// Mutex for synchronizing environment-variable mutations in tests.
196///
197/// Tests that set/remove env vars must acquire this lock to avoid data races
198/// when running tests in parallel (the default for `cargo test`).
199#[cfg(test)]
200static ENV_TEST_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
201
202#[cfg(test)]
203mod tests {
204 use super::*;
205
206 #[test]
207 fn test_cosine_similarity() {
208 // Identical vectors
209 let a = vec![1.0, 0.0, 0.0];
210 let b = vec![1.0, 0.0, 0.0];
211 assert!((cosine_similarity(&a, &b).unwrap() - 1.0).abs() < 0.0001);
212
213 // Orthogonal vectors
214 let a = vec![1.0, 0.0, 0.0];
215 let b = vec![0.0, 1.0, 0.0];
216 assert!((cosine_similarity(&a, &b).unwrap() - 0.0).abs() < 0.0001);
217
218 // Opposite vectors
219 let a = vec![1.0, 0.0, 0.0];
220 let b = vec![-1.0, 0.0, 0.0];
221 assert!((cosine_similarity(&a, &b).unwrap() - (-1.0)).abs() < 0.0001);
222 }
223
224 #[test]
225 fn test_cosine_similarity_different_lengths() {
226 let a = vec![1.0, 0.0];
227 let b = vec![1.0, 0.0, 0.0];
228 assert!(cosine_similarity(&a, &b).is_err());
229 }
230}