Persistent Session with History Context

Store agent conversation history in PostgreSQL and limit how many past runs are added to the context with num_history_runs.

Store conversation history in the session and add a configurable number of previous runs to the agent context.

Code

persistent_session_history.py
"""
This example shows how to use the session history to store the conversation history.
add_history_to_context flag is used to add the history to the messages.
num_history_runs is used to set the number of history runs to add to the messages.
"""

from agno.agent import Agent
from agno.db.postgres import PostgresDb
from agno.models.openai import OpenAIResponses

db_url = "postgresql+psycopg://ai:ai@localhost:5532/ai"

db = PostgresDb(db_url=db_url, session_table="sessions")

agent = Agent(
    model=OpenAIResponses(id="gpt-5.2"),
    db=db,
    add_history_to_context=True,
    num_history_runs=2,
    session_id="space-conversation",
)

agent.print_response("Tell me an interesting fact about space")
agent.print_response("Explain that fact in more detail")

The two turns use space-conversation. Reuse that ID to continue the same conversation after restarting; choose a new ID to start a separate thread. This curated example uses an explicit ID and follow-up turn.

Usage

Docker must be installed and running. Start the example database below, or reuse a compatible PostgreSQL server and update db_url. Before running Python, check readiness with docker exec pgvector pg_isready -U ai -d ai.

Set up your virtual environment

uv venv --python 3.12
source .venv/bin/activate

Install required libraries

uv pip install -U agno openai sqlalchemy "psycopg[binary]"

Set environment variables

export OPENAI_API_KEY="your-api-key"

Run PgVector

docker run -d \
  -e POSTGRES_DB=ai \
  -e POSTGRES_USER=ai \
  -e POSTGRES_PASSWORD=ai \
  -e PGDATA=/var/lib/postgresql \
  -v pgvolume:/var/lib/postgresql \
  -p 5532:5432 \
  --name pgvector \
  agnohq/pgvector:18

Run the agent

python persistent_session_history.py