memory_service.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343
  1. """
  2. agentpaas.services.memory_service — Persistent memory service
  3. Three-tier memory model:
  4. Working — current session context (already exists in Context)
  5. Episodic — recent conversation summaries (auto-compressed, 7 days)
  6. Semantic — permanent knowledge (user preferences, project structure)
  7. Storage: SQLite for dev, Redis for prod.
  8. """
  9. from __future__ import annotations
  10. import json
  11. import os
  12. import time
  13. import hashlib
  14. from dataclasses import dataclass, field, asdict
  15. from typing import Any, Dict, List, Optional
  16. # ════════════════════════════════════════════════════════════
  17. # Memory Entry
  18. # ════════════════════════════════════════════════════════════
  19. @dataclass
  20. class MemoryEntry:
  21. """A single memory record."""
  22. key: str
  23. content: str
  24. tier: str = "semantic" # working / episodic / semantic
  25. tags: List[str] = field(default_factory=list)
  26. source: str = "" # agent_id or "user"
  27. created_at: float = 0
  28. expires_at: float = 0 # 0 = never expires
  29. access_count: int = 0
  30. relevance_score: float = 0 # for search ranking
  31. def __post_init__(self):
  32. if self.created_at == 0:
  33. self.created_at = time.time()
  34. if not self.key:
  35. self.key = hashlib.md5(self.content.encode()).hexdigest()[:12]
  36. def is_expired(self) -> bool:
  37. return self.expires_at > 0 and time.time() > self.expires_at
  38. def to_dict(self) -> dict:
  39. return asdict(self)
  40. @classmethod
  41. def from_dict(cls, data: dict) -> MemoryEntry:
  42. return cls(**{k: v for k, v in data.items() if k in cls.__dataclass_fields__})
  43. # ════════════════════════════════════════════════════════════
  44. # Memory Store (SQLite backend)
  45. # ════════════════════════════════════════════════════════════
  46. class MemoryStore:
  47. """Persistent memory store using SQLite."""
  48. def __init__(self, db_path: str = ""):
  49. self.db_path = db_path or os.path.expanduser("~/.lambdagent/memory.db")
  50. os.makedirs(os.path.dirname(self.db_path), exist_ok=True)
  51. self._init_db()
  52. def _init_db(self):
  53. import sqlite3
  54. conn = sqlite3.connect(self.db_path)
  55. conn.execute("""
  56. CREATE TABLE IF NOT EXISTS memories (
  57. key TEXT PRIMARY KEY,
  58. content TEXT NOT NULL,
  59. tier TEXT DEFAULT 'semantic',
  60. tags TEXT DEFAULT '[]',
  61. source TEXT DEFAULT '',
  62. created_at REAL,
  63. expires_at REAL DEFAULT 0,
  64. access_count INTEGER DEFAULT 0,
  65. relevance_score REAL DEFAULT 0
  66. )
  67. """)
  68. conn.execute("""
  69. CREATE INDEX IF NOT EXISTS idx_tier ON memories(tier)
  70. """)
  71. conn.execute("""
  72. CREATE INDEX IF NOT EXISTS idx_source ON memories(source)
  73. """)
  74. conn.commit()
  75. conn.close()
  76. def _conn(self):
  77. import sqlite3
  78. conn = sqlite3.connect(self.db_path)
  79. conn.row_factory = sqlite3.Row
  80. return conn
  81. def store(self, entry: MemoryEntry) -> str:
  82. """Store or update a memory entry."""
  83. conn = self._conn()
  84. conn.execute("""
  85. INSERT OR REPLACE INTO memories
  86. (key, content, tier, tags, source, created_at, expires_at, access_count, relevance_score)
  87. VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
  88. """, (entry.key, entry.content, entry.tier, json.dumps(entry.tags),
  89. entry.source, entry.created_at, entry.expires_at,
  90. entry.access_count, entry.relevance_score))
  91. conn.commit()
  92. conn.close()
  93. return entry.key
  94. def recall(self, query: str, tier: str = "", source: str = "",
  95. top_k: int = 5) -> List[MemoryEntry]:
  96. """Recall memories by relevance to query."""
  97. conn = self._conn()
  98. # Build WHERE clause
  99. conditions = ["expires_at = 0 OR expires_at > ?"]
  100. params: list = [time.time()]
  101. if tier:
  102. conditions.append("tier = ?")
  103. params.append(tier)
  104. if source:
  105. conditions.append("source = ?")
  106. params.append(source)
  107. where = " AND ".join(conditions)
  108. rows = conn.execute(
  109. f"SELECT * FROM memories WHERE {where} ORDER BY created_at DESC LIMIT 100",
  110. params
  111. ).fetchall()
  112. conn.close()
  113. # Score by simple keyword matching (TF-IDF would be better but this is fast)
  114. query_words = set(query.lower().split())
  115. results = []
  116. for row in rows:
  117. entry = MemoryEntry(
  118. key=row["key"], content=row["content"], tier=row["tier"],
  119. tags=json.loads(row["tags"]), source=row["source"],
  120. created_at=row["created_at"], expires_at=row["expires_at"],
  121. access_count=row["access_count"],
  122. )
  123. # Relevance scoring
  124. content_words = set(entry.content.lower().split())
  125. tag_words = set(t.lower() for t in entry.tags)
  126. overlap = len(query_words & (content_words | tag_words))
  127. entry.relevance_score = overlap / max(1, len(query_words))
  128. results.append(entry)
  129. # Sort by relevance, then by recency
  130. results.sort(key=lambda e: (-e.relevance_score, -e.created_at))
  131. # Update access count for returned entries
  132. if results[:top_k]:
  133. conn = self._conn()
  134. for entry in results[:top_k]:
  135. conn.execute("UPDATE memories SET access_count = access_count + 1 WHERE key = ?",
  136. (entry.key,))
  137. conn.commit()
  138. conn.close()
  139. return results[:top_k]
  140. def get(self, key: str) -> Optional[MemoryEntry]:
  141. """Get a specific memory by key."""
  142. conn = self._conn()
  143. row = conn.execute("SELECT * FROM memories WHERE key = ?", (key,)).fetchone()
  144. conn.close()
  145. if not row:
  146. return None
  147. return MemoryEntry(
  148. key=row["key"], content=row["content"], tier=row["tier"],
  149. tags=json.loads(row["tags"]), source=row["source"],
  150. created_at=row["created_at"], expires_at=row["expires_at"],
  151. access_count=row["access_count"],
  152. )
  153. def forget(self, key: str) -> bool:
  154. """Delete a memory entry."""
  155. conn = self._conn()
  156. conn.execute("DELETE FROM memories WHERE key = ?", (key,))
  157. affected = conn.total_changes
  158. conn.commit()
  159. conn.close()
  160. return affected > 0
  161. def list_all(self, tier: str = "", source: str = "", limit: int = 50) -> List[MemoryEntry]:
  162. """List memories."""
  163. conn = self._conn()
  164. conditions = ["1=1"]
  165. params: list = []
  166. if tier:
  167. conditions.append("tier = ?")
  168. params.append(tier)
  169. if source:
  170. conditions.append("source = ?")
  171. params.append(source)
  172. where = " AND ".join(conditions)
  173. rows = conn.execute(
  174. f"SELECT * FROM memories WHERE {where} ORDER BY created_at DESC LIMIT ?",
  175. params + [limit]
  176. ).fetchall()
  177. conn.close()
  178. return [
  179. MemoryEntry(key=r["key"], content=r["content"], tier=r["tier"],
  180. tags=json.loads(r["tags"]), source=r["source"],
  181. created_at=r["created_at"], access_count=r["access_count"])
  182. for r in rows
  183. ]
  184. def cleanup_expired(self) -> int:
  185. """Remove expired episodic memories."""
  186. conn = self._conn()
  187. conn.execute("DELETE FROM memories WHERE expires_at > 0 AND expires_at < ?",
  188. (time.time(),))
  189. affected = conn.total_changes
  190. conn.commit()
  191. conn.close()
  192. return affected
  193. def stats(self) -> dict:
  194. """Memory statistics."""
  195. conn = self._conn()
  196. total = conn.execute("SELECT COUNT(*) FROM memories").fetchone()[0]
  197. by_tier = {}
  198. for row in conn.execute("SELECT tier, COUNT(*) as cnt FROM memories GROUP BY tier"):
  199. by_tier[row["tier"]] = row["cnt"]
  200. conn.close()
  201. return {"total": total, "by_tier": by_tier, "db_path": self.db_path}
  202. # ════════════════════════════════════════════════════════════
  203. # Agent-side tool functions
  204. # ════════════════════════════════════════════════════════════
  205. _default_store = None
  206. def _get_store() -> MemoryStore:
  207. global _default_store
  208. if _default_store is None:
  209. _default_store = MemoryStore()
  210. return _default_store
  211. def memory_store(input_val: Any) -> str:
  212. """Store a memory. Input: {content, tags?, tier?, key?}"""
  213. params = _parse(input_val)
  214. content = params.get("content", "")
  215. if not content:
  216. return "[ERROR] content is required"
  217. entry = MemoryEntry(
  218. key=params.get("key", ""),
  219. content=content,
  220. tier=params.get("tier", "semantic"),
  221. tags=params.get("tags", []),
  222. source=params.get("source", "agent"),
  223. )
  224. ttl = params.get("ttl", 0)
  225. if ttl > 0:
  226. entry.expires_at = time.time() + ttl
  227. entry.tier = "episodic"
  228. key = _get_store().store(entry)
  229. return f"[OK] Memory stored: key={key}, tier={entry.tier}"
  230. def memory_recall(input_val: Any) -> str:
  231. """Recall memories by query. Input: {query, top_k?, tier?}"""
  232. params = _parse(input_val)
  233. query = params.get("query", "")
  234. if not query:
  235. return "[ERROR] query is required"
  236. results = _get_store().recall(
  237. query,
  238. tier=params.get("tier", ""),
  239. source=params.get("source", ""),
  240. top_k=params.get("top_k", 5),
  241. )
  242. if not results:
  243. return f"[NO_MATCH] No memories matching '{query}'"
  244. lines = []
  245. for entry in results:
  246. tags = f" [{', '.join(entry.tags)}]" if entry.tags else ""
  247. lines.append(f"[{entry.tier}] (score={entry.relevance_score:.2f}{tags})")
  248. lines.append(f" {entry.content[:300]}")
  249. lines.append("")
  250. return "\n".join(lines)
  251. def memory_list(input_val: Any) -> str:
  252. """List all memories. Input: {tier?, limit?}"""
  253. params = _parse(input_val) if input_val else {}
  254. entries = _get_store().list_all(
  255. tier=params.get("tier", ""),
  256. limit=params.get("limit", 20),
  257. )
  258. if not entries:
  259. return "[EMPTY] No memories stored"
  260. lines = []
  261. for e in entries:
  262. age = _format_age(time.time() - e.created_at)
  263. tags = f" [{', '.join(e.tags)}]" if e.tags else ""
  264. lines.append(f" [{e.tier}] {e.key}: {e.content[:80]}...{tags} ({age})")
  265. stats = _get_store().stats()
  266. lines.insert(0, f"Memories: {stats['total']} total ({stats['by_tier']})")
  267. return "\n".join(lines)
  268. def memory_forget(input_val: Any) -> str:
  269. """Forget a memory. Input: {key}"""
  270. params = _parse(input_val)
  271. key = params.get("key", "")
  272. if not key:
  273. return "[ERROR] key is required"
  274. if _get_store().forget(key):
  275. return f"[OK] Memory forgotten: {key}"
  276. return f"[ERROR] Memory not found: {key}"
  277. def _format_age(seconds: float) -> str:
  278. if seconds < 60:
  279. return "just now"
  280. if seconds < 3600:
  281. return f"{int(seconds/60)}m ago"
  282. if seconds < 86400:
  283. return f"{int(seconds/3600)}h ago"
  284. return f"{int(seconds/86400)}d ago"
  285. def _parse(input_val: Any) -> dict:
  286. if isinstance(input_val, dict):
  287. return input_val
  288. if isinstance(input_val, str):
  289. try:
  290. return json.loads(input_val)
  291. except (json.JSONDecodeError, ValueError):
  292. return {"query": input_val} if len(input_val) < 200 else {"content": input_val}
  293. return {}