Fix: update agents/memory_agent.py
Browse files- agents/memory_agent.py +113 -22
agents/memory_agent.py
CHANGED
|
@@ -1,10 +1,13 @@
|
|
| 1 |
"""
|
| 2 |
-
MemoryAgent — Persistent memory
|
|
|
|
| 3 |
"""
|
|
|
|
|
|
|
|
|
|
| 4 |
import structlog
|
| 5 |
-
from typing import Dict
|
| 6 |
from .base_agent import BaseAgent
|
| 7 |
-
from memory.db import save_memory, search_memory, get_history
|
| 8 |
|
| 9 |
log = structlog.get_logger()
|
| 10 |
|
|
@@ -14,26 +17,114 @@ class MemoryAgent(BaseAgent):
|
|
| 14 |
super().__init__("MemoryAgent", ws_manager, ai_router)
|
| 15 |
|
| 16 |
async def run(self, task: str, context: Dict = {}, **kwargs) -> str:
|
| 17 |
-
session_id = kwargs.get("session_id",
|
| 18 |
-
task_id
|
| 19 |
-
task_lower = task.lower()
|
| 20 |
-
|
| 21 |
-
if "recall" in task_lower or "remember" in task_lower or "history" in task_lower:
|
| 22 |
-
memories = await search_memory(task, session_id=session_id)
|
| 23 |
-
if memories:
|
| 24 |
-
items = "\n".join([f"- {m['content'][:120]}" for m in memories[:10]])
|
| 25 |
-
return f"**Memory Recall:**\n{items}"
|
| 26 |
-
return "No relevant memories found."
|
| 27 |
|
| 28 |
-
|
|
|
|
|
|
|
| 29 |
content = context.get("content", task)
|
| 30 |
-
await
|
| 31 |
-
session_id=session_id, key="agent_memory")
|
| 32 |
return f"✅ Saved to memory: {content[:100]}"
|
| 33 |
-
|
| 34 |
else:
|
| 35 |
-
|
| 36 |
-
if
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
"""
|
| 2 |
+
MemoryAgent — Persistent long-term memory system (Phase 5)
|
| 3 |
+
SQLite-backed with semantic search simulation
|
| 4 |
"""
|
| 5 |
+
import json
|
| 6 |
+
import time
|
| 7 |
+
from typing import Dict, List, Optional
|
| 8 |
import structlog
|
|
|
|
| 9 |
from .base_agent import BaseAgent
|
| 10 |
+
from memory.db import save_memory, search_memory, get_history, get_project_memory
|
| 11 |
|
| 12 |
log = structlog.get_logger()
|
| 13 |
|
|
|
|
| 17 |
super().__init__("MemoryAgent", ws_manager, ai_router)
|
| 18 |
|
| 19 |
async def run(self, task: str, context: Dict = {}, **kwargs) -> str:
|
| 20 |
+
session_id = kwargs.get("session_id", "")
|
| 21 |
+
task_id = kwargs.get("task_id", "")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 22 |
|
| 23 |
+
# Determine if retrieve or save
|
| 24 |
+
task_lower = task.lower()
|
| 25 |
+
if any(k in task_lower for k in ["remember", "save", "store", "record"]):
|
| 26 |
content = context.get("content", task)
|
| 27 |
+
await self.save(content, session_id=session_id, memory_type="user_directive")
|
|
|
|
| 28 |
return f"✅ Saved to memory: {content[:100]}"
|
|
|
|
| 29 |
else:
|
| 30 |
+
results = await self.retrieve(task, session_id=session_id)
|
| 31 |
+
if results:
|
| 32 |
+
return "📚 **Memory Retrieved:**\n\n" + "\n".join(f"- {r['content'][:200]}" for r in results[:5])
|
| 33 |
+
return "No relevant memories found."
|
| 34 |
+
|
| 35 |
+
async def save(
|
| 36 |
+
self,
|
| 37 |
+
content: str,
|
| 38 |
+
session_id: str = "",
|
| 39 |
+
project_id: str = "",
|
| 40 |
+
memory_type: str = "general",
|
| 41 |
+
key: str = "",
|
| 42 |
+
metadata: Dict = {},
|
| 43 |
+
):
|
| 44 |
+
"""Save content to persistent memory."""
|
| 45 |
+
await save_memory(
|
| 46 |
+
content=content,
|
| 47 |
+
memory_type=memory_type,
|
| 48 |
+
session_id=session_id,
|
| 49 |
+
project_id=project_id,
|
| 50 |
+
key=key,
|
| 51 |
+
metadata=metadata,
|
| 52 |
+
)
|
| 53 |
+
|
| 54 |
+
async def retrieve(
|
| 55 |
+
self,
|
| 56 |
+
query: str,
|
| 57 |
+
session_id: str = "",
|
| 58 |
+
project_id: str = "",
|
| 59 |
+
limit: int = 10,
|
| 60 |
+
) -> List[Dict]:
|
| 61 |
+
"""Retrieve relevant memories."""
|
| 62 |
+
return await search_memory(query[:100], session_id=session_id, project_id=project_id, limit=limit)
|
| 63 |
+
|
| 64 |
+
async def get_conversation_history(self, session_id: str, limit: int = 20) -> List[Dict]:
|
| 65 |
+
"""Get conversation history for a session."""
|
| 66 |
+
return await get_history(session_id, limit=limit)
|
| 67 |
+
|
| 68 |
+
async def save_interaction(
|
| 69 |
+
self,
|
| 70 |
+
user_message: str,
|
| 71 |
+
assistant_response: str,
|
| 72 |
+
session_id: str = "",
|
| 73 |
+
intent: Dict = {},
|
| 74 |
+
):
|
| 75 |
+
"""Save a full interaction to memory."""
|
| 76 |
+
await save_memory(
|
| 77 |
+
content=user_message,
|
| 78 |
+
memory_type="conversation",
|
| 79 |
+
session_id=session_id,
|
| 80 |
+
key="user_message",
|
| 81 |
+
metadata={"intent": intent.get("intent", ""), "timestamp": time.time()},
|
| 82 |
+
)
|
| 83 |
+
await save_memory(
|
| 84 |
+
content=assistant_response,
|
| 85 |
+
memory_type="conversation",
|
| 86 |
+
session_id=session_id,
|
| 87 |
+
key="assistant_response",
|
| 88 |
+
metadata={"agent": intent.get("primary_agent", "chat"), "timestamp": time.time()},
|
| 89 |
+
)
|
| 90 |
+
|
| 91 |
+
async def save_coding_style(self, style_notes: str, session_id: str = ""):
|
| 92 |
+
"""Remember user's coding preferences."""
|
| 93 |
+
await save_memory(
|
| 94 |
+
content=style_notes,
|
| 95 |
+
memory_type="user_preference",
|
| 96 |
+
session_id=session_id,
|
| 97 |
+
key="coding_style",
|
| 98 |
+
metadata={"category": "coding_style"},
|
| 99 |
+
)
|
| 100 |
+
|
| 101 |
+
async def save_project_context(self, project_id: str, context: Dict):
|
| 102 |
+
"""Save project-specific context."""
|
| 103 |
+
await save_memory(
|
| 104 |
+
content=json.dumps(context),
|
| 105 |
+
memory_type="project_context",
|
| 106 |
+
project_id=project_id,
|
| 107 |
+
key="project_context",
|
| 108 |
+
metadata={"timestamp": time.time()},
|
| 109 |
+
)
|
| 110 |
+
|
| 111 |
+
async def get_project_context(self, project_id: str) -> Optional[Dict]:
|
| 112 |
+
"""Get project context."""
|
| 113 |
+
results = await get_project_memory(project_id, memory_type="project_context", limit=1)
|
| 114 |
+
if results:
|
| 115 |
+
try:
|
| 116 |
+
return json.loads(results[0]["content"])
|
| 117 |
+
except Exception:
|
| 118 |
+
return {"raw": results[0]["content"]}
|
| 119 |
+
return None
|
| 120 |
+
|
| 121 |
+
async def build_context_for_agent(self, session_id: str, query: str) -> Dict:
|
| 122 |
+
"""Build rich context dict for agents from memory."""
|
| 123 |
+
history = await self.get_conversation_history(session_id, limit=10)
|
| 124 |
+
relevant = await self.retrieve(query, session_id=session_id, limit=5)
|
| 125 |
+
|
| 126 |
+
return {
|
| 127 |
+
"history": [{"role": "user" if i % 2 == 0 else "assistant", "content": h["content"]} for i, h in enumerate(reversed(history))],
|
| 128 |
+
"relevant_memories": [r["content"][:200] for r in relevant],
|
| 129 |
+
"session_id": session_id,
|
| 130 |
+
}
|