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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Memory and Knowledge Management Tools"""
|
| 2 |
+
import os
|
| 3 |
+
import json
|
| 4 |
+
import time
|
| 5 |
+
from typing import Dict, List, Optional, Any
|
| 6 |
+
from config import Config
|
| 7 |
+
from utils import Logger
|
| 8 |
+
|
| 9 |
+
class MemoryTools:
|
| 10 |
+
"""Persistent memory storage and retrieval"""
|
| 11 |
+
|
| 12 |
+
def __init__(self, memory_file: str = None):
|
| 13 |
+
self.memory_file = memory_file or Config.MEMORY_FILE
|
| 14 |
+
self.logger = Logger()
|
| 15 |
+
self._ensure_memory()
|
| 16 |
+
|
| 17 |
+
def _ensure_memory(self):
|
| 18 |
+
"""Ensure memory file exists"""
|
| 19 |
+
if not os.path.exists(self.memory_file):
|
| 20 |
+
with open(self.memory_file, "w") as f:
|
| 21 |
+
json.dump({
|
| 22 |
+
"facts": [],
|
| 23 |
+
"conversations": [],
|
| 24 |
+
"tasks": [],
|
| 25 |
+
"preferences": {},
|
| 26 |
+
"created_at": time.time()
|
| 27 |
+
}, f)
|
| 28 |
+
|
| 29 |
+
def _load(self) -> Dict:
|
| 30 |
+
"""Load memory from disk"""
|
| 31 |
+
try:
|
| 32 |
+
with open(self.memory_file, "r") as f:
|
| 33 |
+
return json.load(f)
|
| 34 |
+
except:
|
| 35 |
+
return {"facts": [], "conversations": [], "tasks": [], "preferences": {}}
|
| 36 |
+
|
| 37 |
+
def _save(self, data: Dict):
|
| 38 |
+
"""Save memory to disk"""
|
| 39 |
+
with open(self.memory_file, "w") as f:
|
| 40 |
+
json.dump(data, f, indent=2, ensure_ascii=False)
|
| 41 |
+
|
| 42 |
+
def memory_save(self, category: str, key: str, value: Any,
|
| 43 |
+
tags: List[str] = None, ttl: int = 0) -> Dict:
|
| 44 |
+
"""Save information to memory"""
|
| 45 |
+
try:
|
| 46 |
+
memory = self._load()
|
| 47 |
+
|
| 48 |
+
entry = {
|
| 49 |
+
"key": key,
|
| 50 |
+
"value": value,
|
| 51 |
+
"tags": tags or [],
|
| 52 |
+
"created": time.time(),
|
| 53 |
+
"ttl": ttl,
|
| 54 |
+
"accessed": 0
|
| 55 |
+
}
|
| 56 |
+
|
| 57 |
+
if category == "fact":
|
| 58 |
+
memory["facts"] = [f for f in memory["facts"] if f["key"] != key]
|
| 59 |
+
memory["facts"].append(entry)
|
| 60 |
+
elif category == "task":
|
| 61 |
+
memory["tasks"].append(entry)
|
| 62 |
+
elif category == "preference":
|
| 63 |
+
memory["preferences"][key] = value
|
| 64 |
+
elif category == "conversation":
|
| 65 |
+
memory["conversations"].append({
|
| 66 |
+
**entry,
|
| 67 |
+
"role": value.get("role", "unknown"),
|
| 68 |
+
"content": value.get("content", "")
|
| 69 |
+
})
|
| 70 |
+
|
| 71 |
+
self._save(memory)
|
| 72 |
+
self.logger.log("memory_save", {"category": category, "key": key})
|
| 73 |
+
|
| 74 |
+
return {
|
| 75 |
+
"success": True,
|
| 76 |
+
"category": category,
|
| 77 |
+
"key": key,
|
| 78 |
+
"stored": True
|
| 79 |
+
}
|
| 80 |
+
|
| 81 |
+
except Exception as e:
|
| 82 |
+
return {"success": False, "error": str(e)}
|
| 83 |
+
|
| 84 |
+
def memory_search(self, query: str = "", category: str = "",
|
| 85 |
+
tags: List[str] = None, limit: int = 10,
|
| 86 |
+
time_range: str = "") -> Dict:
|
| 87 |
+
"""Search memory"""
|
| 88 |
+
try:
|
| 89 |
+
memory = self._load()
|
| 90 |
+
results = []
|
| 91 |
+
|
| 92 |
+
cutoff = 0
|
| 93 |
+
if time_range == "today":
|
| 94 |
+
cutoff = time.time() - 86400
|
| 95 |
+
elif time_range == "week":
|
| 96 |
+
cutoff = time.time() - 604800
|
| 97 |
+
elif time_range == "month":
|
| 98 |
+
cutoff = time.time() - 2592000
|
| 99 |
+
|
| 100 |
+
categories = [category] if category else ["facts", "tasks", "conversations"]
|
| 101 |
+
|
| 102 |
+
for cat in categories:
|
| 103 |
+
items = memory.get(cat, [])
|
| 104 |
+
for item in items:
|
| 105 |
+
if cutoff and item.get("created", 0) < cutoff:
|
| 106 |
+
continue
|
| 107 |
+
|
| 108 |
+
if tags and not any(t in item.get("tags", []) for t in tags):
|
| 109 |
+
continue
|
| 110 |
+
|
| 111 |
+
score = 0
|
| 112 |
+
if query:
|
| 113 |
+
query_lower = query.lower()
|
| 114 |
+
if query_lower in item.get("key", "").lower():
|
| 115 |
+
score += 10
|
| 116 |
+
if query_lower in str(item.get("value", "")).lower():
|
| 117 |
+
score += 5
|
| 118 |
+
for tag in item.get("tags", []):
|
| 119 |
+
if query_lower in tag.lower():
|
| 120 |
+
score += 3
|
| 121 |
+
|
| 122 |
+
if not query or score > 0:
|
| 123 |
+
results.append({
|
| 124 |
+
"category": cat,
|
| 125 |
+
"score": score,
|
| 126 |
+
**item
|
| 127 |
+
})
|
| 128 |
+
|
| 129 |
+
if query:
|
| 130 |
+
results.sort(key=lambda x: x["score"], reverse=True)
|
| 131 |
+
else:
|
| 132 |
+
results.sort(key=lambda x: x.get("created", 0), reverse=True)
|
| 133 |
+
|
| 134 |
+
for r in results[:limit]:
|
| 135 |
+
r["accessed"] = r.get("accessed", 0) + 1
|
| 136 |
+
|
| 137 |
+
self._save(memory)
|
| 138 |
+
self.logger.log("memory_search", {"query": query, "results": len(results)})
|
| 139 |
+
|
| 140 |
+
return {
|
| 141 |
+
"success": True,
|
| 142 |
+
"query": query,
|
| 143 |
+
"results": results[:limit],
|
| 144 |
+
"total": len(results)
|
| 145 |
+
}
|
| 146 |
+
|
| 147 |
+
except Exception as e:
|
| 148 |
+
return {"success": False, "error": str(e)}
|
| 149 |
+
|
| 150 |
+
def memory_delete(self, key: str = "", category: str = "",
|
| 151 |
+
older_than: int = 0, confirm: bool = True) -> Dict:
|
| 152 |
+
"""Delete memory entries"""
|
| 153 |
+
try:
|
| 154 |
+
if confirm and not key.startswith("_auto_"):
|
| 155 |
+
from utils import UI
|
| 156 |
+
if not UI.confirm(f"Delete memory entries matching '{key}'?"):
|
| 157 |
+
return {"success": False, "error": "User cancelled"}
|
| 158 |
+
|
| 159 |
+
memory = self._load()
|
| 160 |
+
deleted = 0
|
| 161 |
+
|
| 162 |
+
if key:
|
| 163 |
+
for cat in memory:
|
| 164 |
+
if isinstance(memory[cat], list):
|
| 165 |
+
original = len(memory[cat])
|
| 166 |
+
memory[cat] = [i for i in memory[cat] if i.get("key") != key]
|
| 167 |
+
deleted += original - len(memory[cat])
|
| 168 |
+
|
| 169 |
+
if older_than:
|
| 170 |
+
cutoff = time.time() - older_than
|
| 171 |
+
for cat in memory:
|
| 172 |
+
if isinstance(memory[cat], list):
|
| 173 |
+
original = len(memory[cat])
|
| 174 |
+
memory[cat] = [i for i in memory[cat] if i.get("created", 0) > cutoff]
|
| 175 |
+
deleted += original - len(memory[cat])
|
| 176 |
+
|
| 177 |
+
self._save(memory)
|
| 178 |
+
|
| 179 |
+
return {
|
| 180 |
+
"success": True,
|
| 181 |
+
"deleted": deleted,
|
| 182 |
+
"criteria": {"key": key, "category": category, "older_than": older_than}
|
| 183 |
+
}
|
| 184 |
+
|
| 185 |
+
except Exception as e:
|
| 186 |
+
return {"success": False, "error": str(e)}
|
| 187 |
+
|
| 188 |
+
def memory_stats(self) -> Dict:
|
| 189 |
+
"""Get memory statistics"""
|
| 190 |
+
try:
|
| 191 |
+
memory = self._load()
|
| 192 |
+
return {
|
| 193 |
+
"success": True,
|
| 194 |
+
"facts": len(memory.get("facts", [])),
|
| 195 |
+
"tasks": len(memory.get("tasks", [])),
|
| 196 |
+
"conversations": len(memory.get("conversations", [])),
|
| 197 |
+
"preferences": len(memory.get("preferences", {})),
|
| 198 |
+
"file_size": os.path.getsize(self.memory_file) if os.path.exists(self.memory_file) else 0
|
| 199 |
+
}
|
| 200 |
+
except Exception as e:
|
| 201 |
+
return {"success": False, "error": str(e)}
|
| 202 |
+
|