aidaemon-memory 0.27.2

Swappable long-term memory for aidaemon agents: the MemoryStore traits plus SQLite and embedding implementations
Documentation
//! Text embedders: the [`Embedder`] extension point, a deterministic
//! offline [`HashEmbedder`], and (feature `fastembed`) a local ONNX model.

use async_trait::async_trait;

use crate::error::{MemoryError, Result};
use crate::scoring::tokens;

/// Turns text into vectors. Implement this to use an embedding API or
/// another local model; [`crate::Memory`] only sees `Arc<dyn Embedder>`.
///
/// Vectors should be L2-normalized so cosine similarity is a dot product,
/// but [`cosine`] normalizes anyway.
#[async_trait]
pub trait Embedder: Send + Sync {
    /// Stable identifier persisted beside every vector. Changing the model
    /// changes this id, and old vectors are then ignored (lexical recall
    /// still works) instead of being compared across models, until
    /// [`crate::Memory::reembed_batch`] replaces them.
    fn model_id(&self) -> &str;

    /// Length of every returned vector.
    fn dimensions(&self) -> usize;

    /// One vector per input text, in order.
    async fn embed(&self, texts: &[String]) -> Result<Vec<Vec<f32>>>;
}

#[async_trait]
impl<E: Embedder + ?Sized> Embedder for std::sync::Arc<E> {
    fn model_id(&self) -> &str {
        (**self).model_id()
    }
    fn dimensions(&self) -> usize {
        (**self).dimensions()
    }
    async fn embed(&self, texts: &[String]) -> Result<Vec<Vec<f32>>> {
        (**self).embed(texts).await
    }
}

/// Cosine similarity; 0.0 for mismatched lengths or zero vectors.
pub fn cosine(a: &[f32], b: &[f32]) -> f32 {
    if a.len() != b.len() || a.is_empty() {
        return 0.0;
    }
    let (mut dot, mut na, mut nb) = (0.0f32, 0.0f32, 0.0f32);
    for (x, y) in a.iter().zip(b) {
        dot += x * y;
        na += x * x;
        nb += y * y;
    }
    if na <= f32::EPSILON || nb <= f32::EPSILON {
        return 0.0;
    }
    dot / (na.sqrt() * nb.sqrt())
}

/// Little-endian f32 bytes, the BLOB format used by `SqliteMemoryStore`.
pub fn encode_embedding(vector: &[f32]) -> Vec<u8> {
    vector.iter().flat_map(|v| v.to_le_bytes()).collect()
}

/// Inverse of [`encode_embedding`]; `None` for a malformed blob.
pub fn decode_embedding(bytes: &[u8]) -> Option<Vec<f32>> {
    if !bytes.len().is_multiple_of(4) {
        return None;
    }
    let (chunks, _) = bytes.as_chunks::<4>();
    Some(chunks.iter().map(|c| f32::from_le_bytes(*c)).collect())
}

/// Decode a stored vector that must have `dims` dimensions. Besides the
/// binary format of [`encode_embedding`], this reads the legacy format a
/// JSON array of numbers (older daemon databases stored vectors that way).
/// Any other blob, including binary of the wrong length, is an error.
pub fn decode_embedding_with_dim(bytes: &[u8], dims: usize) -> Result<Vec<f32>> {
    let binary_len = dims
        .checked_mul(std::mem::size_of::<f32>())
        .ok_or_else(|| MemoryError::Invalid("embedding dimension overflow".into()))?;
    if dims > 0 && bytes.len() == binary_len {
        return Ok(decode_embedding(bytes).unwrap_or_default());
    }
    if bytes.first() == Some(&b'[') {
        return serde_json::from_slice(bytes)
            .map_err(|e| MemoryError::Invalid(format!("legacy JSON embedding: {e}")));
    }
    Err(MemoryError::Invalid(format!(
        "unknown embedding format: length {}, expected {dims} dimensions, first byte {:?}",
        bytes.len(),
        bytes.first()
    )))
}

/// Deterministic hashed bag-of-words embedder. No model, no network, same
/// output on every machine (FNV-1a hashing). Similarity reflects shared
/// words only, so it suits tests and offline use, not production recall.
#[derive(Debug, Clone)]
pub struct HashEmbedder {
    dims: usize,
    id: String,
}

impl HashEmbedder {
    pub fn new(dims: usize) -> Self {
        let dims = dims.max(8);
        Self {
            dims,
            id: format!("hash-bow-v1/{dims}"),
        }
    }

    /// Embed one text synchronously.
    pub fn embed_one(&self, text: &str) -> Vec<f32> {
        let mut v = vec![0.0f32; self.dims];
        for token in tokens(text) {
            let h = fnv1a(token.as_bytes());
            let index = (h % self.dims as u64) as usize;
            let sign = if (h >> 63) == 0 { 1.0 } else { -1.0 };
            v[index] += sign;
        }
        let norm = v.iter().map(|x| x * x).sum::<f32>().sqrt();
        if norm > 0.0 {
            v.iter_mut().for_each(|x| *x /= norm);
        }
        v
    }
}

impl Default for HashEmbedder {
    fn default() -> Self {
        Self::new(256)
    }
}

fn fnv1a(bytes: &[u8]) -> u64 {
    let mut hash: u64 = 0xcbf2_9ce4_8422_2325;
    for b in bytes {
        hash ^= u64::from(*b);
        hash = hash.wrapping_mul(0x0100_0000_01b3);
    }
    hash
}

#[async_trait]
impl Embedder for HashEmbedder {
    fn model_id(&self) -> &str {
        &self.id
    }

    fn dimensions(&self) -> usize {
        self.dims
    }

    async fn embed(&self, texts: &[String]) -> Result<Vec<Vec<f32>>> {
        Ok(texts.iter().map(|t| self.embed_one(t)).collect())
    }
}

#[cfg(feature = "fastembed")]
pub use fast::{DEFAULT_FASTEMBED_MODEL, FastEmbedder};

#[cfg(feature = "fastembed")]
mod fast {
    use std::path::PathBuf;
    use std::sync::{Arc, Mutex};

    use async_trait::async_trait;
    use fastembed::{AutoDevicePolicy, EmbeddingModel, TextEmbedding, TextInitOptions};
    use tokio::sync::OnceCell;

    use super::Embedder;
    use crate::error::{MemoryError, Result};

    /// The model [`FastEmbedder::new`] runs: AllMiniLM-L6-v2, 384
    /// dimensions.
    pub const DEFAULT_FASTEMBED_MODEL: &str = "AllMiniLML6V2";

    /// The id vectors of AllMiniLM-L6-v2 have always been stored under.
    const LEGACY_MINILM_ID: &str = "fastembed/all-MiniLM-L6-v2";

    /// A local ONNX text-embedding model via fastembed. The model is
    /// downloaded and loaded lazily on the first `embed` call; loading and
    /// inference run on `spawn_blocking`.
    pub struct FastEmbedder {
        choice: EmbeddingModel,
        model_id: String,
        dimensions: usize,
        cache_dir: Option<PathBuf>,
        show_download_progress: bool,
        // fastembed's `embed` takes `&mut self`: one call at a time.
        model: OnceCell<Arc<Mutex<TextEmbedding>>>,
    }

    impl FastEmbedder {
        /// AllMiniLM-L6-v2 ([`DEFAULT_FASTEMBED_MODEL`]).
        pub fn new() -> Self {
            Self::named(DEFAULT_FASTEMBED_MODEL).expect("the default model is supported")
        }

        /// Any text model fastembed supports, by its `EmbeddingModel`
        /// variant name, case-insensitive: `"AllMiniLML6V2Q"`,
        /// `"BGESmallENV15"`, `"ParaphraseMLMiniLML12V2"`, ...
        pub fn named(name: &str) -> Result<Self> {
            let choice: EmbeddingModel = name.trim().parse().map_err(|_| {
                MemoryError::Embedding(format!(
                    "unknown embedding model `{name}`; supported: {}",
                    Self::supported().join(", ")
                ))
            })?;
            let dimensions = TextEmbedding::get_model_info(&choice)
                .map_err(|e| MemoryError::Embedding(e.to_string()))?
                .dim;
            let model_id = if choice == EmbeddingModel::AllMiniLML6V2 {
                LEGACY_MINILM_ID.to_string()
            } else {
                format!("fastembed/{choice:?}")
            };
            Ok(Self {
                choice,
                model_id,
                dimensions,
                cache_dir: None,
                show_download_progress: false,
                model: OnceCell::new(),
            })
        }

        /// The names [`FastEmbedder::named`] accepts.
        pub fn supported() -> Vec<String> {
            TextEmbedding::list_supported_models()
                .into_iter()
                .map(|info| format!("{:?}", info.model))
                .collect()
        }

        /// Where model files are cached (fastembed's default otherwise).
        pub fn cache_dir(mut self, dir: impl Into<PathBuf>) -> Self {
            self.cache_dir = Some(dir.into());
            self
        }

        pub fn show_download_progress(mut self, show: bool) -> Self {
            self.show_download_progress = show;
            self
        }

        async fn model(&self) -> Result<Arc<Mutex<TextEmbedding>>> {
            let choice = self.choice.clone();
            let cache_dir = self.cache_dir.clone();
            let progress = self.show_download_progress;
            self.model
                .get_or_try_init(|| async move {
                    tokio::task::spawn_blocking(move || {
                        let mut options =
                            TextInitOptions::new(choice).with_show_download_progress(progress);
                        // Plain CPU: ort's default registers CoreML on macOS,
                        // which costs ~5x the memory for this model and is slower.
                        options.auto_device = Some(AutoDevicePolicy::PreferCPU);
                        if let Some(dir) = cache_dir {
                            options = options.with_cache_dir(dir);
                        }
                        TextEmbedding::try_new(options)
                            .map(|model| Arc::new(Mutex::new(model)))
                            .map_err(|e| MemoryError::Embedding(e.to_string()))
                    })
                    .await
                    .map_err(|e| MemoryError::Embedding(e.to_string()))?
                })
                .await
                .cloned()
        }
    }

    impl Default for FastEmbedder {
        fn default() -> Self {
            Self::new()
        }
    }

    #[async_trait]
    impl Embedder for FastEmbedder {
        fn model_id(&self) -> &str {
            &self.model_id
        }

        fn dimensions(&self) -> usize {
            self.dimensions
        }

        async fn embed(&self, texts: &[String]) -> Result<Vec<Vec<f32>>> {
            if texts.is_empty() {
                return Ok(Vec::new());
            }
            let model = self.model().await?;
            let texts = texts.to_vec();
            tokio::task::spawn_blocking(move || {
                let mut model = model.lock().map_err(|e| {
                    MemoryError::Embedding(format!("embedding model lock poisoned: {e}"))
                })?;
                model
                    .embed(texts, None)
                    .map_err(|e| MemoryError::Embedding(e.to_string()))
            })
            .await
            .map_err(|e| MemoryError::Embedding(e.to_string()))?
        }
    }
}

#[cfg(test)]
mod tests {
    use super::{decode_embedding_with_dim, encode_embedding};

    #[test]
    fn dimensioned_decode_reads_binary_and_legacy_json() {
        let original: Vec<f32> = (0..384).map(|i| i as f32 * 0.001).collect();
        let binary = encode_embedding(&original);
        assert_eq!(binary.len(), 1536);
        assert_eq!(decode_embedding_with_dim(&binary, 384).unwrap(), original);
        let json = serde_json::to_vec(&original).unwrap();
        assert_eq!(decode_embedding_with_dim(&json, 384).unwrap(), original);
    }

    #[test]
    fn dimensioned_decode_rejects_other_blobs() {
        assert!(decode_embedding_with_dim(&[0u8; 100], 384).is_err());
        assert!(decode_embedding_with_dim(&[], 384).is_err());
        // Binary of another model's dimension is not silently accepted.
        assert!(decode_embedding_with_dim(&encode_embedding(&[1.0; 8]), 384).is_err());
    }

    #[test]
    fn special_float_values_round_trip() {
        let mut vector: Vec<f32> = (0..384).map(|i| i as f32).collect();
        vector[0] = f32::NEG_INFINITY;
        vector[1] = f32::INFINITY;
        vector[3] = -0.0;
        let decoded = decode_embedding_with_dim(&encode_embedding(&vector), 384).unwrap();
        assert!(decoded[0].is_infinite() && decoded[0].is_sign_negative());
        assert!(decoded[1].is_infinite() && decoded[1].is_sign_positive());
    }

    use super::*;

    #[tokio::test]
    async fn hash_embedder_is_deterministic_and_normalized() {
        let a = HashEmbedder::new(128);
        let b = HashEmbedder::new(128);
        let texts = vec!["Alice Rivera likes hiking".to_string()];
        let va = a.embed(&texts).await.unwrap();
        let vb = b.embed(&texts).await.unwrap();
        assert_eq!(va, vb);
        assert_eq!(va[0].len(), 128);
        let norm: f32 = va[0].iter().map(|x| x * x).sum::<f32>().sqrt();
        assert!((norm - 1.0).abs() < 1e-5);
        let related = a.embed_one("hiking trips for Alice");
        let unrelated = a.embed_one("quarterly invoice totals");
        assert!(cosine(&va[0], &related) > cosine(&va[0], &unrelated));
        assert_eq!(a.embed_one(""), vec![0.0; 128]);
    }

    #[test]
    fn blobs_round_trip() {
        let v = vec![0.25f32, -1.5, 3.0];
        assert_eq!(decode_embedding(&encode_embedding(&v)), Some(v));
        assert_eq!(decode_embedding(&[1, 2, 3]), None);
    }

    #[cfg(feature = "fastembed")]
    #[tokio::test]
    #[ignore = "downloads the AllMiniLM-L6-v2 model"]
    async fn fastembed_embeds_with_384_dims() {
        let e = FastEmbedder::new();
        let out = e.embed(&["Mia and Zoe".to_string()]).await.unwrap();
        assert_eq!(out[0].len(), 384);
    }

    #[cfg(feature = "fastembed")]
    #[test]
    fn models_are_chosen_by_name_with_their_own_id_and_dimensions() {
        let default = FastEmbedder::new();
        assert_eq!(default.model_id(), "fastembed/all-MiniLM-L6-v2");
        assert_eq!(default.dimensions(), 384);

        let quantized = FastEmbedder::named("allminilml6v2q").unwrap();
        assert_eq!(quantized.model_id(), "fastembed/AllMiniLML6V2Q");
        assert_eq!(quantized.dimensions(), 384);

        assert_eq!(
            FastEmbedder::named("BGEBaseENV15").unwrap().dimensions(),
            768
        );
        let unknown = FastEmbedder::named("no-such-model")
            .err()
            .unwrap()
            .to_string();
        assert!(unknown.contains("AllMiniLML6V2Q"), "{unknown}");
    }
}