The PostgresDb class provides PostgreSQL storage for agents, sessions, memories, and more. It’s the recommended database for production deployments.
Constructor
from agno.db.postgres import PostgresDb
db = PostgresDb(
host="localhost",
port=5432,
db="agno",
user="user",
password="password"
)
Parameters
Database driver: “psycopg” or “pg8000”.
Maximum overflow connections.
If True, automatically creates required tables.
session_table
str
default:"agno_sessions"
Name of the sessions table.
And other table name parameters.
Methods
Inherits all methods from BaseDb.
close()
Close database connections and release pool resources.
Example Usage
from agno import Agent
from agno.db.postgres import PostgresDb
db = PostgresDb(
host="localhost",
db="agno",
user="agno_user",
password="secret"
)
agent = Agent(
model="gpt-4o",
db=db,
add_history_to_context=True
)
Production Setup
Connection String
from agno.db.postgres import PostgresDb
db = PostgresDb.from_url(
"postgresql://user:password@localhost:5432/agno"
)
With Connection Pooling
db = PostgresDb(
host="db.example.com",
db="agno",
user="app_user",
password="secret",
pool_size=20, # Core pool size
max_overflow=30, # Additional connections
pool_timeout=30, # Wait time for connection
pool_recycle=3600 # Recycle connections after 1 hour
)
Multi-tenancy
# Separate tables per tenant
tenant_db = PostgresDb(
host="localhost",
db="agno",
user="user",
password="password",
session_table=f"tenant_{tenant_id}_sessions",
memory_table=f"tenant_{tenant_id}_memories"
)
Best Practices
- Use connection pooling: Configure appropriate pool_size for your workload
- Environment variables: Store credentials in environment variables
- SSL in production: Always use SSL for production databases
- Regular backups: Set up automated backups
- Monitor connections: Monitor pool usage and adjust as needed
- Close on shutdown: Call
db.close() during application shutdown
- Indexes: Ensure tables are properly indexed for your queries
Migration from SQLite
from agno.db.sqlite import SQLiteDb
from agno.db.postgres import PostgresDb
# Export from SQLite
sqlite_db = SQLiteDb(db_file="agent.db")
sessions = sqlite_db.get_sessions(session_type=SessionType.AGENT)
# Import to PostgreSQL
postgres_db = PostgresDb(...)
postgres_db.upsert_sessions(sessions)