Skip to main content

adk_tool/memory/
load_memory.rs

1//! LoadMemoryTool — an agent-callable tool for searching long-term memory.
2//!
3//! Agents invoke this tool during reasoning to retrieve relevant context
4//! from the configured [`MemoryService`].
5
6use std::sync::Arc;
7
8use adk_core::{AdkError, Result, Tool, ToolContext};
9use adk_memory::{MemoryService, SearchRequest};
10use async_trait::async_trait;
11use serde_json::{Value, json};
12
13use super::config::MemoryToolConfig;
14use super::format::format_memory_results;
15
16/// A tool that searches the agent's long-term memory on demand.
17///
18/// Agents call this tool during reasoning to retrieve relevant memories.
19/// It delegates to the configured [`MemoryService`] and returns formatted results.
20///
21/// # Example
22///
23/// ```rust,ignore
24/// use adk_tool::memory::LoadMemoryTool;
25/// use adk_memory::InMemoryMemoryService;
26/// use std::sync::Arc;
27///
28/// let service = Arc::new(InMemoryMemoryService::new());
29/// let tool = LoadMemoryTool::builder()
30///     .memory_service(service)
31///     .max_results(5)
32///     .build()
33///     .unwrap();
34/// ```
35pub struct LoadMemoryTool {
36    memory_service: Arc<dyn MemoryService>,
37    config: MemoryToolConfig,
38}
39
40#[async_trait]
41impl Tool for LoadMemoryTool {
42    fn name(&self) -> &str {
43        "load_memory"
44    }
45
46    fn description(&self) -> &str {
47        "Search the agent's long-term memory for relevant information. \
48         Use this when you need to recall past conversations, facts, or context."
49    }
50
51    fn is_read_only(&self) -> bool {
52        true
53    }
54
55    fn is_concurrency_safe(&self) -> bool {
56        true
57    }
58
59    fn parameters_schema(&self) -> Option<Value> {
60        Some(json!({
61            "type": "object",
62            "properties": {
63                "query": {
64                    "type": "string",
65                    "description": "The search query to find relevant memories"
66                },
67                "limit": {
68                    "type": "integer",
69                    "description": "Maximum number of results to return",
70                    "minimum": 1,
71                    "maximum": 100
72                }
73            },
74            "required": ["query"]
75        }))
76    }
77
78    async fn execute(&self, ctx: Arc<dyn ToolContext>, args: Value) -> Result<Value> {
79        let query = args
80            .get("query")
81            .and_then(|v| v.as_str())
82            .ok_or_else(|| AdkError::tool("query parameter is required"))?
83            .to_string();
84
85        let limit = args
86            .get("limit")
87            .and_then(|v| v.as_u64())
88            .map(|v| (v as usize).min(self.config.max_results))
89            .unwrap_or(self.config.max_results);
90
91        let request = SearchRequest {
92            query,
93            user_id: ctx.user_id().to_string(),
94            app_name: ctx.app_name().to_string(),
95            limit: Some(limit),
96            min_score: self.config.min_relevance_score,
97            project_id: self.config.project_id.clone(),
98        };
99
100        let response = self.memory_service.search(request).await?;
101        Ok(format_memory_results(&response.memories))
102    }
103}
104
105impl LoadMemoryTool {
106    /// Create a new builder for `LoadMemoryTool`.
107    pub fn builder() -> LoadMemoryToolBuilder {
108        LoadMemoryToolBuilder::default()
109    }
110}
111
112/// Builder for [`LoadMemoryTool`].
113#[derive(Default)]
114pub struct LoadMemoryToolBuilder {
115    memory_service: Option<Arc<dyn MemoryService>>,
116    config: MemoryToolConfig,
117}
118
119impl LoadMemoryToolBuilder {
120    /// Set the memory service implementation.
121    pub fn memory_service(mut self, service: Arc<dyn MemoryService>) -> Self {
122        self.memory_service = Some(service);
123        self
124    }
125
126    /// Set the maximum number of results to return.
127    pub fn max_results(mut self, max: usize) -> Self {
128        self.config.max_results = max;
129        self
130    }
131
132    /// Set the minimum relevance score threshold.
133    pub fn min_relevance_score(mut self, score: f32) -> Self {
134        self.config.min_relevance_score = Some(score);
135        self
136    }
137
138    /// Set the project identifier for scoped searches.
139    pub fn project_id(mut self, id: impl Into<String>) -> Self {
140        self.config.project_id = Some(id.into());
141        self
142    }
143
144    /// Build the `LoadMemoryTool`, validating configuration.
145    ///
146    /// # Errors
147    ///
148    /// Returns an error if:
149    /// - `memory_service` is not configured
150    /// - `max_results` is outside [1, 100]
151    /// - `min_relevance_score` is outside [0.0, 1.0]
152    pub fn build(self) -> Result<LoadMemoryTool> {
153        let memory_service = self
154            .memory_service
155            .ok_or_else(|| AdkError::tool("memory_service is required for LoadMemoryTool"))?;
156
157        self.config.validate()?;
158
159        Ok(LoadMemoryTool { memory_service, config: self.config })
160    }
161}
162
163#[cfg(test)]
164mod tests {
165    use super::*;
166    use adk_core::{Content, EventActions, ReadonlyContext};
167    use adk_memory::{InMemoryMemoryService, MemoryEntry};
168    use std::sync::Mutex;
169
170    struct MockToolContext {
171        content: Content,
172        actions: Mutex<EventActions>,
173    }
174
175    impl MockToolContext {
176        fn new() -> Self {
177            Self {
178                content: Content::new("user").with_text("test input"),
179                actions: Mutex::new(EventActions::default()),
180            }
181        }
182    }
183
184    #[async_trait]
185    impl ReadonlyContext for MockToolContext {
186        fn invocation_id(&self) -> &str {
187            "inv-1"
188        }
189        fn agent_name(&self) -> &str {
190            "test-agent"
191        }
192        fn user_id(&self) -> &str {
193            "user-1"
194        }
195        fn app_name(&self) -> &str {
196            "test-app"
197        }
198        fn session_id(&self) -> &str {
199            "session-1"
200        }
201        fn branch(&self) -> &str {
202            ""
203        }
204        fn user_content(&self) -> &Content {
205            &self.content
206        }
207    }
208
209    #[async_trait]
210    impl adk_core::CallbackContext for MockToolContext {
211        fn artifacts(&self) -> Option<Arc<dyn adk_core::Artifacts>> {
212            None
213        }
214    }
215
216    #[async_trait]
217    impl ToolContext for MockToolContext {
218        fn function_call_id(&self) -> &str {
219            "call-1"
220        }
221        fn actions(&self) -> EventActions {
222            self.actions.lock().unwrap().clone()
223        }
224        fn set_actions(&self, actions: EventActions) {
225            *self.actions.lock().unwrap() = actions;
226        }
227        async fn search_memory(&self, _query: &str) -> Result<Vec<adk_core::MemoryEntry>> {
228            Ok(vec![])
229        }
230    }
231
232    #[test]
233    fn test_tool_metadata() {
234        let service = Arc::new(InMemoryMemoryService::new());
235        let tool = LoadMemoryTool::builder().memory_service(service).build().unwrap();
236
237        assert_eq!(tool.name(), "load_memory");
238        assert!(tool.is_read_only());
239        assert!(tool.is_concurrency_safe());
240        assert!(tool.parameters_schema().is_some());
241    }
242
243    #[test]
244    fn test_builder_missing_service() {
245        let result = LoadMemoryTool::builder().build();
246        assert!(result.is_err());
247    }
248
249    #[test]
250    fn test_builder_invalid_max_results() {
251        let service = Arc::new(InMemoryMemoryService::new());
252        let result = LoadMemoryTool::builder().memory_service(service).max_results(0).build();
253        assert!(result.is_err());
254    }
255
256    #[tokio::test]
257    async fn test_execute_with_query() {
258        let service = Arc::new(InMemoryMemoryService::new());
259
260        // Add a memory entry
261        let entry = MemoryEntry::new(
262            Content::new("user").with_text("The capital of France is Paris"),
263            "user",
264        );
265        service.add_session("test-app", "user-1", "session-1", vec![entry]).await.unwrap();
266
267        let tool = LoadMemoryTool::builder().memory_service(service).build().unwrap();
268
269        let ctx = Arc::new(MockToolContext::new()) as Arc<dyn ToolContext>;
270        let args = json!({"query": "capital of France"});
271        let result = tool.execute(ctx, args).await.unwrap();
272
273        assert_eq!(result["count"], 1);
274        let memories = result["memories"].as_array().unwrap();
275        assert_eq!(memories[0]["content"], "The capital of France is Paris");
276    }
277
278    #[tokio::test]
279    async fn test_execute_missing_query() {
280        let service = Arc::new(InMemoryMemoryService::new());
281        let tool = LoadMemoryTool::builder().memory_service(service).build().unwrap();
282
283        let ctx = Arc::new(MockToolContext::new()) as Arc<dyn ToolContext>;
284        let args = json!({});
285        let result = tool.execute(ctx, args).await;
286        assert!(result.is_err());
287    }
288
289    #[tokio::test]
290    async fn test_execute_empty_results() {
291        let service = Arc::new(InMemoryMemoryService::new());
292        let tool = LoadMemoryTool::builder().memory_service(service).build().unwrap();
293
294        let ctx = Arc::new(MockToolContext::new()) as Arc<dyn ToolContext>;
295        let args = json!({"query": "nonexistent"});
296        let result = tool.execute(ctx, args).await.unwrap();
297
298        assert_eq!(result["count"], 0);
299        assert_eq!(result["memories"].as_array().unwrap().len(), 0);
300    }
301
302    #[test]
303    fn test_parameters_schema_structure() {
304        let service = Arc::new(InMemoryMemoryService::new());
305        let tool = LoadMemoryTool::builder().memory_service(service).build().unwrap();
306
307        let schema = tool.parameters_schema().unwrap();
308        assert_eq!(schema["type"], "object");
309        assert!(schema["properties"]["query"].is_object());
310        assert_eq!(schema["properties"]["query"]["type"], "string");
311        assert!(schema["properties"]["limit"].is_object());
312        assert_eq!(schema["properties"]["limit"]["type"], "integer");
313
314        let required = schema["required"].as_array().unwrap();
315        assert!(required.contains(&json!("query")));
316    }
317}