Skip to main content

synaptic_embeddings/
fake.rs

1use async_trait::async_trait;
2use synaptic_core::SynapticError;
3
4use crate::Embeddings;
5
6/// Deterministic embeddings for testing.
7/// Generates vectors based on a simple hash of the input text.
8pub struct FakeEmbeddings {
9    dimensions: usize,
10}
11
12impl FakeEmbeddings {
13    pub fn new(dimensions: usize) -> Self {
14        Self { dimensions }
15    }
16}
17
18impl Default for FakeEmbeddings {
19    fn default() -> Self {
20        Self::new(4)
21    }
22}
23
24#[async_trait]
25impl Embeddings for FakeEmbeddings {
26    async fn embed_documents(&self, texts: &[&str]) -> Result<Vec<Vec<f32>>, SynapticError> {
27        Ok(texts
28            .iter()
29            .map(|t| text_to_vector(t, self.dimensions))
30            .collect())
31    }
32
33    async fn embed_query(&self, text: &str) -> Result<Vec<f32>, SynapticError> {
34        Ok(text_to_vector(text, self.dimensions))
35    }
36}
37
38/// Generate a deterministic vector from text. Similar texts produce similar vectors.
39fn text_to_vector(text: &str, dimensions: usize) -> Vec<f32> {
40    let mut vec = vec![0.0f32; dimensions];
41    for (i, byte) in text.bytes().enumerate() {
42        vec[i % dimensions] += byte as f32;
43    }
44    // Normalize to unit vector
45    let magnitude: f32 = vec.iter().map(|x| x * x).sum::<f32>().sqrt();
46    if magnitude > 0.0 {
47        for x in &mut vec {
48            *x /= magnitude;
49        }
50    }
51    vec
52}