Code

cookbook/agent_concepts/memory/postgres_memory.py
"""
This example shows how to use the Memory class with PostgreSQL storage.
"""

import asyncio
import os

from agno.agent.agent import Agent
from agno.memory.v2.db.postgres import PostgresMemoryDb
from agno.memory.v2.memory import Memory
from agno.models.openai.chat import OpenAIChat

# Get PostgreSQL connection string from environment
# Format: postgresql://user:password@localhost:5432/dbname
postgres_url = "postgresql://postgres:postgres@localhost:5432/agno_memory"

# Create PostgreSQL memory database
memory_db = PostgresMemoryDb(
    table_name="agno_memory",  # Table name to use in the database
    connection_string=postgres_url,
    schema_name="public",      # Schema name for the table (optional)
)

# Create memory instance with PostgreSQL backend
memory = Memory(db=memory_db)

# This will create the table if it doesn't exist
memory.clear()

# Create agent with memory
agent = Agent(
    model=OpenAIChat(id="gpt-4o"),
    memory=memory,
    enable_user_memories=True,
)

async def run_example():
    # Use the agent with PostgreSQL-backed memory
    await agent.aprint_response(
        "My name is John Doe and I like to hike in the mountains on weekends.",
        user_id="john@example.com",
    )
    
    await agent.aprint_response(
        "What are my hobbies?",
        user_id="john@example.com",
    )
    
    # Display the memories stored in PostgreSQL
    memories = memory.get_user_memories(user_id="john@example.com")
    print("Memories stored in PostgreSQL:")
    for i, m in enumerate(memories):
        print(f"{i}: {m.memory}")

if __name__ == "__main__":
    asyncio.run(run_example())

Usage

1

Create a virtual environment

Open the Terminal and create a python virtual environment.

python3 -m venv .venv
source .venv/bin/activate
2

Set environment variables

export OPENAI_API_KEY=xxx
3

Install libraries

pip install -U agno openai sqlalchemy 'psycopg[binary]'
4

Run Example

python cookbook/agent_concepts/memory/postgres_memory.py