Skip to main content

adk_memory/
service.rs

1use adk_core::{Content, Result};
2use async_trait::async_trait;
3use chrono::{DateTime, Utc};
4use std::time::Duration;
5
6/// One stored memory: what was said or learned, who said it, and when.
7///
8/// | Field | Set by | Meaning |
9/// |-------|--------|---------|
10/// | `id` | [`with_id`](Self::with_id), or the backend when it stores the entry | The handle [`MemoryService::delete_memory`] takes; every entry a backend returns carries one |
11/// | `expires_at` | [`with_ttl`](Self::with_ttl), [`with_expires_at`](Self::with_expires_at), or the service's default TTL | When the entry stops being recalled; `None` keeps it until it is deleted |
12///
13/// [`crate::expiry`] states the expiry rule every backend applies.
14///
15/// # Example
16///
17/// ```rust
18/// use adk_core::Content;
19/// use adk_memory::MemoryEntry;
20/// use std::time::Duration;
21///
22/// let entry = MemoryEntry::new(Content::new("user").with_text("Parking: level 3, bay 12."), "user")
23///     .with_id("parking-today")
24///     .with_ttl(Duration::from_secs(8 * 60 * 60));
25/// assert_eq!(entry.id.as_deref(), Some("parking-today"));
26/// assert!(!entry.is_expired_at(chrono::Utc::now()));
27/// ```
28#[derive(Debug, Clone, PartialEq, serde::Serialize)]
29#[serde(rename_all = "camelCase")]
30#[non_exhaustive]
31pub struct MemoryEntry {
32    /// The entry's id within its user's memory; `None` until a backend stores it, unless set.
33    #[serde(skip_serializing_if = "Option::is_none")]
34    pub id: Option<String>,
35    /// What the memory holds.
36    pub content: Content,
37    /// Who the memory came from.
38    pub author: String,
39    /// When the memory was recorded.
40    pub timestamp: DateTime<Utc>,
41    /// When the memory expires; `None` takes the service's default TTL, or never expires.
42    #[serde(skip_serializing_if = "Option::is_none")]
43    pub expires_at: Option<DateTime<Utc>>,
44}
45
46impl MemoryEntry {
47    /// An entry of `content` by `author`, recorded now, without an id or an expiry.
48    pub fn new(content: Content, author: impl Into<String>) -> Self {
49        Self { id: None, content, author: author.into(), timestamp: Utc::now(), expires_at: None }
50    }
51
52    /// Sets when the memory was recorded.
53    pub fn with_timestamp(mut self, timestamp: DateTime<Utc>) -> Self {
54        self.timestamp = timestamp;
55        self
56    }
57
58    /// Sets the entry's id, so a caller can delete it later without searching for it.
59    ///
60    /// The id should be unique within the user's memory:
61    /// [`delete_memory`](MemoryService::delete_memory) removes every entry carrying it.
62    pub fn with_id(mut self, id: impl Into<String>) -> Self {
63        self.id = Some(id.into());
64        self
65    }
66
67    /// Expires the entry at `expires_at`, overriding the service's default TTL.
68    pub fn with_expires_at(mut self, expires_at: DateTime<Utc>) -> Self {
69        self.expires_at = Some(crate::expiry::to_millis(expires_at));
70        self
71    }
72
73    /// Expires the entry `ttl` from now, overriding the service's default TTL.
74    pub fn with_ttl(self, ttl: Duration) -> Self {
75        let expires_at = crate::expiry::expiry_after(Utc::now(), ttl);
76        self.with_expires_at(expires_at)
77    }
78
79    /// Adds a reference to the artifact at `uri` — an image, a frame, a document — as a
80    /// `Part::FileData` after the entry's text. The text stays what a search matches; the
81    /// reference comes back with the entry.
82    ///
83    /// # Example
84    ///
85    /// ```rust
86    /// use adk_core::Content;
87    /// use adk_memory::MemoryEntry;
88    /// use adk_memory::text::{ArtifactReference, extract_text};
89    ///
90    /// let entry = MemoryEntry::new(Content::new("model").with_text("torn seal, carton 117"), "inspector")
91    ///     .with_artifact("artifact://inspector/u1/s1/vision-ab12.png#0", "image/png");
92    /// assert_eq!(extract_text(&entry.content), "torn seal, carton 117");
93    /// assert_eq!(
94    ///     entry.artifact_references(),
95    ///     vec![ArtifactReference::new("artifact://inspector/u1/s1/vision-ab12.png#0", "image/png")]
96    /// );
97    /// ```
98    pub fn with_artifact(mut self, uri: impl Into<String>, mime_type: impl Into<String>) -> Self {
99        self.content.parts.push(crate::text::ArtifactReference::new(uri, mime_type).to_part());
100        self
101    }
102
103    /// The artifacts the entry refers to, by [`crate::text::artifact_references`].
104    pub fn artifact_references(&self) -> Vec<crate::text::ArtifactReference> {
105        crate::text::artifact_references(&self.content)
106    }
107
108    /// Whether the entry has expired at `now`, by [`crate::expiry::is_expired`].
109    pub fn is_expired_at(&self, now: DateTime<Utc>) -> bool {
110        crate::expiry::is_expired(self.expires_at, now)
111    }
112}
113
114/// One stored memory of a user, as [`MemoryService::export_user`] returns it.
115///
116/// # Example
117///
118/// ```rust
119/// use adk_core::Content;
120/// use adk_memory::{MemoryEntry, UserMemory};
121///
122/// let memory = UserMemory {
123///     entry: MemoryEntry::new(Content::new("user").with_text("Hometown: Nairobi."), "user")
124///         .with_id("m1"),
125///     session_id: Some("s1".to_string()),
126///     project_id: None,
127/// };
128/// let json = serde_json::to_value(&memory).unwrap();
129/// assert_eq!(json["sessionId"], "s1");
130/// assert_eq!(json["author"], "user");
131/// assert_eq!(json["id"], "m1");
132/// ```
133#[derive(Debug, Clone, serde::Serialize)]
134#[serde(rename_all = "camelCase")]
135pub struct UserMemory {
136    /// The entry.
137    #[serde(flatten)]
138    pub entry: MemoryEntry,
139    /// The session the entry was added from; `None` for an entry added directly.
140    #[serde(skip_serializing_if = "Option::is_none")]
141    pub session_id: Option<String>,
142    /// The project the entry is scoped to; `None` for a global entry.
143    #[serde(skip_serializing_if = "Option::is_none")]
144    pub project_id: Option<String>,
145}
146
147#[derive(Debug, Clone, serde::Deserialize)]
148pub struct SearchRequest {
149    pub query: String,
150    pub user_id: String,
151    pub app_name: String,
152    /// Maximum number of results to return. `None` defaults to 10.
153    pub limit: Option<usize>,
154    /// Minimum similarity score threshold (0.0–1.0). Results below this
155    /// score are excluded. `None` means no threshold.
156    pub min_score: Option<f32>,
157    /// Optional project scope. `None` returns only global entries.
158    /// `Some(id)` returns global entries + entries for that project.
159    #[serde(default)]
160    pub project_id: Option<String>,
161}
162
163#[derive(Debug, Clone)]
164pub struct SearchResponse {
165    pub memories: Vec<MemoryEntry>,
166}
167
168/// Validate a project identifier.
169///
170/// Returns `Ok(())` if the project_id is non-empty and at most 256 characters.
171/// Returns a descriptive error otherwise.
172pub fn validate_project_id(project_id: &str) -> Result<()> {
173    if project_id.is_empty() {
174        return Err(adk_core::AdkError::memory("project_id must not be empty"));
175    }
176    if project_id.len() > 256 {
177        return Err(adk_core::AdkError::memory(format!(
178            "project_id exceeds maximum length of 256 characters (got {})",
179            project_id.len()
180        )));
181    }
182    Ok(())
183}
184
185#[async_trait]
186pub trait MemoryService: Send + Sync {
187    async fn add_session(
188        &self,
189        app_name: &str,
190        user_id: &str,
191        session_id: &str,
192        entries: Vec<MemoryEntry>,
193    ) -> Result<()>;
194    async fn search(&self, req: SearchRequest) -> Result<SearchResponse>;
195
196    /// Delete all memory entries for a specific user.
197    ///
198    /// Removes every stored memory of the user in the app, embeddings and
199    /// project-scoped entries included.
200    async fn delete_user(&self, app_name: &str, user_id: &str) -> Result<()> {
201        let _ = (app_name, user_id);
202        Err(adk_core::AdkError::memory("delete_user not implemented"))
203    }
204
205    /// Returns every memory held for `user_id` in `app_name` — added from a session or
206    /// directly, global or project-scoped — oldest first. [`delete_user`](Self::delete_user)
207    /// removes exactly these.
208    ///
209    /// [`MemorySubjectData`](crate::MemorySubjectData) exports a data subject's memory
210    /// through it.
211    ///
212    /// # Errors
213    ///
214    /// The default returns `subject.unsupported`
215    /// ([`SUBJECT_UNSUPPORTED_CODE`](adk_core::subject::SUBJECT_UNSUPPORTED_CODE)), so a
216    /// backend that cannot list a user's entries is reported, not silently empty.
217    async fn export_user(&self, app_name: &str, user_id: &str) -> Result<Vec<UserMemory>> {
218        let _ = (app_name, user_id);
219        Err(adk_core::subject::unsupported_error("memory", "export"))
220    }
221
222    /// Delete all memory entries for a specific session.
223    async fn delete_session(&self, app_name: &str, user_id: &str, session_id: &str) -> Result<()> {
224        let _ = (app_name, user_id, session_id);
225        Err(adk_core::AdkError::memory("delete_session not implemented"))
226    }
227
228    /// Add a single memory entry directly (not tied to a session).
229    async fn add_entry(&self, app_name: &str, user_id: &str, entry: MemoryEntry) -> Result<()> {
230        let _ = (app_name, user_id, entry);
231        Err(adk_core::AdkError::memory("add_entry not implemented"))
232    }
233
234    /// Delete entries matching a query. Returns count of deleted entries.
235    async fn delete_entries(&self, app_name: &str, user_id: &str, query: &str) -> Result<u64> {
236        let _ = (app_name, user_id, query);
237        Err(adk_core::AdkError::memory("delete_entries not implemented"))
238    }
239
240    /// List the most recent entries for a user (global + project-scoped),
241    /// newest first. Unlike `search`, this is a pure recency listing — no
242    /// query, no similarity ranking — suitable for "what does the agent
243    /// remember?" UIs and latest-item lookups.
244    async fn list_recent(
245        &self,
246        app_name: &str,
247        user_id: &str,
248        limit: usize,
249    ) -> Result<Vec<MemoryEntry>> {
250        let _ = (app_name, user_id, limit);
251        Err(adk_core::AdkError::memory("list_recent not implemented"))
252    }
253
254    /// Deletes the memory `memory_id` of `user_id` in `app_name`, global or in any project,
255    /// and returns how many entries it removed: 0 when the user holds none with that id.
256    ///
257    /// `memory_id` is the [`MemoryEntry::id`] a search, listing or export returned, or the id
258    /// the caller set with [`MemoryEntry::with_id`]. Another user's entry with the same id is
259    /// never touched.
260    ///
261    /// # Errors
262    ///
263    /// The default returns an error, so a backend that cannot delete one entry is reported
264    /// rather than silently keeping it.
265    async fn delete_memory(&self, app_name: &str, user_id: &str, memory_id: &str) -> Result<u64> {
266        let _ = (app_name, user_id, memory_id);
267        Err(adk_core::AdkError::memory(
268            "delete_memory is not implemented by this memory backend; every adk-memory backend \
269             implements it, or remove the user's entries with delete_user",
270        ))
271    }
272
273    /// Removes every stored entry whose expiry has passed, across all apps and users, and
274    /// returns how many it removed.
275    ///
276    /// Reads never return an expired entry, so a purge reclaims storage without changing what
277    /// a search recalls. A backend whose store expires data natively (Redis key expiry, the
278    /// MongoDB TTL index, Memory Bank) also removes entries on the store's own schedule; the
279    /// count covers only what this call removed. [`crate::expiry::spawn_expiry_sweep`] runs
280    /// it on an interval.
281    ///
282    /// # Errors
283    ///
284    /// The default returns an error, so a backend that cannot purge is reported rather than
285    /// silently keeping expired entries.
286    async fn purge_expired(&self) -> Result<u64> {
287        Err(adk_core::AdkError::memory(
288            "purge_expired is not implemented by this memory backend; every adk-memory backend \
289             implements it",
290        ))
291    }
292
293    /// Verify backend connectivity.
294    ///
295    /// Returns `Ok(())` if the backend is reachable and responsive.
296    /// The default implementation always succeeds (suitable for in-memory).
297    async fn health_check(&self) -> Result<()> {
298        Ok(())
299    }
300
301    /// Whether this backend keeps project-scoped entries isolated.
302    ///
303    /// Returns `false` by default. A backend that implements the project methods
304    /// below overrides this to `true`, so a caller can tell isolation apart from a
305    /// backend that has no project support rather than discovering it from data.
306    fn supports_project_scoping(&self) -> bool {
307        false
308    }
309
310    /// Adds session entries scoped to a project.
311    ///
312    /// # Errors
313    ///
314    /// The default implementation returns an error. Discarding `project_id` and
315    /// writing globally would make entries intended for one project visible to
316    /// everything else under the same app and user, with nothing in the return value
317    /// to say so, so a backend without project support refuses the write instead.
318    async fn add_session_to_project(
319        &self,
320        app_name: &str,
321        user_id: &str,
322        session_id: &str,
323        project_id: &str,
324        entries: Vec<MemoryEntry>,
325    ) -> Result<()> {
326        let _ = (app_name, user_id, session_id, project_id, entries);
327        Err(project_scoping_unsupported("add_session_to_project"))
328    }
329
330    /// Adds a single entry scoped to a project.
331    ///
332    /// # Errors
333    ///
334    /// Returns an error by default, for the reason given on
335    /// [`MemoryService::add_session_to_project`].
336    async fn add_entry_to_project(
337        &self,
338        app_name: &str,
339        user_id: &str,
340        project_id: &str,
341        entry: MemoryEntry,
342    ) -> Result<()> {
343        let _ = (app_name, user_id, project_id, entry);
344        Err(project_scoping_unsupported("add_entry_to_project"))
345    }
346
347    /// Deletes entries matching a query within a specific project.
348    ///
349    /// # Errors
350    ///
351    /// Returns an error by default. Falling back to a global delete would remove
352    /// entries outside the named project, which is worse than refusing.
353    async fn delete_entries_in_project(
354        &self,
355        app_name: &str,
356        user_id: &str,
357        project_id: &str,
358        query: &str,
359    ) -> Result<u64> {
360        let _ = (app_name, user_id, project_id, query);
361        Err(project_scoping_unsupported("delete_entries_in_project"))
362    }
363
364    /// Delete all entries for a specific project.
365    /// Default returns "not implemented" error.
366    async fn delete_project(&self, app_name: &str, user_id: &str, project_id: &str) -> Result<u64> {
367        let _ = (app_name, user_id, project_id);
368        Err(adk_core::AdkError::memory("delete_project not implemented"))
369    }
370}
371
372/// The error a backend without project support returns from a project method.
373fn project_scoping_unsupported(method: &str) -> adk_core::AdkError {
374    adk_core::AdkError::memory(format!(
375        "this memory backend does not implement project scoping, so `{method}` cannot honour \
376         the project boundary; use a backend whose `supports_project_scoping` returns true, or \
377         call the global method explicitly if global scope is intended"
378    ))
379}