Skip to main content

adk_tool/memory/
graph.rs

1//! Knowledge-graph memory tools — agent-callable **write/curation** for the
2//! bi-temporal graph in [`adk_memory::GraphMemoryService`].
3//!
4//! Recall is already covered by [`LoadMemoryTool`](super::LoadMemoryTool), which
5//! works over any [`MemoryService`](adk_memory::MemoryService) — including
6//! `GraphMemoryService`. What the base `MemoryService` trait can't express is
7//! *structured writes*: creating entities, attaching observations, and relating
8//! entities. These tools expose the graph's concrete inherent ops so an agent
9//! can curate its own long-term memory:
10//!
11//! - [`RememberTool`] (`remember`) — save durable facts about an entity.
12//! - [`RelateTool`] (`relate`) — record a typed relationship between entities.
13//! - [`GraphMemoryToolset`] — bundles both, so an agent opts in with one line.
14//!
15//! All three are scoped to the calling invocation's `(app_name, user_id)` taken
16//! from the [`ToolContext`], exactly like [`LoadMemoryTool`](super::LoadMemoryTool).
17//!
18//! # Feature gate
19//!
20//! Requires `graph-memory-tools` (which enables `memory-tools` and
21//! `adk-memory/graph-memory`):
22//!
23//! ```toml
24//! adk-tool = { version = "3.0.0", features = ["graph-memory-tools"] }
25//! ```
26//!
27//! # Example
28//!
29//! ```rust,ignore
30//! use adk_tool::memory::GraphMemoryToolset;
31//! use adk_memory::GraphMemoryService;
32//! use std::sync::Arc;
33//!
34//! let kg = Arc::new(GraphMemoryService::new("sqlite:kg.db").await?);
35//! kg.migrate().await?;
36//! // Add the whole KG curation toolset to an agent:
37//! let toolset = GraphMemoryToolset::new(kg);
38//! ```
39
40use std::collections::HashSet;
41use std::sync::Arc;
42
43use adk_core::{AdkError, ReadonlyContext, Result, Tool, ToolContext, Toolset};
44use adk_memory::{CreateEntityInput, CreateRelationInput, GraphMemoryService};
45use async_trait::async_trait;
46use serde_json::{Value, json};
47
48/// Default entity category used when the caller doesn't supply one.
49const DEFAULT_ENTITY_TYPE: &str = "general";
50
51// ─── remember ────────────────────────────────────────────────────────────────
52
53/// A tool that saves durable facts about an entity into the knowledge graph.
54///
55/// Appends to the entity if it already exists (preserving its type); otherwise
56/// creates it. Intended for stable facts — names, preferences, goals, life
57/// events — not transient conversation.
58pub struct RememberTool {
59    kg: Arc<GraphMemoryService>,
60}
61
62impl RememberTool {
63    /// Create a `remember` tool backed by the given graph.
64    pub fn new(kg: Arc<GraphMemoryService>) -> Self {
65        Self { kg }
66    }
67}
68
69#[async_trait]
70impl Tool for RememberTool {
71    fn name(&self) -> &str {
72        "remember"
73    }
74
75    fn description(&self) -> &str {
76        "Save durable facts about an entity (e.g. the user) to long-term memory. \
77         Use for stable, reusable facts — name spelling, preferences, goals, \
78         relationships, life events — not small talk. Do not re-save facts you \
79         already know. `entity` is what the facts are about (e.g. the user's \
80         name); `facts` is one or more short statements."
81    }
82
83    fn parameters_schema(&self) -> Option<Value> {
84        Some(json!({
85            "type": "object",
86            "properties": {
87                "entity": {
88                    "type": "string",
89                    "description": "The thing the facts are about (e.g. a person's name, a place, a topic)."
90                },
91                "entity_type": {
92                    "type": "string",
93                    "description": "Optional category for a new entity, e.g. \"person\", \"place\", \"preference\". Ignored if the entity already exists."
94                },
95                "facts": {
96                    "type": "array",
97                    "items": { "type": "string" },
98                    "minItems": 1,
99                    "description": "One or more short factual statements to remember."
100                }
101            },
102            "required": ["entity", "facts"]
103        }))
104    }
105
106    async fn execute(&self, ctx: Arc<dyn ToolContext>, args: Value) -> Result<Value> {
107        let entity = args
108            .get("entity")
109            .and_then(|v| v.as_str())
110            .map(str::trim)
111            .filter(|s| !s.is_empty())
112            .ok_or_else(|| AdkError::tool("`entity` is required and must be a non-empty string"))?
113            .to_string();
114
115        let facts: Vec<String> = args
116            .get("facts")
117            .and_then(|v| v.as_array())
118            .map(|arr| {
119                arr.iter()
120                    .filter_map(|v| v.as_str())
121                    .map(|s| s.trim().to_string())
122                    .filter(|s| !s.is_empty())
123                    .collect()
124            })
125            .unwrap_or_default();
126        if facts.is_empty() {
127            return Err(AdkError::tool("`facts` must contain at least one non-empty string"));
128        }
129
130        let entity_type = args.get("entity_type").and_then(|v| v.as_str()).map(str::trim);
131        let app = ctx.app_name();
132        let user = ctx.user_id();
133
134        if let Some(ty) = entity_type.filter(|s| !s.is_empty()) {
135            // Explicit type: upsert the entity (sets/updates type) and append facts.
136            self.kg
137                .create_entities(
138                    app,
139                    user,
140                    vec![CreateEntityInput {
141                        name: entity.clone(),
142                        entity_type: ty.to_string(),
143                        observations: facts.clone(),
144                    }],
145                )
146                .await?;
147        } else {
148            // No type given: prefer appending so an existing entity's type is
149            // preserved; fall back to creating it (as "general") if unknown.
150            if self.kg.add_observations(app, user, &entity, facts.clone()).await.is_err() {
151                self.kg
152                    .create_entities(
153                        app,
154                        user,
155                        vec![CreateEntityInput {
156                            name: entity.clone(),
157                            entity_type: DEFAULT_ENTITY_TYPE.to_string(),
158                            observations: facts.clone(),
159                        }],
160                    )
161                    .await?;
162            }
163        }
164
165        Ok(json!({ "stored": true, "entity": entity, "facts_added": facts.len() }))
166    }
167}
168
169// ─── relate ──────────────────────────────────────────────────────────────────
170
171/// A tool that records a typed relationship between two entities, creating any
172/// that don't yet exist (without disturbing the type of those that do).
173pub struct RelateTool {
174    kg: Arc<GraphMemoryService>,
175}
176
177impl RelateTool {
178    /// Create a `relate` tool backed by the given graph.
179    pub fn new(kg: Arc<GraphMemoryService>) -> Self {
180        Self { kg }
181    }
182}
183
184#[async_trait]
185impl Tool for RelateTool {
186    fn name(&self) -> &str {
187        "relate"
188    }
189
190    fn description(&self) -> &str {
191        "Record a typed relationship between two entities in long-term memory, \
192         e.g. source \"Shai\" relation \"located_in\" target \"Bay Area\". \
193         Creates either entity if it does not exist yet. Use snake_case for the \
194         relation type."
195    }
196
197    fn parameters_schema(&self) -> Option<Value> {
198        Some(json!({
199            "type": "object",
200            "properties": {
201                "source": { "type": "string", "description": "The source entity name." },
202                "relation": { "type": "string", "description": "The relation type, e.g. \"located_in\", \"works_at\", \"prefers\"." },
203                "target": { "type": "string", "description": "The target entity name." }
204            },
205            "required": ["source", "relation", "target"]
206        }))
207    }
208
209    async fn execute(&self, ctx: Arc<dyn ToolContext>, args: Value) -> Result<Value> {
210        let field = |key: &str| -> Result<String> {
211            args.get(key)
212                .and_then(|v| v.as_str())
213                .map(str::trim)
214                .filter(|s| !s.is_empty())
215                .map(str::to_string)
216                .ok_or_else(|| AdkError::tool(format!("`{key}` is required and must be non-empty")))
217        };
218        let source = field("source")?;
219        let relation = field("relation")?;
220        let target = field("target")?;
221
222        let app = ctx.app_name();
223        let user = ctx.user_id();
224
225        // Create only the endpoints that don't already exist, so existing
226        // entities keep their type/observations.
227        let existing = self.kg.open_nodes(app, user, vec![source.clone(), target.clone()]).await?;
228        let known: HashSet<&str> = existing.iter().map(|r| r.entity.name.as_str()).collect();
229        let to_create: Vec<CreateEntityInput> = [&source, &target]
230            .into_iter()
231            .filter(|n| !known.contains(n.as_str()))
232            .map(|n| CreateEntityInput {
233                name: n.clone(),
234                entity_type: DEFAULT_ENTITY_TYPE.to_string(),
235                observations: vec![],
236            })
237            .collect();
238        if !to_create.is_empty() {
239            self.kg.create_entities(app, user, to_create).await?;
240        }
241
242        self.kg
243            .create_relations(
244                app,
245                user,
246                vec![CreateRelationInput {
247                    source: source.clone(),
248                    relation_type: relation.clone(),
249                    target: target.clone(),
250                }],
251            )
252            .await?;
253
254        Ok(json!({ "related": true, "source": source, "relation": relation, "target": target }))
255    }
256}
257
258// ─── toolset ─────────────────────────────────────────────────────────────────
259
260/// Bundles the knowledge-graph curation tools ([`RememberTool`], [`RelateTool`])
261/// so an agent can opt into KG memory writes in one line.
262///
263/// Pair with [`LoadMemoryTool`](super::LoadMemoryTool) for recall.
264pub struct GraphMemoryToolset {
265    kg: Arc<GraphMemoryService>,
266}
267
268impl GraphMemoryToolset {
269    /// Create the toolset backed by the given graph.
270    pub fn new(kg: Arc<GraphMemoryService>) -> Self {
271        Self { kg }
272    }
273}
274
275#[async_trait]
276impl Toolset for GraphMemoryToolset {
277    fn name(&self) -> &str {
278        "graph_memory"
279    }
280
281    async fn tools(&self, _ctx: Arc<dyn ReadonlyContext>) -> Result<Vec<Arc<dyn Tool>>> {
282        Ok(vec![
283            Arc::new(RememberTool::new(self.kg.clone())),
284            Arc::new(RelateTool::new(self.kg.clone())),
285        ])
286    }
287}
288
289#[cfg(test)]
290mod tests {
291    use super::*;
292    use adk_core::{Content, EventActions, ReadonlyContext};
293
294    struct MockToolContext;
295
296    #[async_trait]
297    impl ReadonlyContext for MockToolContext {
298        fn invocation_id(&self) -> &str {
299            "inv-1"
300        }
301        fn agent_name(&self) -> &str {
302            "test-agent"
303        }
304        fn user_id(&self) -> &str {
305            "shai"
306        }
307        fn app_name(&self) -> &str {
308            "test-app"
309        }
310        fn session_id(&self) -> &str {
311            "session-1"
312        }
313        fn branch(&self) -> &str {
314            ""
315        }
316        fn user_content(&self) -> &Content {
317            // Leak a tiny Content once; fine for tests.
318            static CONTENT: std::sync::OnceLock<Content> = std::sync::OnceLock::new();
319            CONTENT.get_or_init(|| Content::new("user").with_text("hi"))
320        }
321    }
322
323    #[async_trait]
324    impl adk_core::CallbackContext for MockToolContext {
325        fn artifacts(&self) -> Option<Arc<dyn adk_core::Artifacts>> {
326            None
327        }
328    }
329
330    #[async_trait]
331    impl ToolContext for MockToolContext {
332        fn function_call_id(&self) -> &str {
333            "call-1"
334        }
335        fn actions(&self) -> EventActions {
336            EventActions::default()
337        }
338        fn set_actions(&self, _actions: EventActions) {}
339        async fn search_memory(&self, _query: &str) -> Result<Vec<adk_core::MemoryEntry>> {
340            Ok(vec![])
341        }
342    }
343
344    async fn kg() -> Arc<GraphMemoryService> {
345        let kg = GraphMemoryService::new("sqlite::memory:").await.unwrap();
346        kg.migrate().await.unwrap();
347        Arc::new(kg)
348    }
349
350    fn ctx() -> Arc<dyn ToolContext> {
351        Arc::new(MockToolContext) as Arc<dyn ToolContext>
352    }
353
354    #[tokio::test]
355    async fn metadata_and_schema() {
356        let tool = RememberTool::new(kg().await);
357        assert_eq!(tool.name(), "remember");
358        let schema = tool.parameters_schema().unwrap();
359        assert_eq!(schema["type"], "object");
360        assert!(schema["properties"]["entity"].is_object());
361        assert!(schema["required"].as_array().unwrap().contains(&json!("entity")));
362        assert!(schema["required"].as_array().unwrap().contains(&json!("facts")));
363    }
364
365    #[tokio::test]
366    async fn remember_creates_entity_with_type_and_facts() {
367        let kg = kg().await;
368        let tool = RememberTool::new(kg.clone());
369        let out = tool
370            .execute(
371                ctx(),
372                json!({
373                    "entity": "Shai",
374                    "entity_type": "person",
375                    "facts": ["Name is spelled S-H-A-I", "Relocated to the Bay Area"]
376                }),
377            )
378            .await
379            .unwrap();
380        assert_eq!(out["stored"], true);
381        assert_eq!(out["facts_added"], 2);
382
383        let hits = kg.search_nodes("test-app", "shai", "Shai", 5).await.unwrap();
384        assert_eq!(hits.len(), 1);
385        assert_eq!(hits[0].entity.entity_type, "person");
386        assert_eq!(hits[0].entity.observations.len(), 2);
387    }
388
389    #[tokio::test]
390    async fn remember_without_type_preserves_existing_type() {
391        let kg = kg().await;
392        let tool = RememberTool::new(kg.clone());
393        // Seed with an explicit type.
394        tool.execute(ctx(), json!({"entity": "Shai", "entity_type": "person", "facts": ["a"]}))
395            .await
396            .unwrap();
397        // Append without a type — must not clobber "person" back to "general".
398        tool.execute(ctx(), json!({"entity": "Shai", "facts": ["b"]})).await.unwrap();
399
400        let hits = kg.open_nodes("test-app", "shai", vec!["Shai".into()]).await.unwrap();
401        assert_eq!(hits[0].entity.entity_type, "person");
402        assert_eq!(hits[0].entity.observations.len(), 2);
403    }
404
405    #[tokio::test]
406    async fn remember_rejects_empty_facts() {
407        let kg = kg().await;
408        let tool = RememberTool::new(kg);
409        assert!(tool.execute(ctx(), json!({"entity": "Shai", "facts": []})).await.is_err());
410        assert!(tool.execute(ctx(), json!({"entity": "", "facts": ["x"]})).await.is_err());
411    }
412
413    #[tokio::test]
414    async fn relate_creates_missing_endpoints_and_preserves_existing_type() {
415        let kg = kg().await;
416        let remember = RememberTool::new(kg.clone());
417        // Shai exists as a person.
418        remember
419            .execute(ctx(), json!({"entity": "Shai", "entity_type": "person", "facts": ["x"]}))
420            .await
421            .unwrap();
422
423        let relate = RelateTool::new(kg.clone());
424        let out = relate
425            .execute(
426                ctx(),
427                json!({"source": "Shai", "relation": "located_in", "target": "Bay Area"}),
428            )
429            .await
430            .unwrap();
431        assert_eq!(out["related"], true);
432
433        let (entities, relations) = kg.read_graph("test-app", "shai").await.unwrap();
434        // Shai kept "person"; Bay Area was created as "general".
435        let shai = entities.iter().find(|e| e.name == "Shai").unwrap();
436        assert_eq!(shai.entity_type, "person");
437        assert!(entities.iter().any(|e| e.name == "Bay Area" && e.entity_type == "general"));
438        assert_eq!(relations.len(), 1);
439        assert_eq!(relations[0].relation_type, "located_in");
440    }
441
442    #[tokio::test]
443    async fn toolset_exposes_remember_and_relate() {
444        let kg = kg().await;
445        let toolset = GraphMemoryToolset::new(kg);
446        let ctx = Arc::new(MockToolContext) as Arc<dyn ReadonlyContext>;
447        let tools = toolset.tools(ctx).await.unwrap();
448        let names: Vec<&str> = tools.iter().map(|t| t.name()).collect();
449        assert!(names.contains(&"remember"));
450        assert!(names.contains(&"relate"));
451    }
452}