-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmemory_tools.py
More file actions
269 lines (230 loc) · 8.67 KB
/
Copy pathmemory_tools.py
File metadata and controls
269 lines (230 loc) · 8.67 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
"""
Memory Tools - Tool definitions for RLM-style memory access
Instead of passive injection, these tools let the LLM actively query
and traverse memory as needed during a conversation.
"""
from typing import List, Dict, Any, Optional
from dataclasses import dataclass
from engram_pkg import VectorMemory
@dataclass
class MemoryToolResult:
"""Result from a memory tool call"""
success: bool
data: Any
message: str
class MemoryTools:
"""
Tools for active memory retrieval.
The LLM can call these tools iteratively to:
1. Search for relevant memories
2. Follow related memory links
3. Get specific memories by ID
4. Store new memories
"""
def __init__(self, memory_system: VectorMemory):
self.memory = memory_system
def search_memory(self, query: str, limit: int = 5) -> List[Dict[str, Any]]:
"""
Search memories by semantic similarity.
Args:
query: Natural language search query
limit: Maximum number of results (default 5)
Returns:
List of matching memories with content, importance, tags, and IDs
"""
memories = self.memory.retrieve_memory(query, limit=limit)
results = []
for mem in memories:
results.append({
"id": mem.id,
"content": mem.content,
"importance": round(mem.importance, 2),
"tags": mem.tags,
"access_count": mem.access_count,
"has_related": len(mem.related_memories) > 0,
"related_count": len(mem.related_memories)
})
return results
def get_related_memories(self, memory_id: str, limit: int = 3) -> List[Dict[str, Any]]:
"""
Get memories related to a specific memory.
Args:
memory_id: ID of the memory to find relations for (can be partial)
limit: Maximum number of related memories to return
Returns:
List of related memories
"""
# Support partial ID matching
full_id = self._resolve_memory_id(memory_id)
if not full_id:
return []
memory = self.memory.get_memory_by_id(full_id)
if not memory or not memory.related_memories:
return []
results = []
for related_id in memory.related_memories[:limit]:
related = self.memory.get_memory_by_id(related_id)
if related:
results.append({
"id": related.id,
"content": related.content,
"importance": round(related.importance, 2),
"tags": related.tags
})
return results
def get_memory_by_id(self, memory_id: str) -> Optional[Dict[str, Any]]:
"""
Get a specific memory by its ID.
Args:
memory_id: Full or partial memory ID
Returns:
Memory details or None if not found
"""
full_id = self._resolve_memory_id(memory_id)
if not full_id:
return None
memory = self.memory.get_memory_by_id(full_id)
if not memory:
return None
return {
"id": memory.id,
"content": memory.content,
"importance": round(memory.importance, 2),
"tags": memory.tags,
"access_count": memory.access_count,
"timestamp": memory.timestamp.isoformat(),
"related_memories": memory.related_memories[:5]
}
def get_recent_memories(self, hours: int = 24, limit: int = 5) -> List[Dict[str, Any]]:
"""
Get recently created memories.
Args:
hours: Look back this many hours (default 24)
limit: Maximum number of memories to return
Returns:
List of recent memories
"""
memories = self.memory.get_recent_memories(hours=hours, limit=limit)
results = []
for mem in memories:
results.append({
"id": mem.id,
"content": mem.content,
"importance": round(mem.importance, 2),
"tags": mem.tags,
"timestamp": mem.timestamp.isoformat()
})
return results
def store_memory(self, content: str, importance: float = 0.7,
tags: List[str] = None) -> Dict[str, Any]:
"""
Store a new memory.
Args:
content: The memory content to store
importance: Importance score 0.0-1.0 (default 0.7)
tags: Optional list of tags for categorization
Returns:
Stored memory info with ID
"""
memory_id = self.memory.store_memory(
content=content,
importance=importance,
tags=tags or []
)
return {
"id": memory_id,
"content": content,
"importance": importance,
"stored": True
}
def _resolve_memory_id(self, partial_id: str) -> Optional[str]:
"""Resolve a partial memory ID to full ID"""
if partial_id in self.memory.memories:
return partial_id
matches = [mid for mid in self.memory.memories if mid.startswith(partial_id)]
if len(matches) == 1:
return matches[0]
return None
def get_memory_count(self) -> int:
"""Get total number of stored memories"""
return len(self.memory.memories)
# Tool schemas for Gemini function calling
MEMORY_TOOL_DECLARATIONS = [
{
"name": "search_memory",
"description": "Search your memory for relevant information using semantic similarity. Use this to recall facts, preferences, past decisions, or anything you might have learned about the user.",
"parameters": {
"type": "object",
"properties": {
"query": {
"type": "string",
"description": "Natural language search query describing what you're looking for"
},
"limit": {
"type": "integer",
"description": "Maximum number of memories to return (default 5)"
}
},
"required": ["query"]
}
},
{
"name": "get_related_memories",
"description": "Get memories that are semantically related to a specific memory. Use this to follow connections and build deeper understanding.",
"parameters": {
"type": "object",
"properties": {
"memory_id": {
"type": "string",
"description": "ID of the memory to find relations for (can be partial ID)"
},
"limit": {
"type": "integer",
"description": "Maximum number of related memories to return (default 3)"
}
},
"required": ["memory_id"]
}
},
{
"name": "get_recent_memories",
"description": "Get the most recently stored memories. Useful for understanding recent context or what was just discussed.",
"parameters": {
"type": "object",
"properties": {
"hours": {
"type": "integer",
"description": "Look back this many hours (default 24)"
},
"limit": {
"type": "integer",
"description": "Maximum number of memories to return (default 5)"
}
},
"required": []
}
},
{
"name": "store_memory",
"description": "Store an important piece of information in memory for future reference. Use sparingly - only for genuinely important facts, preferences, or decisions.",
"parameters": {
"type": "object",
"properties": {
"content": {
"type": "string",
"description": "The information to remember"
},
"importance": {
"type": "number",
"description": "How important is this? 0.0 (low) to 1.0 (critical). Default 0.7"
},
"tags": {
"type": "array",
"items": {"type": "string"},
"description": "Optional categorization tags"
}
},
"required": ["content"]
}
}
]