Spaces:
Running
Running
File size: 7,386 Bytes
6cdcdeb 9918f43 6cdcdeb 9918f43 6cdcdeb 9918f43 6cdcdeb 9918f43 6cdcdeb | 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 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 | """Long-term memory layer (semantic / procedural / episodic).
Uses stdlib ``sqlite3`` so the project ships with no extra dependencies.
The interface mirrors the three-tier taxonomy from the recent agent-memory
literature, so an alternative backend (Mem0 / Letta / sqlite-vec) can
replace this one without touching the call sites.
Tiers
-----
* **Working** — held in the LangGraph state (untouched by this module).
* **Semantic** — atomic facts about the user (likes, dislikes, hard
constraints, lab results). Survives across sessions.
* **Procedural** — verdicts the validator produced. Lets the system note
"this user rejected high-carb breakfasts twice" without re-asking.
* **Episodic** — JSON snapshot of past sessions for replay / audit.
The schema is three tables, one row per fact / verdict / session. SQL
``LIKE`` over short text is sufficient at the demo's scale; a vector
backend can be added when retrieval recall becomes the bottleneck.
"""
from __future__ import annotations
import json
import sqlite3
import threading
from datetime import datetime
from typing import Any, Dict, List, Optional
_SCHEMA = """
CREATE TABLE IF NOT EXISTS semantic_facts (
id INTEGER PRIMARY KEY AUTOINCREMENT,
user_id TEXT NOT NULL,
fact_type TEXT NOT NULL, -- e.g. 'dislike', 'allergy', 'preference'
content TEXT NOT NULL,
source TEXT NOT NULL DEFAULT '', -- e.g. 'user_stated', 'inferred', 'validator'
created_at TEXT NOT NULL
);
CREATE INDEX IF NOT EXISTS idx_facts_user ON semantic_facts(user_id, fact_type);
CREATE TABLE IF NOT EXISTS procedural_records (
id INTEGER PRIMARY KEY AUTOINCREMENT,
user_id TEXT NOT NULL,
plan_summary TEXT NOT NULL,
verdict TEXT NOT NULL, -- 'pass' | 'revise' | 'reject'
issues_json TEXT NOT NULL, -- JSON list of ValidationIssue
created_at TEXT NOT NULL
);
CREATE INDEX IF NOT EXISTS idx_proc_user ON procedural_records(user_id, created_at);
CREATE TABLE IF NOT EXISTS episodic_sessions (
id INTEGER PRIMARY KEY AUTOINCREMENT,
user_id TEXT NOT NULL,
session_id TEXT NOT NULL,
payload_json TEXT NOT NULL, -- JSON snapshot of session state
created_at TEXT NOT NULL
);
CREATE INDEX IF NOT EXISTS idx_episodic_user ON episodic_sessions(user_id, created_at);
"""
class LongTermMemory:
"""SQLite-backed three-tier long-term memory.
Pass a file path for persistence across runs, or ``None`` (default) for an
in-memory database useful in tests / ephemeral demos.
"""
def __init__(self, db_path: Optional[str] = None) -> None:
self.db_path = db_path or ":memory:"
# SQLite connections are not thread-safe by default; one connection per
# thread is the standard pattern. The demo is single-process so a single
# connection + lock is enough.
self.conn = sqlite3.connect(self.db_path, check_same_thread=False)
self.conn.row_factory = sqlite3.Row
self._lock = threading.Lock()
self._init_schema()
def _init_schema(self) -> None:
with self._lock:
self.conn.executescript(_SCHEMA)
self.conn.commit()
def close(self) -> None:
with self._lock:
self.conn.close()
# ------------------------------------------------------------------
# Semantic facts
# ------------------------------------------------------------------
def remember_fact(
self,
user_id: str,
fact_type: str,
content: str,
source: str = "user_stated",
) -> int:
"""Insert a semantic fact. Returns the row id."""
now = datetime.utcnow().isoformat()
with self._lock:
cur = self.conn.execute(
"INSERT INTO semantic_facts (user_id, fact_type, content, source, created_at) "
"VALUES (?, ?, ?, ?, ?)",
(user_id, fact_type, content, source, now),
)
self.conn.commit()
return int(cur.lastrowid or 0)
def recall_facts(
self,
user_id: str,
fact_type: Optional[str] = None,
contains: Optional[str] = None,
limit: int = 50,
) -> List[Dict[str, Any]]:
"""List facts for a user, optionally filtered by type / substring."""
sql = "SELECT * FROM semantic_facts WHERE user_id = ?"
params: List[Any] = [user_id]
if fact_type:
sql += " AND fact_type = ?"
params.append(fact_type)
if contains:
sql += " AND content LIKE ?"
params.append(f"%{contains}%")
sql += " ORDER BY created_at DESC LIMIT ?"
params.append(limit)
with self._lock:
cur = self.conn.execute(sql, params)
return [dict(row) for row in cur.fetchall()]
def forget_fact(self, fact_id: int) -> None:
with self._lock:
self.conn.execute("DELETE FROM semantic_facts WHERE id = ?", (fact_id,))
self.conn.commit()
# ------------------------------------------------------------------
# Procedural records (validator history)
# ------------------------------------------------------------------
def remember_validation(
self,
user_id: str,
plan_summary: str,
verdict: str,
issues: List[Dict[str, Any]],
) -> int:
now = datetime.utcnow().isoformat()
with self._lock:
cur = self.conn.execute(
"INSERT INTO procedural_records (user_id, plan_summary, verdict, issues_json, created_at) "
"VALUES (?, ?, ?, ?, ?)",
(user_id, plan_summary, verdict, json.dumps(issues), now),
)
self.conn.commit()
return int(cur.lastrowid or 0)
def recall_validations(self, user_id: str, limit: int = 10) -> List[Dict[str, Any]]:
with self._lock:
cur = self.conn.execute(
"SELECT * FROM procedural_records WHERE user_id = ? ORDER BY created_at DESC LIMIT ?",
(user_id, limit),
)
return [
{**dict(row), "issues": json.loads(row["issues_json"])}
for row in cur.fetchall()
]
# ------------------------------------------------------------------
# Episodic sessions
# ------------------------------------------------------------------
def remember_session(self, user_id: str, session_id: str, payload: Dict[str, Any]) -> int:
now = datetime.utcnow().isoformat()
with self._lock:
cur = self.conn.execute(
"INSERT INTO episodic_sessions (user_id, session_id, payload_json, created_at) "
"VALUES (?, ?, ?, ?)",
(user_id, session_id, json.dumps(payload, default=str), now),
)
self.conn.commit()
return int(cur.lastrowid or 0)
def recall_sessions(self, user_id: str, limit: int = 5) -> List[Dict[str, Any]]:
with self._lock:
cur = self.conn.execute(
"SELECT * FROM episodic_sessions WHERE user_id = ? ORDER BY created_at DESC LIMIT ?",
(user_id, limit),
)
return [
{**dict(row), "payload": json.loads(row["payload_json"])}
for row in cur.fetchall()
]
__all__ = ["LongTermMemory"]
|