mem0-rust 0.2.0

Rust implementation of mem0 - Universal memory layer for AI Agents
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
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
//! Core Memory manager.

use std::collections::HashMap;
use std::sync::Arc;
use tracing::{debug, info, warn};
use uuid::Uuid;
use chrono::Utc;

use crate::config::MemoryConfig;
use crate::embeddings::{create_embedder, Embedder};
use crate::errors::{LLMError, MemoryError};
use crate::history::HistoryManager;
use crate::llms::{create_llm, generate_json, GenerateOptions, LLM};
use crate::models::{
    AddOptions, AddResult, EventType, Filters, GetAllOptions, HistoryEntry, MemoryEvent,
    MemoryRecord, Message, Messages, Payload, ResetOptions, Role, ScoredMemory, SearchOptions,
    SearchResult,
};
use crate::vector_stores::{create_vector_store, VectorStore};
use crate::rerankers::{create_reranker, Reranker};

use super::prompts::{
    format_fact_extraction_input, format_memory_update_input, FACT_EXTRACTION_PROMPT,
    MEMORY_UPDATE_PROMPT,
};

/// Main Memory interface
pub struct Memory {
    embedder: Arc<dyn Embedder>,
    vector_store: Arc<dyn VectorStore>,
    llm: Option<Arc<dyn LLM>>,
    history: Option<Arc<HistoryManager>>,
    reranker: Option<Arc<dyn Reranker>>,
    #[allow(dead_code)]
    config: MemoryConfig,
}

impl Memory {
    /// Create a new Memory instance
    pub async fn new(config: MemoryConfig) -> Result<Self, MemoryError> {
        let embedder = create_embedder(&config.embedder)?;
        let dimensions = embedder.dimensions();

        let vector_store =
            create_vector_store(&config.vector_store, &config.collection_name, dimensions).await?;

        let llm = if let Some(llm_config) = &config.llm {
            Some(create_llm(llm_config)?)
        } else {
            None
        };

        let history = if let Some(path) = &config.history_db_path {
            Some(Arc::new(HistoryManager::new(path)?))
        } else {
            None
        };

        let reranker = if let Some(reranker_config) = &config.reranker {
            Some(create_reranker(reranker_config)?)
        } else {
            None
        };

        info!(
            "Initialized Memory with {} embedder, {} dimensions",
            embedder.model_name(),
            dimensions
        );

        Ok(Self {
            embedder,
            vector_store,
            llm,
            history,
            reranker,
            config,
        })
    }

    /// Add memories from messages
    pub async fn add(
        &self,
        messages: impl Into<Messages>,
        options: AddOptions,
    ) -> Result<AddResult, MemoryError> {
        let messages = messages.into().into_messages();
        // Validate scoping
        if options.user_id.is_none() && options.agent_id.is_none() && options.run_id.is_none() {
            return Err(MemoryError::InvalidInput(
                "At least one of user_id, agent_id, or run_id is required".to_string(),
            ));
        }

        let results = if options.infer && self.llm.is_some() {
            // Use LLM for fact extraction
            self.add_with_inference(&messages, &options).await?
        } else {
            // Add messages directly without inference
            self.add_raw(&messages, &options).await?
        };

        Ok(AddResult { results })
    }

    /// Add messages directly without LLM inference
    async fn add_raw(
        &self,
        messages: &[Message],
        options: &AddOptions,
    ) -> Result<Vec<MemoryEvent>, MemoryError> {
        let mut results = Vec::new();

        for msg in messages {
            if msg.role == Role::System {
                continue;
            }

            let record = MemoryRecord::with_scoping(
                msg.content.clone(),
                options
                    .metadata
                    .as_ref()
                    .map(|m| serde_json::to_value(m).unwrap_or_default())
                    .unwrap_or(serde_json::Value::Object(serde_json::Map::new())),
                options.user_id.clone(),
                options.agent_id.clone(),
                options.run_id.clone(),
            );

            let embedding = self.embedder.embed(&record.content).await?;
            let payload = Payload::from(&record);

            self.vector_store
                .insert(&record.id.to_string(), embedding, payload)
                .await?;

            if let Some(history) = &self.history {
                let _ = history.add_history(
                    record.id,
                    None,
                    record.content.clone(),
                    EventType::Add,
                    record.created_at,
                    record.user_id.clone(),
                    record.agent_id.clone(),
                    record.run_id.clone(),
                );
            }

            results.push(MemoryEvent {
                id: record.id,
                memory: record.content,
                event: EventType::Add,
            });
        }

        Ok(results)
    }

    /// Add messages with LLM inference
    async fn add_with_inference(
        &self,
        messages: &[Message],
        options: &AddOptions,
    ) -> Result<Vec<MemoryEvent>, MemoryError> {
        let llm = self.llm.as_ref().ok_or(LLMError::NotConfigured)?;

        // Format messages for extraction
        let messages_text = messages
            .iter()
            .map(|m| format!("{:?}: {}", m.role, m.content))
            .collect::<Vec<_>>()
            .join("\n");

        // Extract facts
        let extraction_messages = vec![
            Message::system(FACT_EXTRACTION_PROMPT),
            Message::user(format_fact_extraction_input(&messages_text)),
        ];

        #[derive(serde::Deserialize)]
        struct FactsResponse {
            facts: Vec<String>,
        }

        let facts: FactsResponse = generate_json(
            llm.as_ref(),
            &extraction_messages,
            GenerateOptions::default(),
        )
        .await?;

        if facts.facts.is_empty() {
            debug!("No facts extracted from messages");
            return Ok(Vec::new());
        }

        info!("Extracted {} facts", facts.facts.len());

        // Search for existing related memories
        let mut existing_memories: Vec<(String, String)> = Vec::new(); // (Index, Content)
        let mut memory_map: HashMap<String, String> = HashMap::new(); // Index -> RealID

        let search_filters = Filters {
            conditions: vec![],
            logic: crate::models::FilterLogic::And,
        };

        for fact in &facts.facts {
            let embedding = self.embedder.embed(fact).await?;

            let similar = self
                .vector_store
                .search(&embedding, 5, Some(&search_filters))
                .await?;

            for result in similar {
                // Check if we already have this memory in our list (dedupe by real ID)
                let real_id = result.id.clone();
                if !memory_map.values().any(|rid| rid == &real_id) {
                     let index = memory_map.len().to_string();
                     memory_map.insert(index.clone(), real_id);
                     existing_memories.push((index, result.payload.data));
                }
            }
        }

        // Determine memory actions
        let update_messages = vec![
            Message::system(MEMORY_UPDATE_PROMPT),
            Message::user(format_memory_update_input(&existing_memories, &facts.facts)),
        ];

        #[derive(serde::Deserialize)]
        struct MemoryAction {
            event: String,
            text: Option<String>,
            id: Option<String>,
        }

        #[derive(serde::Deserialize)]
        struct MemoryActionsResponse {
            memory: Vec<MemoryAction>,
        }

        let actions: MemoryActionsResponse = generate_json(
            llm.as_ref(),
            &update_messages,
            GenerateOptions::default(),
        )
        .await?;

        let mut results = Vec::new();

        for action in actions.memory {
            match action.event.to_uppercase().as_str() {
                "ADD" => {
                    if let Some(text) = action.text {
                        let record = MemoryRecord::with_scoping(
                            &text,
                            options
                                .metadata
                                .as_ref()
                                .map(|m| serde_json::to_value(m).unwrap_or_default())
                                .unwrap_or(serde_json::Value::Object(serde_json::Map::new())),
                            options.user_id.clone(),
                            options.agent_id.clone(),
                            options.run_id.clone(),
                        );

                        let embedding = self.embedder.embed(&text).await?;
                        let payload = Payload::from(&record);

                        self.vector_store
                            .insert(&record.id.to_string(), embedding, payload)
                            .await?;

                        if let Some(history) = &self.history {
                            let _ = history.add_history(
                                record.id,
                                None,
                                record.content.clone(),
                                EventType::Add,
                                record.created_at,
                                record.user_id.clone(),
                                record.agent_id.clone(),
                                record.run_id.clone(),
                            );
                        }

                        results.push(MemoryEvent {
                            id: record.id,
                            memory: text,
                            event: EventType::Add,
                        });
                    }
                }
                "UPDATE" => {
                    if let (Some(index_id), Some(text)) = (action.id, action.text) {
                        if let Some(real_id) = memory_map.get(&index_id) {
                            debug!("Updating memory {} (index {}) with: {}", real_id, index_id, text);
                            
                            // Perform update
                            match self.update(real_id, &text).await {
                                Ok(record) => {
                                    results.push(MemoryEvent {
                                        id: record.id,
                                        memory: text,
                                        event: EventType::Update,
                                    });
                                },
                                Err(e) => {
                                    warn!("Failed to update memory {}: {}", real_id, e);
                                }
                            }
                        } else {
                            warn!("LLM tried to update unknown memory index: {}", index_id);
                        }
                    }
                }
                "DELETE" => {
                    if let Some(index_id) = action.id {
                        if let Some(real_id) = memory_map.get(&index_id) {
                            debug!("Deleting memory {} (index {})", real_id, index_id);
                            
                            // Perform delete
                            match self.delete(real_id).await {
                                Ok(_) => {
                                     // ID is needed for event, but delete returns void.
                                     // We can use Uuid::parse_str(real_id)
                                     if let Ok(uuid) = Uuid::parse_str(real_id) {
                                         results.push(MemoryEvent {
                                            id: uuid,
                                            memory: String::new(), // Deleted
                                            event: EventType::Delete,
                                        });
                                     }
                                },
                                Err(e) => {
                                    warn!("Failed to delete memory {}: {}", real_id, e);
                                }
                            }
                        } else {
                            warn!("LLM tried to delete unknown memory index: {}", index_id);
                        }
                    }
                }
                "NOOP" => {
                    debug!("No action needed");
                }
                _ => {
                    warn!("Unknown memory action: {}", action.event);
                }
            }
        }

        Ok(results)
    }

    /// Search for memories
    pub async fn search(
        &self,
        query: &str,
        options: SearchOptions,
    ) -> Result<SearchResult, MemoryError> {
        let embedding = self.embedder.embed(query).await?;
        let limit = options.limit.unwrap_or(10);
        let threshold = options.threshold.unwrap_or(0.0);

        // Fetch more candidates if reranking is enabled
        let search_limit = if options.rerank { limit * 10 } else { limit * 2 };

        let results = self
            .vector_store
            .search(&embedding, search_limit, options.filters.as_ref())
            .await?;

        let mut scored: Vec<ScoredMemory> = results
            .into_iter()
            .map(|r| r.to_scored_memory())
            .collect();

        // Apply scoping filters
        scored.retain(|m| {
            if let Some(ref user_id) = options.user_id {
                if m.record.user_id.as_ref() != Some(user_id) {
                    return false;
                }
            }
            if let Some(ref agent_id) = options.agent_id {
                if m.record.agent_id.as_ref() != Some(agent_id) {
                    return false;
                }
            }
            if let Some(ref run_id) = options.run_id {
                if m.record.run_id.as_ref() != Some(run_id) {
                    return false;
                }
            }
            true
        });

        // Filter by threshold before reranking (optional, but saves rerank quota)
        scored.retain(|m| m.score >= threshold);

        // Reranking
        if options.rerank {
            if let Some(reranker) = &self.reranker {
                scored = reranker.rerank(query, scored).await?;
            } else {
                 warn!("Reranking requested but no reranker configured");
            }
        }
        
        // Final sort and limit
        scored.sort_by(|a, b| b.score.partial_cmp(&a.score).unwrap_or(std::cmp::Ordering::Equal));
        scored.truncate(limit);

        Ok(SearchResult { results: scored })
    }

    /// Get a memory by ID
    pub async fn get(&self, id: &str) -> Result<Option<MemoryRecord>, MemoryError> {
        let result = self.vector_store.get(id).await?;
        Ok(result.map(|r| r.to_memory_record()))
    }

    /// Get all memories
    pub async fn get_all(&self, options: GetAllOptions) -> Result<Vec<MemoryRecord>, MemoryError> {
        let limit = options.limit.unwrap_or(100);
        let results = self.vector_store.list(None, limit).await?;

        let mut records: Vec<MemoryRecord> =
            results.into_iter().map(|r| r.to_memory_record()).collect();

        // Apply scoping filters
        records.retain(|m| {
            if let Some(ref user_id) = options.user_id {
                if m.user_id.as_ref() != Some(user_id) {
                    return false;
                }
            }
            if let Some(ref agent_id) = options.agent_id {
                if m.agent_id.as_ref() != Some(agent_id) {
                    return false;
                }
            }
            if let Some(ref run_id) = options.run_id {
                if m.run_id.as_ref() != Some(run_id) {
                    return false;
                }
            }
            true
        });

        Ok(records)
    }

    /// Update a memory
    pub async fn update(&self, id: &str, content: &str) -> Result<MemoryRecord, MemoryError> {
        // Get existing record
        let existing = self
            .vector_store
            .get(id)
            .await?
            .ok_or_else(|| MemoryError::NotFound(id.to_string()))?;

        let mut record = existing.to_memory_record();
        let previous_content = record.content.clone();
        record.update_content(content);

        let embedding = self.embedder.embed(content).await?;
        let payload = Payload::from(&record);

        self.vector_store
            .update(id, Some(embedding), payload)
            .await?;

        if let Some(history) = &self.history {
            let _ = history.add_history(
                record.id,
                Some(previous_content),
                record.content.clone(),
                EventType::Update,
                Utc::now(),
                record.user_id.clone(),
                record.agent_id.clone(),
                record.run_id.clone(),
            );
        }

        Ok(record)
    }

    /// Delete a memory
    pub async fn delete(&self, id: &str) -> Result<(), MemoryError> {
        // Get record first for history
        let record = self.get(id).await?;
        
        self.vector_store.delete(id).await?;

        if let Some(record) = record {
            if let Some(history) = &self.history {
                let _ = history.add_history(
                    record.id,
                    Some(record.content),
                    "DELETED".to_string(),
                    EventType::Delete,
                    Utc::now(),
                    record.user_id,
                    record.agent_id,
                    record.run_id,
                );
            }
        }
        
        Ok(())
    }

    /// Get memory history
    pub async fn history(&self, id: &str) -> Result<Vec<HistoryEntry>, MemoryError> {
        if let Some(history) = &self.history {
            let memory_id = Uuid::parse_str(id).map_err(|e| MemoryError::InvalidInput(e.to_string()))?;
            history.get_history(memory_id)
        } else {
            Ok(Vec::new())
        }
    }

    /// Reset all memories
    pub async fn reset(&self, options: ResetOptions) -> Result<(), MemoryError> {
        // Build filters based on options
        let filters = if options.user_id.is_some() || options.agent_id.is_some() {
            // TODO: Build proper filters
            None
        } else {
            None
        };

        self.vector_store.delete_all(filters.as_ref()).await?;
        
        if let Some(history) = &self.history {
            // If global reset, clear history too
            if filters.is_none() {
                history.reset()?;
            }
        }
        
        Ok(())
    }
}

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

    #[tokio::test]
    async fn test_memory_creation() {
        let config = MemoryConfig::default();
        let memory = Memory::new(config).await;
        assert!(memory.is_ok());
    }

    #[tokio::test]
    async fn test_add_raw() {
        let config = MemoryConfig::default();
        let memory = Memory::new(config).await.unwrap();

        let result = memory
            .add(
                "Test memory content",
                AddOptions {
                    user_id: Some("test_user".to_string()),
                    infer: false,
                    ..Default::default()
                },
            )
            .await;

        assert!(result.is_ok());
        assert_eq!(result.unwrap().results.len(), 1);
    }

    #[tokio::test]
    async fn test_search() {
        let config = MemoryConfig::default();
        let memory = Memory::new(config).await.unwrap();

        // Add a memory
        memory
            .add(
                "I love programming in Rust",
                AddOptions {
                    user_id: Some("test_user".to_string()),
                    infer: false,
                    ..Default::default()
                },
            )
            .await
            .unwrap();

        // Search for it
        let results = memory
            .search(
                "Rust programming",
                SearchOptions {
                    user_id: Some("test_user".to_string()),
                    ..Default::default()
                },
            )
            .await
            .unwrap();

        assert!(!results.results.is_empty());
    }
}