-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmemory.py
More file actions
99 lines (75 loc) · 2.86 KB
/
memory.py
File metadata and controls
99 lines (75 loc) · 2.86 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
"""
Memory — Persistent user & session context
JSON-backed, survives restarts. No amnesia.
"""
import json
import logging
from datetime import datetime
from pathlib import Path
from typing import Any
logger = logging.getLogger("memory")
DATA_DIR = Path("~/.cin_agent").expanduser()
MEMORY_FILE = DATA_DIR / "memory.json"
MAX_HISTORY = 50 # messages per user
def _load() -> dict:
DATA_DIR.mkdir(parents=True, exist_ok=True)
if MEMORY_FILE.exists():
try:
return json.loads(MEMORY_FILE.read_text())
except (json.JSONDecodeError, IOError):
logger.warning("Memory file corrupted, starting fresh")
return {"users": {}, "globals": {}}
def _save(data: dict):
MEMORY_FILE.write_text(json.dumps(data, indent=2, default=str))
# ── Public API ─────────────────────────────────────────────────────────────
def remember(user_id: int | str, key: str, value: Any):
"""Store a fact about a user."""
data = _load()
uid = str(user_id)
data["users"].setdefault(uid, {"facts": {}, "history": []})
data["users"][uid]["facts"][key] = value
_save(data)
def recall(user_id: int | str, key: str, default=None) -> Any:
"""Retrieve a stored fact about a user."""
data = _load()
uid = str(user_id)
return data["users"].get(uid, {}).get("facts", {}).get(key, default)
def add_history(user_id: int | str, role: str, content: str):
"""Append a message to user's conversation history."""
data = _load()
uid = str(user_id)
data["users"].setdefault(uid, {"facts": {}, "history": []})
history = data["users"][uid]["history"]
history.append({
"role": role,
"content": content,
"ts": datetime.now().isoformat(),
})
# Trim to max
if len(history) > MAX_HISTORY:
data["users"][uid]["history"] = history[-MAX_HISTORY:]
_save(data)
def get_history(user_id: int | str, n: int = 10) -> list[dict]:
"""Get last n messages for a user (without timestamps, for LLM context)."""
data = _load()
uid = str(user_id)
history = data["users"].get(uid, {}).get("history", [])
return [{"role": h["role"], "content": h["content"]} for h in history[-n:]]
def get_user_profile(user_id: int | str) -> dict:
"""Get everything known about a user."""
data = _load()
uid = str(user_id)
return data["users"].get(uid, {"facts": {}, "history": []})
def set_global(key: str, value: Any):
data = _load()
data["globals"][key] = value
_save(data)
def get_global(key: str, default=None) -> Any:
data = _load()
return data["globals"].get(key, default)
def clear_user_history(user_id: int | str):
data = _load()
uid = str(user_id)
if uid in data["users"]:
data["users"][uid]["history"] = []
_save(data)