gadk_memory/service.rs
1// Copyright 2026 Chris Olson
2// Portions derived from ADK-Go (https://github.com/google/adk-go), Copyright 2026 Google LLC.
3//
4// Licensed under the Apache License, Version 2.0 (the "License");
5// you may not use this file except in compliance with the License.
6// You may obtain a copy of the License at
7//
8// http://www.apache.org/licenses/LICENSE-2.0
9//
10// Unless required by applicable law or agreed to in writing, software
11// distributed under the License is distributed on an "AS IS" BASIS,
12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13// See the License for the specific language governing permissions and
14// limitations under the License.
15
16//! The memory service API: entities to interact with agent
17//! memory (long-term knowledge).
18
19use async_trait::async_trait;
20use chrono::{DateTime, Utc};
21use gadk_genai::Content;
22use gadk_session::{Event, Session, SessionError};
23use serde_json::{Map, Value};
24
25/// The memory service.
26///
27/// The service ingests sessions into memory so that it can be used for user queries across
28/// user-scoped sessions.
29#[async_trait]
30pub trait MemoryService: Send + Sync {
31 /// Adds a session to the memory service.
32 ///
33 /// A session can be added multiple times during its lifetime.
34 async fn add_session_to_memory(&self, session: &dyn Session) -> Result<(), MemoryError>;
35
36 /// Returns memory entries relevant to the given query.
37 /// Empty slice is returned if there are no matches.
38 async fn search_memory(&self, req: SearchRequest) -> Result<SearchResponse, MemoryError>;
39
40 /// The service's [`EventAdder`], when it can ingest an incremental delta of events;
41 /// `None` by default.
42 ///
43 /// A type that wraps a service forwards this method itself, or its wrapped adder is not
44 /// reachable through [`add_events_to_memory`].
45 ///
46 /// EXPERIMENTAL: its API and behavior may change or be removed later.
47 fn as_event_adder(&self) -> Option<&dyn EventAdder> {
48 None
49 }
50}
51
52/// An optional capability of a [`MemoryService`] that can ingest
53/// an incremental delta of events without re-ingesting a full session. A service exposes it
54/// through [`MemoryService::as_event_adder`]; [`crate::InMemoryMemoryService`] implements it.
55///
56/// EXPERIMENTAL: its API and behavior may change or be removed later.
57#[async_trait]
58pub trait EventAdder: Send + Sync {
59 /// Appends an incremental batch of events to the memory service for the scope named by
60 /// `req`. Events already stored for the scope are kept: the batch
61 /// never replaces them. Implementations document how they treat events that repeat an ID
62 /// already stored.
63 async fn add_events(&self, req: AddEventsRequest) -> Result<(), MemoryError>;
64}
65
66/// The parameter of [`EventAdder::add_events`] and
67/// [`add_events_to_memory`].
68///
69/// EXPERIMENTAL: its API and behavior may change or be removed later.
70#[derive(Debug, Clone, Default, PartialEq)]
71pub struct AddEventsRequest {
72 /// The application name for memory scope.
73 pub app_name: String,
74 /// The user ID for memory scope.
75 pub user_id: String,
76 /// The optional session ID for memory partitioning. In the in-memory service an empty ID
77 /// places the events in a shared default bucket per (app, user), distinct from the bucket
78 /// of every session, including a session whose ID is `""` added with
79 /// [`MemoryService::add_session_to_memory`]. Implementations for which session
80 /// partitioning does not apply may ignore it.
81 pub session_id: String,
82 /// The ordered events to add to memory.
83 pub events: Vec<Event>,
84 /// Optional, implementation-defined metadata for memory generation. The in-memory service
85 /// ignores it.
86 pub custom_metadata: Map<String, Value>,
87}
88
89/// Adds `req.events` to `svc` through its
90/// [`EventAdder`], or returns [`MemoryError::AddEventsUnsupported`] when `svc` has none.
91///
92/// EXPERIMENTAL: its API and behavior may change or be removed later.
93pub async fn add_events_to_memory(
94 svc: &dyn MemoryService,
95 req: AddEventsRequest,
96) -> Result<(), MemoryError> {
97 let adder = svc
98 .as_event_adder()
99 .ok_or(MemoryError::AddEventsUnsupported)?;
100 adder.add_events(req).await
101}
102
103/// A request for memory search.
104#[derive(Debug, Clone, Default, PartialEq)]
105pub struct SearchRequest {
106 /// The search query.
107 pub query: String,
108 /// The user whose memories are searched.
109 pub user_id: String,
110 /// The app whose memories are searched.
111 pub app_name: String,
112}
113
114/// The response from a memory search.
115#[derive(Debug, Clone, Default, PartialEq)]
116pub struct SearchResponse {
117 /// The matching memory entries.
118 pub memories: Vec<MemoryEntry>,
119}
120
121/// A single memory entry.
122#[derive(Debug, Clone, Default, PartialEq)]
123pub struct MemoryEntry {
124 /// The unique identifier of the memory.
125 pub id: String,
126 /// The main content of the memory.
127 pub content: Option<Content>,
128 /// Author of the memory.
129 pub author: String,
130 /// When the original content of this memory happened. It is forwarded to the LLM formatted
131 /// as ISO 8601. `None` when the event's timestamp is unset (the zero time).
132 pub timestamp: Option<DateTime<Utc>>,
133 /// Optional custom metadata associated with the memory.
134 pub custom_metadata: Map<String, Value>,
135}
136
137/// Errors returned by a [`MemoryService`].
138#[non_exhaustive]
139#[derive(Debug, thiserror::Error)]
140pub enum MemoryError {
141 /// The request was invalid.
142 #[error("{0}")]
143 InvalidRequest(String),
144 /// A session operation failed.
145 #[error(transparent)]
146 Session(#[from] SessionError),
147 /// The storage backend failed.
148 #[error(transparent)]
149 Backend(Box<dyn std::error::Error + Send + Sync>),
150 /// The service does not implement [`EventAdder`]. A caller that receives it can ingest the
151 /// full session with [`MemoryService::add_session_to_memory`] instead, as its message says.
152 #[error(
153 "memory: service does not support adding event deltas; call Service.AddSessionToMemory to ingest the full session"
154 )]
155 AddEventsUnsupported,
156}