DeepImagix commited on
Commit
7faca03
·
verified ·
1 Parent(s): c60914a

Upload memory.py

Browse files
Files changed (1) hide show
  1. agent/memory/memory.py +101 -0
agent/memory/memory.py CHANGED
@@ -0,0 +1,101 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ NeuraPrompt Agent — Memory Module v7.6 (MongoDB Integrated)
3
+ Properly connects to your existing MongoDB system from main.py
4
+ """
5
+
6
+ from typing import List, Dict, Optional
7
+ import logging
8
+ from datetime import datetime, timezone
9
+
10
+ log = logging.getLogger("agent.memory.v7.6")
11
+
12
+ # These will be injected from main.py
13
+ long_term_memory_col = None
14
+ chat_history_col = None
15
+
16
+
17
+ def set_collections(long_term_col, chat_history_col_ref):
18
+ """Call this from main.py to inject MongoDB collections"""
19
+ global long_term_memory_col, chat_history_col
20
+ long_term_memory_col = long_term_col
21
+ chat_history_col = chat_history_col_ref
22
+
23
+
24
+ class MemoryManager:
25
+ def __init__(self, user_id: str):
26
+ self.user_id = user_id
27
+ self.short_term: List[Dict] = []
28
+
29
+ def load_long_term_memory(self) -> Dict:
30
+ """Load user's long-term memory from MongoDB"""
31
+ if not long_term_memory_col:
32
+ return {}
33
+ try:
34
+ doc = long_term_memory_col.find_one({"user_id": self.user_id})
35
+ return doc or {}
36
+ except Exception as e:
37
+ log.error(f"Failed to load long-term memory: {e}")
38
+ return {}
39
+
40
+ def load_recent_chat(self, limit: int = 8) -> List[Dict]:
41
+ """Load recent chat history from MongoDB"""
42
+ if not chat_history_col:
43
+ return []
44
+ try:
45
+ cursor = chat_history_col.find(
46
+ {"user_id": self.user_id}
47
+ ).sort("timestamp", -1).limit(limit)
48
+ messages = list(cursor)
49
+ messages.reverse()
50
+ return messages
51
+ except Exception as e:
52
+ log.error(f"Failed to load chat history: {e}")
53
+ return []
54
+
55
+ def get_context_for_agent(self) -> str:
56
+ """Build rich context string for the agent"""
57
+ long_term = self.load_long_term_memory()
58
+ recent = self.load_recent_chat(6)
59
+
60
+ context_parts = []
61
+
62
+ # Long-term facts
63
+ if long_term:
64
+ facts = []
65
+ for key, value in long_term.items():
66
+ if key not in ["_id", "user_id", "last_updated"]:
67
+ facts.append(f"{key}: {value}")
68
+ if facts:
69
+ context_parts.append("Known about user: " + ", ".join(facts[:7]))
70
+
71
+ # Recent conversation
72
+ if recent:
73
+ chat_lines = []
74
+ for msg in recent[-5:]:
75
+ role = msg.get("role", "unknown").capitalize()
76
+ content = msg.get("content", "")[:180]
77
+ chat_lines.append(f"{role}: {content}")
78
+ context_parts.append("Recent conversation:\n" + "\n".join(chat_lines))
79
+
80
+ return "\n\n".join(context_parts) if context_parts else "No previous memory available."
81
+
82
+ def save_important_fact(self, key: str, value: str):
83
+ """Save important fact to long-term memory"""
84
+ if not long_term_memory_col:
85
+ return
86
+ try:
87
+ long_term_memory_col.update_one(
88
+ {"user_id": self.user_id},
89
+ {"$set": {
90
+ key: value,
91
+ "last_updated": datetime.now(timezone.utc)
92
+ }},
93
+ upsert=True
94
+ )
95
+ log.info(f"Saved fact '{key}' for user {self.user_id}")
96
+ except Exception as e:
97
+ log.error(f"Failed to save fact: {e}")
98
+
99
+
100
+ def get_memory_manager(user_id: str) -> MemoryManager:
101
+ return MemoryManager(user_id)