Skip to main content

aidaemon_memory/
recall.rs

1//! [`MemoryRecall`]: plugs [`Memory`] into
2//! `aidaemon_policies::MemoryInjection` through the `Recall` trait.
3
4use aidaemon_policies::Recall;
5use async_trait::async_trait;
6
7use crate::memory::Memory;
8
9/// An `aidaemon_policies::Recall` backed by [`Memory`]: top facts first,
10/// then relevant episodes, as one-line snippets. Errors are logged and
11/// yield no snippets, so a memory outage never breaks a run.
12///
13/// ```
14/// use aidaemon_memory::{HashEmbedder, InMemoryMemoryStore, Memory, MemoryRecall};
15///
16/// let memory = Memory::new(InMemoryMemoryStore::new(), HashEmbedder::default());
17/// let hook = aidaemon_policies::MemoryInjection::new(MemoryRecall::new(memory));
18/// # let _ = hook;
19/// ```
20pub struct MemoryRecall {
21    memory: Memory,
22    max_episodes: usize,
23}
24
25impl MemoryRecall {
26    pub fn new(memory: Memory) -> Self {
27        Self {
28            memory,
29            max_episodes: 2,
30        }
31    }
32
33    /// At most this many episode snippets (default 2), within the limit.
34    pub fn max_episodes(mut self, n: usize) -> Self {
35        self.max_episodes = n;
36        self
37    }
38}
39
40#[async_trait]
41impl Recall for MemoryRecall {
42    async fn recall(&self, session_id: &str, query: &str, limit: usize) -> Vec<String> {
43        if limit == 0 || query.trim().is_empty() {
44            return Vec::new();
45        }
46        let scope = self.memory.scope_for(session_id);
47        let audience = self.memory.audience_for(session_id);
48        let mut out: Vec<String> = match self
49            .memory
50            .recall_facts_for(&scope, query, limit, &audience)
51            .await
52        {
53            Ok(facts) => facts
54                .into_iter()
55                .map(|f| {
56                    format!(
57                        "{} {}: {}",
58                        f.fact.category,
59                        f.fact.key.replace('_', " "),
60                        f.fact.value
61                    )
62                })
63                .collect(),
64            Err(error) => {
65                tracing::warn!(%error, "fact recall failed");
66                Vec::new()
67            }
68        };
69        let room = limit.saturating_sub(out.len()).min(self.max_episodes);
70        if room > 0 {
71            match self
72                .memory
73                .recall_episodes_for(&scope, query, room, &audience)
74                .await
75            {
76                Ok(episodes) => out.extend(episodes.into_iter().map(|e| {
77                    format!(
78                        "Earlier conversation ({}): {}",
79                        e.episode.created_at.format("%Y-%m-%d"),
80                        e.episode.summary
81                    )
82                })),
83                Err(error) => tracing::warn!(%error, "episode recall failed"),
84            }
85        }
86        out
87    }
88}