Ep. 11 — Persistent Memory in SQLite: Episodes, Timestamps, and Provenance
Yesterday we saw how embeddings turn words into coordinates: "dog" and "puppy" end up close in vector space. But there's a problem. Turn off the process, restart the script: the coordinates vanish. The agent wakes up virgin, with no memory of what it learned. Today we give it a permanent address.
Imagine a laboratory notebook. Not loose sheets scattered by wind: numbered, dated, signed pages. Every entry answers three questions: what happened, when, and where the information came from. In technical terms: content, timestamp, provenance. Without these three coordinates, an agent mistakes yesterday's hypothesis for a fact observed a minute ago.
SQLite is the natural choice: a single file, no server, zero configuration, yet ACID-compliant. All it takes is a well-designed table.
import sqlite3
from datetime import datetime
from pathlib import Path
DB_PATH = Path("memoria_agente.db")
def init_db():
with sqlite3.connect(DB_PATH) as conn:
conn.execute("""
CREATE TABLE IF NOT EXISTS episodes (
id INTEGER PRIMARY KEY AUTOINCREMENT,
type TEXT NOT NULL, -- e.g. 'observation', 'hypothesis', 'action'
content TEXT NOT NULL, -- the fact, the text, the serialized vector
timestamp TEXT NOT NULL, -- ISO 8601: 2026-12-01T14:30:00.123456
provenance TEXT NOT NULL, -- origin: 'user', 'sensor:camera', 'web:search', 'inference:llm'
embedding BLOB -- optional: serialized vector (bytes)
)
""")
# Indexes for temporal queries and provenance
conn.execute("CREATE INDEX IF NOT EXISTS idx_episodes_time ON episodes(timestamp)")
conn.execute("CREATE INDEX IF NOT EXISTS idx_episodes_prov ON episodes(provenance)")
def save_episode(type: str, content: str, provenance: str, embedding: bytes | None = None):
now = datetime.utcnow().isoformat(timespec='microseconds')
with sqlite3.connect(DB_PATH) as conn:
conn.execute(
"INSERT INTO episodes (type, content, timestamp, provenance, embedding) VALUES (?, ?, ?, ?, ?)",
(type, content, now, provenance, embedding)
)
# Usage example
if __name__ == "__main__":
init_db()
save_episode(
type="observation",
content="User asked for temperature in Milan",
provenance="user:telegram"
)
save_episode(
type="inference:llm",
content="Forecast: 12°C, light rain",
provenance="model:weather-gpt"
)
print("Episodes saved. Restart the script all you want: they stay here.")Every row is now a fact anchored in time and source. You can ask: "Give me all observations from the last hour coming from the user" or "What inferences did the weather model produce yesterday?". Provenance lets you weigh trust: a reading from a hardware sensor weighs more than an LLM hypothesis.
Where we stop today
As days pass memory grows, but the AI's chalkboard stays narrow. Tomorrow we talk about when those files become more than an archive: Ep. 12 — Log vs Continuity: When Memory Becomes Identity. Check back at progettosiliceo.online/tutorial-agenti.html.