To persist memories across sessions and execution cycles, store memories in a persistent storage like a database.If you’re using Memory in production, persistent storage is critical as you’d want to retain user memories across application restarts.Agno’s memory system supports multiple persistent storage options.
To configure memory storage, you’ll need to create a database instance and pass it to the Memory constructor:
Copy
Ask AI
from agno.memory.v2.memory import Memoryfrom agno.memory.v2.db.sqlite import SqliteMemoryDb# Create a SQLite database for memorymemory_db = SqliteMemoryDb( table_name="memories", # The table name to use db_file="path/to/memory.db" # The SQLite database file)# Initialize Memory with the storage backendmemory = Memory(db=memory_db)
from agno.memory.v2.memory import Memoryfrom agno.memory.v2.db.sqlite import SqliteMemoryDbfrom agno.memory.v2.schema import UserMemory# Create a SQLite memory databasememory_db = SqliteMemoryDb( table_name="user_memories", db_file="tmp/memory.db")# Initialize Memory with the storage backendmemory = Memory(db=memory_db)# Add a user memory that will persist across restartsuser_id = "user@example.com"memory.add_user_memory( memory=UserMemory( memory="The user prefers dark mode in applications", topics=["preferences", "ui"] ), user_id=user_id)# Retrieve memories (these will be loaded from the database)user_memories = memory.get_user_memories(user_id=user_id)for m in user_memories: print(f"Memory: {m.memory}") print(f"Topics: {m.topics}") print(f"Last Updated: {m.last_updated}")
postgres_memory.py
Copy
Ask AI
from agno.memory.v2.memory import Memoryfrom agno.memory.v2.db.postgres import PostgresMemoryDbfrom agno.memory.v2.schema import UserMemory# Create a PostgreSQL memory databasememory_db = PostgresMemoryDb( table_name="user_memories", connection_string="postgresql://user:password@localhost:5432/mydb")# Initialize Memory with the storage backendmemory = Memory(db=memory_db)# Add user memoriesuser_id = "user@example.com"memory.add_user_memory( memory=UserMemory( memory="The user has a premium subscription", topics=["subscription", "account"] ), user_id=user_id)# Memory operations work the same regardless of the backendprint(f"User has {len(memory.get_user_memories(user_id=user_id))} memories stored")
When building agents with memory, you’ll often want to store both agent sessions and memories. Agno makes this easy by allowing you to configure both storage systems:
When using persistent storage, the Memory system offers several functions to manage stored memories:
Copy
Ask AI
# Delete a specific memorymemory.delete_user_memory(user_id="user@example.com", memory_id="memory_123")# Replace/update a memorymemory.replace_user_memory( memory_id="memory_123", memory=UserMemory(memory="Updated information about the user"), user_id="user@example.com")# Clear all memoriesmemory.clear()