forked from bojieli/ai-agent-book
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtools.py
More file actions
320 lines (274 loc) · 11.1 KB
/
Copy pathtools.py
File metadata and controls
320 lines (274 loc) · 11.1 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
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
"""Tool definitions for the User Memory RAG Agent
This module provides tool definitions and implementations for searching
and retrieving information from indexed conversation memories.
"""
import json
import logging
from typing import Dict, Any, List, Optional
from dataclasses import dataclass
from indexer import MemoryIndexer, SearchResult
from config import IndexConfig
logger = logging.getLogger(__name__)
@dataclass
class ToolResult:
"""Result from a tool execution"""
success: bool
data: Any
error: Optional[str] = None
def to_dict(self) -> Dict[str, Any]:
if self.success:
return {"status": "success", "data": self.data}
else:
return {"status": "error", "error": self.error}
class MemoryTools:
"""Tools for searching and retrieving user memory information"""
def __init__(self, indexer: MemoryIndexer):
"""
Initialize memory tools
Args:
indexer: The memory indexer instance
"""
self.indexer = indexer
logger.info("Initialized memory tools")
def search_memory(self,
query: str,
top_k: int = 3,
filter_test_id: Optional[str] = None) -> ToolResult:
"""
Search user memory for relevant information
Args:
query: Natural language search query
top_k: Number of results to return
filter_test_id: Optional test ID to filter results
Returns:
ToolResult with search results
"""
try:
# Perform search
results = self.indexer.search(query, top_k=top_k)
# Filter by test ID if specified
if filter_test_id:
results = [r for r in results if r.chunk.test_id == filter_test_id]
# Format results
formatted_results = []
for result in results:
# Extract key information from the chunk
chunk_info = {
"chunk_id": result.chunk_id,
"score": round(result.score, 4),
"test_id": result.chunk.test_id,
"conversation_id": result.chunk.conversation_id,
"rounds": f"{result.chunk.start_round}-{result.chunk.end_round}",
"metadata": result.chunk.metadata,
"content": result.chunk.to_text(), # FULL content, not truncated
"match_type": result.match_type
}
formatted_results.append(chunk_info)
logger.info(f"Search query: '{query}' returned {len(formatted_results)} results")
return ToolResult(
success=True,
data={
"query": query,
"total_results": len(formatted_results),
"results": formatted_results
}
)
except Exception as e:
logger.error(f"Error in search_memory: {e}")
return ToolResult(
success=False,
data=None,
error=str(e)
)
def get_conversation_context(self,
chunk_id: str,
context_size: int = 2) -> ToolResult:
"""
Get surrounding context for a specific chunk
Args:
chunk_id: The chunk ID to get context for
context_size: Number of chunks before/after to include
Returns:
ToolResult with conversation context
"""
try:
# Get the target chunk
if chunk_id not in self.indexer.chunks:
return ToolResult(
success=False,
data=None,
error=f"Chunk {chunk_id} not found"
)
target_chunk = self.indexer.chunks[chunk_id]
# Find related chunks from same conversation
related_chunks = []
for cid, chunk in self.indexer.chunks.items():
if (chunk.conversation_id == target_chunk.conversation_id and
chunk.test_id == target_chunk.test_id):
related_chunks.append(chunk)
# Sort by chunk index
related_chunks.sort(key=lambda x: x.chunk_index)
# Find target index
target_idx = next(
(i for i, c in enumerate(related_chunks) if c.chunk_id == chunk_id),
None
)
if target_idx is None:
return ToolResult(
success=False,
data=None,
error="Could not locate chunk in conversation"
)
# Get context chunks
start_idx = max(0, target_idx - context_size)
end_idx = min(len(related_chunks), target_idx + context_size + 1)
context_chunks = related_chunks[start_idx:end_idx]
# Format result
context_data = {
"target_chunk": {
"chunk_id": target_chunk.chunk_id,
"rounds": f"{target_chunk.start_round}-{target_chunk.end_round}",
"content": target_chunk.to_text()
},
"context_chunks": []
}
for chunk in context_chunks:
if chunk.chunk_id != chunk_id:
context_data["context_chunks"].append({
"chunk_id": chunk.chunk_id,
"rounds": f"{chunk.start_round}-{chunk.end_round}",
"position": "before" if chunk.chunk_index < target_chunk.chunk_index else "after",
"content": chunk.to_text()
})
return ToolResult(
success=True,
data=context_data
)
except Exception as e:
logger.error(f"Error in get_conversation_context: {e}")
return ToolResult(
success=False,
data=None,
error=str(e)
)
def get_full_conversation(self,
conversation_id: str,
test_id: str) -> ToolResult:
"""
Retrieve all chunks from a specific conversation
Args:
conversation_id: Conversation identifier
test_id: Test case identifier
Returns:
ToolResult with full conversation
"""
try:
# Find all chunks for this conversation
conversation_chunks = []
for chunk_id, chunk in self.indexer.chunks.items():
if (chunk.conversation_id == conversation_id and
chunk.test_id == test_id):
conversation_chunks.append(chunk)
if not conversation_chunks:
return ToolResult(
success=False,
data=None,
error=f"No chunks found for conversation {conversation_id}"
)
# Sort by chunk index
conversation_chunks.sort(key=lambda x: x.chunk_index)
# Format result
conversation_data = {
"conversation_id": conversation_id,
"test_id": test_id,
"total_chunks": len(conversation_chunks),
"total_rounds": max(c.end_round for c in conversation_chunks),
"metadata": conversation_chunks[0].metadata if conversation_chunks else {},
"chunks": []
}
for chunk in conversation_chunks:
conversation_data["chunks"].append({
"chunk_id": chunk.chunk_id,
"chunk_index": chunk.chunk_index,
"rounds": f"{chunk.start_round}-{chunk.end_round}",
"content": chunk.to_text()
})
return ToolResult(
success=True,
data=conversation_data
)
except Exception as e:
logger.error(f"Error in get_full_conversation: {e}")
return ToolResult(
success=False,
data=None,
error=str(e)
)
def get_tool_definitions() -> List[Dict[str, Any]]:
"""
Get OpenAI function calling tool definitions
Returns:
List of tool definitions for OpenAI API
"""
return [
{
"type": "function",
"function": {
"name": "search_memory",
"description": "Search user conversation memory for relevant information. Use this to find specific details from past conversations.",
"parameters": {
"type": "object",
"properties": {
"query": {
"type": "string",
"description": "Natural language search query describing what information to find"
},
},
"required": ["query"]
}
}
},
{
"type": "function",
"function": {
"name": "get_conversation_context",
"description": "Get surrounding context for a specific conversation chunk. Use this when you need more context around a search result.",
"parameters": {
"type": "object",
"properties": {
"chunk_id": {
"type": "string",
"description": "The chunk ID to get context for"
},
"context_size": {
"type": "integer",
"description": "Number of chunks before/after to include (default: 2)",
"default": 2
}
},
"required": ["chunk_id"]
}
}
},
{
"type": "function",
"function": {
"name": "get_full_conversation",
"description": "Retrieve all chunks from a specific conversation. Use this when you need to review an entire conversation history.",
"parameters": {
"type": "object",
"properties": {
"conversation_id": {
"type": "string",
"description": "The conversation identifier"
},
"test_id": {
"type": "string",
"description": "The test case identifier"
}
},
"required": ["conversation_id", "test_id"]
}
}
}
]