Implementing Persistent Memory in AI Agents Using SQLite: A Complete Guide
AI agents in the awesome-ai-apps repository achieve session continuity by persisting state to embedded SQLite databases, using either the SqliteDb class for conversation history or the Memori framework for long-term semantic memory.
Implementing persistent memory in AI agents using SQLite allows your agents to recall previous interactions, maintain user context across restarts, and share knowledge between multiple agent instances. The awesome-ai-apps repository demonstrates two complementary patterns for achieving durable state: short-term conversation storage via Agno's SqliteDb and long-term knowledge retention via the Memori library. Both approaches leverage SQLite's zero-dependency architecture to create portable, file-based persistence without requiring external database servers.
Why SQLite for AI Agent Persistence?
SQLite provides three critical advantages for agent memory systems:
- Zero-dependency deployment: The database lives in a single file (
*.dbor*.sqlite) that works on any platform without installing or managing a separate database server process. - ACID transaction guarantees: Every write operation, whether storing conversation turns or memory blocks, is wrapped in a transaction, ensuring data is never partially committed during crashes or interruptions.
- Fast indexed retrieval: SQLite's B-tree indexes enable O(log n) performance for operations agents frequently perform, such as fetching the most recent k conversation rows or querying specific memory namespaces.
Short-Term Conversation History with SqliteDb
The SqliteDb class from the Agno framework manages ephemeral-to-short-term memory, automatically storing agent runs and injecting historical context into prompts.
Configuring SqliteDb for Agent State
In simple_ai_agents/email_to_calendar_scheduler/main.py, the repository initializes a shared database connection that persists across multiple agents and team orchestration:
import os
from agno.db.sqlite import SqliteDb
from agno.agent import Agent
from agno.models.nebius import Nebius
# Path can be customised via DB_PATH env var
DB_PATH = os.getenv(
"DB_PATH",
os.path.join(os.path.dirname(__file__), "tmp", "data.db")
)
os.makedirs(os.path.dirname(DB_PATH), exist_ok=True)
# Initialise the lightweight DB wrapper
db = SqliteDb(db_file=DB_PATH)
# Attach it to an agent with history enabled
email_agent = Agent(
model=Nebius(id="Qwen/Qwen3-32b", api_key=os.getenv("NEBIUS_API_KEY")),
tools=[...],
db=db, # ← persistent store
add_history_to_context=True, # Inject past runs into prompts
num_history_runs=3, # Keep last 3 exchanges
read_chat_history=True, # Enable UI timeline survival
)
When add_history_to_context=True, the framework automatically prepends the last n conversation turns (specified by num_history_runs) from the SQLite database to every new prompt. The read_chat_history=True flag additionally enables Streamlit interfaces to display conversation timelines that survive process restarts.
Long-Term Semantic Memory with Memori
For durable knowledge that must survive indefinitely and be queryable via natural language, the repository uses Memori configured with a SQLite backend.
Setting Up Memori with SQLite Backend
The Memori class accepts a SQLAlchemy-style URI via the database_connect parameter, creating a vector-enabled knowledge store backed by a local SQLite file. This pattern appears in memory_agents/social_media_agent/twitter_agents.py:
from memori import Memori, create_memory_tool
def init_memori():
mem = Memori(
database_connect="sqlite:///tmp/twitter_style_memory.db",
auto_ingest=True,
conscious_ingest=True,
namespace="twitter_tweeting_style",
)
mem.enable()
return mem, create_memory_tool(mem)
# Initialise once at application startup
memory_system, memory_tool = init_memori()
# Store structured memory blocks
memory_system.record_conversation(
user_input="My tweeting style is casual and humorous.",
ai_output="Got it! I'll keep that tone in mind.",
model="nebius-glm-4.5-air",
metadata={"type": "twitter_style_profile", "handle": "@myhandle"},
)
# Retrieve with natural-language queries
result = memory_tool.execute(query="twitter style tone personality")
The record_conversation method writes structured facts (including metadata JSON) to the SQLite file, while execute performs similarity searches over stored chunks. Because the connection string points to a file path, the same memory persists through container restarts and remains accessible to other agents or future sessions.
Multi-Agent Teams with Shared Persistence
The repository demonstrates combining both persistence patterns within a Team orchestration. By passing the same SqliteDb instance to multiple agents and the team itself, all members share a unified conversation history, while Memori provides cross-cutting long-term knowledge:
from agno.team import Team
team = Team(
name="Productivity Agent",
members=[email_agent, calendar_agent],
db=db, # Shared conversation history
model=Nebius(...),
instructions=[
"First, read the latest emails …",
"Then, update the calendar …",
"Always check your long‑term Memori store for prior style info."
],
)
This configuration, found in simple_ai_agents/email_to_calendar_scheduler/main.py, ensures that when the email_agent hands off to the calendar_agent, both see the same interaction history from the SQLite database, while the Memori system (initialized separately) provides persistent user preferences.
Project Configuration and File Management
The awesome-ai-apps repository follows specific conventions for database file handling:
- Environment overrides: Both patterns support environment variables (
DB_PATHforSqliteDb,SQLITE_DB_PATHforMemori) to customize file locations without code changes. - Directory creation: The code explicitly creates parent directories using
os.makedirs(os.path.dirname(DB_PATH), exist_ok=True)before initializing connections. - Git exclusion: The root
.gitignoreexplicitly ignores SQLite artifacts (db.sqlite3*) to prevent database files from entering version control.
Summary
- Two storage patterns: Use
SqliteDbfor automatic conversation history persistence andMemorifor queryable long-term semantic memory. - SQLite advantages: File-based storage provides ACID guarantees, zero external dependencies, and fast indexed reads for agent retrieval patterns.
- Implementation location: Reference
simple_ai_agents/email_to_calendar_scheduler/main.pyforSqliteDbusage andmemory_agents/social_media_agent/twitter_agents.pyforMemoriconfiguration. - Configuration: Override default paths using
DB_PATHorSQLITE_DB_PATHenvironment variables; database directories are created automatically on first run. - Multi-agent support: Pass the same
SqliteDbinstance toAgentandTeamconstructors to share state across agent boundaries.
Frequently Asked Questions
How does add_history_to_context differ from read_chat_history?
The add_history_to_context=True parameter instructs the Agno framework to fetch previous conversation turns from the SQLite database and prepend them to the LLM prompt, directly affecting the model's context window. In contrast, read_chat_history=True enables the UI layer (such as Streamlit) to display historical messages to the user without necessarily including them in the model's context, allowing for visual timeline continuity even when you limit the context window size.
Can multiple agents share the same SQLite database file?
Yes. In simple_ai_agents/email_to_calendar_scheduler/main.py, the repository demonstrates instantiating a single SqliteDb object and passing it to both individual Agent instances and a parent Team object via the db= parameter. This ensures all agents write to and read from the same SQLite file, creating a unified conversation history across the entire multi-agent workflow.
What is the difference between SqliteDb and Memori persistence?
SqliteDb (from the Agno framework) automatically persists agent run metadata, tool usage, and conversation turns for the purpose of maintaining short-term session history and enabling context window management. Memori (from the memori package) provides a higher-level abstraction for long-term memory, storing structured "memory blocks" that can be retrieved via natural-language queries and shared across different agents or sessions, effectively functioning as a semantic knowledge base rather than just a conversation log.
How do I change the default SQLite file location?
For SqliteDb, set the DB_PATH environment variable before running your script; the code in simple_ai_agents/email_to_calendar_scheduler/main.py uses os.getenv("DB_PATH", default_path) to determine the file location. For Memori, as shown in memory_agents/youtube_trend_agent/core.py, set the SQLITE_DB_PATH environment variable or directly modify the database_connect parameter in the constructor to point to your preferred file path (e.g., "sqlite:///custom/path/memory.db").
Have a question about this repo?
These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:
curl -s "https://instagit.com/install.md" Maintain an open-source project? Get it listed too →