Code
persistent_session_history.py
Usage
1
Set up your virtual environment
2
Install required libraries
3
Set environment variables
4
Start PostgreSQL database
5
Run the agent
Documentation Index
Fetch the complete documentation index at: /llms.txt
Use this file to discover all available pages before exploring further.
Store agent conversation history in PostgreSQL and limit how many past runs are added to the context with num_history_runs.
"""
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,
)
agent.print_response("Tell me a new interesting fact about space")
Set up your virtual environment
uv venv --python 3.12
source .venv/bin/activate
uv venv --python 3.12
.venv\Scripts\activate
Install required libraries
uv pip install -U agno openai sqlalchemy "psycopg[binary]"
Set environment variables
export OPENAI_API_KEY=****
Start PostgreSQL database
./cookbook/scripts/run_pgvector.sh
Run the agent
python persistent_session_history.py
Was this page helpful?