Context Persistence Across Sessions
Storing and loading user preferences, conversation history, and task state.
Why Persist Context?
Without persistence, every agent session starts from scratch. A context-persistent agent remembers the user's name, past conversations, stated preferences, and facts the user shared. This makes interactions feel continuous and personal.
SQLite for Session State
SQLite is perfect for single-user personal agents: zero server overhead, file-based, and reliable. Store conversation history and user data in a local database.
import sqlite3
from datetime import datetime
def init_db(db_path: str = 'agent_memory.db') -> sqlite3.Connection:
conn = sqlite3.connect(db_path, check_same_thread=False)
conn.row_factory = sqlite3.Row # Dict-like access
conn.executescript('''
CREATE TABLE IF NOT EXISTS sessions (
id INTEGER PRIMARY KEY AUTOINCREMENT,
session_id TEXT UNIQUE NOT NULL,
user_id TEXT NOT NULL,
started_at TEXT,
last_active TEXT
);
CREATE TABLE IF NOT EXISTS messages (
id INTEGER PRIMARY KEY AUTOINCREMENT,
session_id TEXT NOT NULL,
role TEXT NOT NULL,
content TEXT NOT NULL,
timestamp TEXT NOT NULL
);
CREATE TABLE IF NOT EXISTS user_facts (
id INTEGER PRIMARY KEY AUTOINCREMENT,
user_id TEXT NOT NULL,
fact_key TEXT NOT NULL,
fact_value TEXT NOT NULL,
created_at TEXT,
UNIQUE(user_id, fact_key)
);
''')
conn.commit()
return conn
conn = init_db()
print('Database initialized')All lessons in this course
- Always-On Agent Design Patterns
- Proactive Notification and Alert Systems
- Context Persistence Across Sessions
- Building a Daily Briefing Agent