tillu-AI commited on
Commit
0977402
·
verified ·
1 Parent(s): 91c82a6

upload app/tools/memory_tools.py

Browse files
Files changed (1) hide show
  1. app/tools/memory_tools.py +144 -0
app/tools/memory_tools.py ADDED
@@ -0,0 +1,144 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Memory Tools - Knowledge base operations
3
+ """
4
+ from typing import Any, Dict, Optional, List
5
+ from app.tools.registry import BaseTool, ToolMetadata, ToolRegistry
6
+ from app.utils.database import db
7
+ from app.utils.cache import cache
8
+ from app.utils.logging import get_logger
9
+
10
+ logger = get_logger("memory_tools")
11
+
12
+
13
+ class RememberFactTool(BaseTool):
14
+ """Store a fact in the knowledge base"""
15
+
16
+ metadata = ToolMetadata(
17
+ name="tool_remember_fact",
18
+ description="Store a fact or preference about the user in the knowledge base. Use this to remember important information.",
19
+ parameters={
20
+ "content": {"type": "string", "description": "The fact or information to remember"},
21
+ "category": {"type": "string", "description": "Category (e.g., preference, fact, insight)", "default": "fact"},
22
+ "user_id": {"type": "string", "description": "User ID (usually auto-populated)"}
23
+ },
24
+ rate_limited=False
25
+ )
26
+
27
+ async def execute(
28
+ self,
29
+ content: str,
30
+ category: str = "fact",
31
+ user_id: str = None
32
+ ) -> Dict[str, Any]:
33
+ """Store fact in knowledge base"""
34
+ try:
35
+ if not user_id:
36
+ return {
37
+ "success": False,
38
+ "error": "User ID required"
39
+ }
40
+
41
+ knowledge_data = {
42
+ "user_id": user_id,
43
+ "content": content,
44
+ "content_type": category,
45
+ "source_type": "tool",
46
+ "confidence_score": 0.9,
47
+ "quality_score": 0.9
48
+ }
49
+
50
+ result = await db.insert("knowledge_base", knowledge_data)
51
+
52
+ if result:
53
+ # Invalidate cache
54
+ await cache.delete(f"knowledge_base:{user_id}")
55
+
56
+ return {
57
+ "success": True,
58
+ "memory_id": result[0]["id"],
59
+ "message": f"Remembered: {content[:100]}..."
60
+ }
61
+ else:
62
+ return {
63
+ "success": False,
64
+ "error": "Failed to store in database"
65
+ }
66
+
67
+ except Exception as e:
68
+ logger.error(f"Remember fact error: {e}")
69
+ return {
70
+ "success": False,
71
+ "error": str(e)
72
+ }
73
+
74
+
75
+ class RecallMemoryTool(BaseTool):
76
+ """Search and recall memories from knowledge base"""
77
+
78
+ metadata = ToolMetadata(
79
+ name="tool_recall_memory",
80
+ description="Search the knowledge base for relevant information. Use this to recall facts about the user.",
81
+ parameters={
82
+ "query": {"type": "string", "description": "What to search for"},
83
+ "limit": {"type": "integer", "description": "Max results", "default": 5},
84
+ "user_id": {"type": "string", "description": "User ID (usually auto-populated)"}
85
+ },
86
+ rate_limited=False
87
+ )
88
+
89
+ async def execute(
90
+ self,
91
+ query: str,
92
+ limit: int = 5,
93
+ user_id: str = None
94
+ ) -> Dict[str, Any]:
95
+ """Search knowledge base"""
96
+ try:
97
+ if not user_id:
98
+ return {
99
+ "success": False,
100
+ "error": "User ID required"
101
+ }
102
+
103
+ # For now, do text-based search (semantic search with embeddings in Phase 2)
104
+ results = await db.fetch_many(
105
+ "knowledge_base",
106
+ filters={"user_id": user_id},
107
+ order_by="created_at",
108
+ ascending=False,
109
+ limit=limit
110
+ )
111
+
112
+ # Filter results that contain query terms (simple text match)
113
+ query_lower = query.lower()
114
+ filtered = [
115
+ r for r in results
116
+ if query_lower in r.get("content", "").lower()
117
+ ]
118
+
119
+ return {
120
+ "success": True,
121
+ "query": query,
122
+ "results": [
123
+ {
124
+ "id": r["id"],
125
+ "content": r["content"],
126
+ "category": r.get("category"),
127
+ "created_at": r["created_at"]
128
+ }
129
+ for r in filtered
130
+ ],
131
+ "result_count": len(filtered)
132
+ }
133
+
134
+ except Exception as e:
135
+ logger.error(f"Recall memory error: {e}")
136
+ return {
137
+ "success": False,
138
+ "error": str(e)
139
+ }
140
+
141
+
142
+ # Register tools
143
+ ToolRegistry.register(RememberFactTool())
144
+ ToolRegistry.register(RecallMemoryTool())