Skip to main content

temporal_replacement/
temporal_replacement.rs

1//! Demonstrates temporal replacement: an old fact is invalidated and the new
2//! fact is the only one recalled.
3//!
4//! Run: `cargo run --example temporal_replacement -p basemyai`
5
6use basemyai::{AgentId, Memory, MemoryLayer};
7use basemyai_core::{Embedder, Store};
8
9const DIM: usize = 384;
10
11struct DemoEmbedder;
12
13impl DemoEmbedder {
14    fn vec_for(text: &str) -> Vec<f32> {
15        let mut v = vec![0.0_f32; DIM];
16        for (i, b) in text.bytes().enumerate() {
17            v[i % DIM] += f32::from(b) + 1.0;
18        }
19        v[0] += 1.0;
20        v
21    }
22}
23
24impl Embedder for DemoEmbedder {
25    fn embed(&self, text: &str) -> basemyai_core::Result<Vec<f32>> {
26        Ok(Self::vec_for(text))
27    }
28
29    fn embed_batch(&self, texts: &[String]) -> basemyai_core::Result<Vec<Vec<f32>>> {
30        Ok(texts.iter().map(|t| Self::vec_for(t)).collect())
31    }
32
33    fn model_id(&self) -> &str {
34        "demo-deterministic"
35    }
36
37    fn dim(&self) -> usize {
38        DIM
39    }
40}
41
42#[tokio::main]
43async fn main() -> Result<(), Box<dyn std::error::Error>> {
44    let store = Store::open_in_memory().await?;
45    let agent = AgentId::new("temporal-demo").expect("non-empty id");
46    let memory = Memory::open(store, Box::new(DemoEmbedder), agent).await?;
47
48    let old_id = memory
49        .remember("The user is on the Free billing plan.", MemoryLayer::Semantic)
50        .await?;
51
52    println!("Initially remembered: Free plan ({old_id})");
53
54    memory.invalidate(&old_id).await?;
55    let new_id = memory
56        .remember("The user is on the Pro billing plan.", MemoryLayer::Semantic)
57        .await?;
58
59    println!("Invalidated old fact and remembered: Pro plan ({new_id})");
60
61    let hits = memory.recall_hybrid("current billing plan", 5).await?;
62    println!("\nRecall for `current billing plan`:");
63    for hit in &hits {
64        println!("  [{layer}] {text}", layer = hit.layer.table(), text = hit.text);
65    }
66
67    assert!(
68        hits.iter().any(|r| r.text.contains("Pro billing plan")),
69        "the current fact should be recalled"
70    );
71    assert!(
72        hits.iter().all(|r| !r.text.contains("Free billing plan")),
73        "the invalidated fact should not be recalled"
74    );
75
76    Ok(())
77}