Skip to main content
This example demonstrates how to use session state with PostgreSQL database and manage user context across different sessions. It shows how session state persists and can be retrieved for different users and sessions.

Code

session_state_in_context.py
from agno.agent import Agent
from agno.db.postgres import PostgresDb
from agno.models.openai import OpenAIChat

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

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


agent = Agent(
    model=OpenAIChat(id="gpt-5-mini"),
    instructions="Users name is {user_name} and age is {age}",
    db=db,
)

# Sets the session state for the session with the id "user_1_session_1"
agent.print_response(
    "What is my name?",
    session_id="user_1_session_1",
    user_id="user_1",
    session_state={"user_name": "John", "age": 30},
)

# Will load the session state from the session with the id "user_1_session_1"
agent.print_response("How old am I?", session_id="user_1_session_1", user_id="user_1")

# Sets the session state for the session with the id "user_2_session_1"
agent.print_response(
    "What is my name?",
    session_id="user_2_session_1",
    user_id="user_2",
    session_state={"user_name": "Jane", "age": 25},
)

# Will load the session state from the session with the id "user_2_session_1"
agent.print_response("How old am I?", session_id="user_2_session_1", user_id="user_2")

Usage

1

Create a virtual environment

Open the Terminal and create a python virtual environment.
python3 -m venv .venv
source .venv/bin/activate
2

Install libraries

pip install -U agno openai psycopg
3

Setup PostgreSQL

# Make sure PostgreSQL is running
# Update connection string in the code as needed
4

Export your OpenAI API key

  export OPENAI_API_KEY="your_openai_api_key_here"
5

Create a Python file

Create a Python file and add the above code.
touch session_state_in_context.py
6

Run Agent

python session_state_in_context.py
7

Find All Cookbooks

Explore all the available cookbooks in the Agno repository. Click the link below to view the code on GitHub:Agno Cookbooks on GitHub
I