langchain_rust/semantic_router/
utils.rs

1pub fn combine_embeddings(embeddings: &[Vec<f64>]) -> Vec<f64> {
2    embeddings
3        .iter()
4        // Initialize a vector with zeros based on the length of the first embedding vector.
5        // It's assumed all embeddings have the same dimensions.
6        .fold(
7            vec![0f64; embeddings[0].len()],
8            |mut accumulator, embedding_vec| {
9                for (i, &value) in embedding_vec.iter().enumerate() {
10                    accumulator[i] += value;
11                }
12                accumulator
13            },
14        )
15        // Calculate the mean for each element across all embeddings.
16        .iter()
17        .map(|&sum| sum / embeddings.len() as f64)
18        .collect()
19}
20
21pub fn cosine_similarity(vec1: &[f64], vec2: &[f64]) -> f64 {
22    let dot_product: f64 = vec1.iter().zip(vec2.iter()).map(|(a, b)| a * b).sum();
23    let magnitude_vec1: f64 = vec1.iter().map(|x| x.powi(2)).sum::<f64>().sqrt();
24    let magnitude_vec2: f64 = vec2.iter().map(|x| x.powi(2)).sum::<f64>().sqrt();
25    dot_product / (magnitude_vec1 * magnitude_vec2)
26}
27
28pub fn sum_vectors(vectors: &[Vec<f64>]) -> Vec<f64> {
29    let mut sum_vec = vec![0.0; vectors[0].len()];
30    for vec in vectors {
31        for (i, &value) in vec.iter().enumerate() {
32            sum_vec[i] += value;
33        }
34    }
35    sum_vec
36}