Persistent Session

Demonstrates persistent team sessions with optional history injection.

persistent_session.py
"""
Persistent Session
==================

Demonstrates persistent team sessions with optional history injection.
"""

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

# ---------------------------------------------------------------------------
# Setup
# ---------------------------------------------------------------------------
db_url = "postgresql+psycopg://ai:ai@localhost:5532/ai"
db = PostgresDb(db_url=db_url, session_table="sessions")

# ---------------------------------------------------------------------------
# Create Members
# ---------------------------------------------------------------------------
agent = Agent(model=OpenAIResponses(id="gpt-5-mini"))

# ---------------------------------------------------------------------------
# Create Team
# ---------------------------------------------------------------------------
basic_team = Team(
    model=OpenAIResponses(id="gpt-5-mini"),
    members=[agent],
    db=db,
)

history_team = Team(
    model=OpenAIResponses(id="gpt-5-mini"),
    members=[agent],
    db=db,
    add_history_to_context=True,
    num_history_runs=3,
)

# ---------------------------------------------------------------------------
# Run Team
# ---------------------------------------------------------------------------
if __name__ == "__main__":
    basic_team.print_response("Tell me a new interesting fact about space")

    history_team.print_response("Tell me a new interesting fact about space")
    history_team.print_response("Tell me a new interesting fact about oceans")
    history_team.print_response("What have we been talking about?")

Reuse the session after restarting

Postgres persists both teams' runs. Repeated calls without a session ID reuse the ID generated for that Team instance, but constructing a new instance generates another ID. To resume the same conversation after restarting, pass a stable session_id to each call or set it on the team. basic_team stores its run without injecting history; history_team includes up to three previous runs.

Run the Example

Set up your virtual environment

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

Install dependencies

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

Export your OpenAI API key

export OPENAI_API_KEY="your_openai_api_key_here"

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 example

Save the code above as persistent_session.py, then run:

python persistent_session.py

Full source: cookbook/03_teams/07_session/persistent_session.py