tandem-memory 0.5.2

Memory storage and embedding utilities for Tandem
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
// Embedding Service Module
// Generates embeddings using local fastembed implementation.

use crate::types::{
    MemoryError, MemoryResult, DEFAULT_EMBEDDING_DIMENSION, DEFAULT_EMBEDDING_MODEL,
};
#[cfg(feature = "local-embeddings")]
use fastembed::{EmbeddingModel, InitOptions, TextEmbedding};
use once_cell::sync::OnceCell;
use sha2::{Digest, Sha256};
#[cfg(feature = "local-embeddings")]
use std::path::PathBuf;
use std::sync::Arc;
use tokio::sync::Mutex;

#[cfg(feature = "local-embeddings")]
type EmbeddingBackend = TextEmbedding;
#[cfg(not(feature = "local-embeddings"))]
type EmbeddingBackend = ();

/// Embedding service for generating vector representations.
pub struct EmbeddingService {
    model_name: String,
    dimension: usize,
    model: Option<EmbeddingBackend>,
    disabled_reason: Option<String>,
    deterministic: bool,
}

impl EmbeddingService {
    /// Create a new embedding service with default model.
    pub fn new() -> Self {
        Self::with_model(
            DEFAULT_EMBEDDING_MODEL.to_string(),
            DEFAULT_EMBEDDING_DIMENSION,
        )
    }

    /// Create with custom model.
    pub fn with_model(model_name: String, dimension: usize) -> Self {
        let (model, disabled_reason) = Self::init_model(&model_name);

        if let Some(reason) = &disabled_reason {
            tracing::warn!(
                target: "tandem.memory",
                "Embeddings disabled: model={} reason={}",
                model_name,
                reason
            );
        } else {
            tracing::info!(
                target: "tandem.memory",
                "Embeddings enabled: model={} dimension={}",
                model_name,
                dimension
            );
        }

        Self {
            model_name,
            dimension,
            model,
            disabled_reason,
            deterministic: false,
        }
    }

    /// Create a lightweight deterministic embedding service for tests
    /// and offline callers that need vector-shaped data without loading
    /// the local ONNX model.
    pub fn deterministic_for_tests(dimension: usize) -> Self {
        Self {
            model_name: "deterministic-test-embedding".to_string(),
            dimension,
            model: None,
            disabled_reason: None,
            deterministic: true,
        }
    }

    fn init_model(model_name: &str) -> (Option<EmbeddingBackend>, Option<String>) {
        #[cfg(not(feature = "local-embeddings"))]
        {
            let _ = model_name;
            (
                None,
                Some("local embeddings are disabled at build time".to_string()),
            )
        }

        #[cfg(feature = "local-embeddings")]
        {
            if let Some(reason) = embeddings_runtime_disabled_reason() {
                return (None, Some(reason));
            }

            let Some(parsed_model) = Self::parse_model_id(model_name) else {
                return (
                    None,
                    Some(format!(
                        "unsupported embedding model id '{}'; supported: {}",
                        model_name, DEFAULT_EMBEDDING_MODEL
                    )),
                );
            };

            let cache_dir = resolve_embedding_cache_dir();
            let options = InitOptions::new(parsed_model).with_cache_dir(cache_dir.clone());

            tracing::info!(
                target: "tandem.memory",
                "Initializing embeddings with cache dir: {}",
                cache_dir.display()
            );

            match TextEmbedding::try_new(options) {
                Ok(model) => (Some(model), None),
                Err(err) => (
                    None,
                    Some(format!(
                        "failed to initialize embedding model '{}': {}",
                        model_name, err
                    )),
                ),
            }
        }
    }

    #[cfg(feature = "local-embeddings")]
    fn parse_model_id(model_name: &str) -> Option<EmbeddingModel> {
        match model_name.trim().to_ascii_lowercase().as_str() {
            "all-minilm-l6-v2" | "all_minilm_l6_v2" => Some(EmbeddingModel::AllMiniLML6V2),
            _ => None,
        }
    }

    /// Get the embedding dimension.
    pub fn dimension(&self) -> usize {
        self.dimension
    }

    /// Get the model name.
    pub fn model_name(&self) -> &str {
        &self.model_name
    }

    /// Returns whether semantic embeddings are currently available.
    pub fn is_available(&self) -> bool {
        self.model.is_some()
    }

    /// Returns disabled reason if embeddings are unavailable.
    pub fn disabled_reason(&self) -> Option<&str> {
        self.disabled_reason.as_deref()
    }

    fn unavailable_error(&self) -> MemoryError {
        let reason = self
            .disabled_reason
            .as_deref()
            .unwrap_or("embedding backend unavailable");
        MemoryError::Embedding(format!("embeddings disabled: {reason}"))
    }

    fn deterministic_embedding(&self, text: &str) -> Vec<f32> {
        let mut values = Vec::with_capacity(self.dimension);
        let mut seed = Sha256::digest(text.as_bytes()).to_vec();
        while values.len() < self.dimension {
            for byte in &seed {
                let value = (*byte as f32 / 127.5) - 1.0;
                values.push(value);
                if values.len() == self.dimension {
                    break;
                }
            }
            seed = Sha256::digest(&seed).to_vec();
        }
        values
    }

    #[cfg(feature = "local-embeddings")]
    fn ensure_dimension(&self, embedding: &[f32]) -> MemoryResult<()> {
        if embedding.len() != self.dimension {
            return Err(MemoryError::Embedding(format!(
                "embedding dimension mismatch: expected {}, got {}",
                self.dimension,
                embedding.len()
            )));
        }
        Ok(())
    }

    /// Generate embeddings for a single text.
    pub async fn embed(&self, text: &str) -> MemoryResult<Vec<f32>> {
        if self.deterministic {
            return Ok(self.deterministic_embedding(text));
        }

        #[cfg(not(feature = "local-embeddings"))]
        {
            let _ = text;
            Err(self.unavailable_error())
        }

        #[cfg(feature = "local-embeddings")]
        {
            let Some(model) = self.model.as_ref() else {
                return Err(self.unavailable_error());
            };

            let mut embeddings = model
                .embed(vec![text.to_string()], None)
                .map_err(|e| MemoryError::Embedding(e.to_string()))?;
            let embedding = embeddings
                .pop()
                .ok_or_else(|| MemoryError::Embedding("no embedding generated".to_string()))?;
            self.ensure_dimension(&embedding)?;
            Ok(embedding)
        }
    }

    /// Generate embeddings for multiple texts.
    pub async fn embed_batch(&self, texts: &[String]) -> MemoryResult<Vec<Vec<f32>>> {
        if self.deterministic {
            return Ok(texts
                .iter()
                .map(|text| self.deterministic_embedding(text))
                .collect());
        }

        #[cfg(not(feature = "local-embeddings"))]
        {
            let _ = texts;
            Err(self.unavailable_error())
        }

        #[cfg(feature = "local-embeddings")]
        {
            let Some(model) = self.model.as_ref() else {
                return Err(self.unavailable_error());
            };

            let embeddings = model
                .embed(texts.to_vec(), None)
                .map_err(|e| MemoryError::Embedding(e.to_string()))?;

            for embedding in &embeddings {
                self.ensure_dimension(embedding)?;
            }

            Ok(embeddings)
        }
    }

    /// Calculate cosine similarity between two vectors.
    pub fn cosine_similarity(a: &[f32], b: &[f32]) -> f32 {
        if a.len() != b.len() {
            return 0.0;
        }

        let dot_product: f32 = a.iter().zip(b.iter()).map(|(x, y)| x * y).sum();
        let magnitude_a: f32 = a.iter().map(|x| x * x).sum::<f32>().sqrt();
        let magnitude_b: f32 = b.iter().map(|x| x * x).sum::<f32>().sqrt();

        if magnitude_a == 0.0 || magnitude_b == 0.0 {
            0.0
        } else {
            dot_product / (magnitude_a * magnitude_b)
        }
    }

    /// Calculate Euclidean distance between two vectors.
    pub fn euclidean_distance(a: &[f32], b: &[f32]) -> f32 {
        a.iter()
            .zip(b.iter())
            .map(|(x, y)| (x - y).powi(2))
            .sum::<f32>()
            .sqrt()
    }
}

#[cfg(feature = "local-embeddings")]
fn embeddings_runtime_disabled_reason() -> Option<String> {
    let disable = std::env::var("TANDEM_DISABLE_EMBEDDINGS")
        .ok()
        .map(|v| v.trim().to_ascii_lowercase())
        .filter(|v| !v.is_empty())
        .map(|v| matches!(v.as_str(), "1" | "true" | "yes" | "on"))
        .unwrap_or(false);

    if disable {
        return Some("disabled by TANDEM_DISABLE_EMBEDDINGS".to_string());
    }
    None
}

#[cfg(feature = "local-embeddings")]
fn resolve_embedding_cache_dir() -> PathBuf {
    if let Ok(explicit) = std::env::var("FASTEMBED_CACHE_DIR") {
        let explicit_path = PathBuf::from(explicit);
        if let Err(err) = std::fs::create_dir_all(&explicit_path) {
            tracing::warn!(
                target: "tandem.memory",
                "Failed to create FASTEMBED_CACHE_DIR {:?}: {}",
                explicit_path,
                err
            );
        }
        return explicit_path;
    }

    let base = dirs::data_local_dir()
        .or_else(dirs::cache_dir)
        .unwrap_or_else(std::env::temp_dir);
    let cache_dir = base.join("tandem").join("fastembed");

    if let Err(err) = std::fs::create_dir_all(&cache_dir) {
        tracing::warn!(
            target: "tandem.memory",
            "Failed to create embedding cache directory {:?}: {}",
            cache_dir,
            err
        );
    }

    cache_dir
}

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

// Global embedding service instance.
static EMBEDDING_SERVICE: OnceCell<Arc<Mutex<EmbeddingService>>> = OnceCell::new();

/// Get or initialize the global embedding service.
pub async fn get_embedding_service() -> Arc<Mutex<EmbeddingService>> {
    EMBEDDING_SERVICE
        .get_or_init(|| Arc::new(Mutex::new(EmbeddingService::new())))
        .clone()
}

/// Initialize the embedding service with custom configuration.
pub fn init_embedding_service(model_name: Option<String>, dimension: Option<usize>) {
    let service = if let (Some(name), Some(dim)) = (model_name, dimension) {
        EmbeddingService::with_model(name, dim)
    } else {
        EmbeddingService::new()
    };

    let _ = EMBEDDING_SERVICE.set(Arc::new(Mutex::new(service)));
}

#[cfg(test)]
mod tests {
    use super::*;

    #[tokio::test]
    async fn test_embedding_dimension_or_unavailable() {
        let service = EmbeddingService::new();

        if !service.is_available() {
            let err = service.embed("Hello world").await.unwrap_err();
            assert!(err.to_string().contains("embeddings disabled"));
            return;
        }

        let embedding = service.embed("Hello world").await.unwrap();
        assert_eq!(embedding.len(), DEFAULT_EMBEDDING_DIMENSION);
    }

    #[tokio::test]
    async fn test_embed_batch_or_unavailable() {
        let service = EmbeddingService::new();
        let texts = vec![
            "First text".to_string(),
            "Second text".to_string(),
            "Third text".to_string(),
        ];

        let result = service.embed_batch(&texts).await;
        if !service.is_available() {
            assert!(result.is_err());
            return;
        }

        let embeddings = result.unwrap();
        assert_eq!(embeddings.len(), 3);
        for emb in &embeddings {
            assert_eq!(emb.len(), DEFAULT_EMBEDDING_DIMENSION);
        }
    }

    #[test]
    fn test_cosine_similarity() {
        let a = vec![1.0f32, 0.0, 0.0];
        let b = vec![1.0f32, 0.0, 0.0];
        let c = vec![0.0f32, 1.0, 0.0];

        let sim_same = EmbeddingService::cosine_similarity(&a, &b);
        let sim_orthogonal = EmbeddingService::cosine_similarity(&a, &c);

        assert!((sim_same - 1.0).abs() < 1e-6);
        assert!(sim_orthogonal.abs() < 1e-6);
    }
}