Skip to main content
Your Agents often need to access certain data during a run/session. It could be a todo list, the user’s profile, or anything else. When this data needs to remain accessible across runs, or needs to be updated during the session, you want to consider it session state. Session state is accessible from tool calls, pre-hooks and post-hooks, and other functions that are part of the Agent run. You are also able to use it in the system message, to ultimately present it to the Model. Session state is also persisted in the database, if one is available to the Agent, and is automatically loaded when the session is continued.
Understanding Agent “Statelessness”: Agents in Agno don’t maintain working state directly on the Agent object in memory. Instead they provide state management capabilities:
  • The session.get_session_state(session_id=session_id) method retrieves the session state of a particular session from the database
  • The session_state parameter on Agent provides the default state data for new sessions
  • Working state is managed per run and persisted to the database per session
  • The agent instance (or attributes thereof) itself is not modified during runs

State Management

Now that we understand what session state is, let’s see how it works:
  • You can set the Agent’s session_state parameter with a dictionary of default state variables. This will be the initial state.
  • You can pass session_state to agent.run(). This will take precedence over the Agent’s default state for that run.
  • You can access the session state in tool calls and other functions, via run_context.session_state.
  • The session_state will be stored in your database. Subsequent runs within the same session will load the state from the database. See the guide for more information.
  • You can use any data in your session_state in the system message, by referencing it in the description and instructions parameters. See the guide for more information.
  • You can have your Agent automatically update the session state by setting the enable_agentic_state parameter to True. See the guide for more information.
Here’s an example where an Agent is managing a shopping list:
session_state.py
from agno.agent import Agent
from agno.db.sqlite import SqliteDb
from agno.models.openai import OpenAIChat
from agno.run import RunContext

# Define a tool that adds an item to the shopping list
def add_item(run_context: RunContext, item: str) -> str:
    """Add an item to the shopping list."""

    # We access the session state via run_context.session_state
    run_context.session_state["shopping_list"].append(item)

    return f"The shopping list is now {run_context.session_state['shopping_list']}"


# Create an Agent that maintains state
agent = Agent(
    model=OpenAIChat(id="gpt-5-mini"),
    # Database to store sessions and their state
    db=SqliteDb(db_file="tmp/agents.db"),
    # Initialize the session state with an empty shopping list. This will be the default state for all sessions.
    session_state={"shopping_list": []},
    tools=[add_item],
    # You can use variables from the session state in the instructions
    instructions="Current state (shopping list) is: {shopping_list}",
    markdown=True,
)

# Example usage
agent.print_response("Add milk, eggs, and bread to the shopping list", stream=True)
print(f"Final session state: {agent.get_session_state()}")
The RunContext object is automatically passed to the tool as an argument. Any updates to run_context.session_state will automatically be persisted in the database and reflected in the session state. See the RunContext schema for more information.
Session state is also shared between members of a team when using Team. See Teams for more information.

Maintaining state across multiple runs

A big advantage of sessions is the ability to maintain state across multiple runs within the same session. For example, let’s say the agent is helping a user keep track of their shopping list.
You have to configure your storage via the db parameter for state to be persisted across runs. See Storage for more information.
shopping_list.py
from textwrap import dedent

from agno.agent import Agent
from agno.db.sqlite import SqliteDb
from agno.models.openai import OpenAIChat
from agno.run import RunContext


# Define tools to manage our shopping list
def add_item(run_context: RunContext, item: str) -> str:
    """Add an item to the shopping list and return confirmation."""
    # Add the item if it's not already in the list
    if item.lower() not in [i.lower() for i in run_context.session_state["shopping_list"]]:
        run_context.session_state["shopping_list"].append(item)  # type: ignore
        return f"Added '{item}' to the shopping list"
    else:
        return f"'{item}' is already in the shopping list"


def remove_item(run_context: RunContext, item: str) -> str:
    """Remove an item from the shopping list by name."""
    # Case-insensitive search
    for i, list_item in enumerate(run_context.session_state["shopping_list"]):
        if list_item.lower() == item.lower():
            run_context.session_state["shopping_list"].pop(i)
            return f"Removed '{list_item}' from the shopping list"

    return f"'{item}' was not found in the shopping list"


def list_items(run_context: RunContext) -> str:
    """List all items in the shopping list."""
    shopping_list = run_context.session_state["shopping_list"]

    if not shopping_list:
        return "The shopping list is empty."

    items_text = "\n".join([f"- {item}" for item in shopping_list])
    return f"Current shopping list:\n{items_text}"


# Create a Shopping List Manager Agent that maintains state
agent = Agent(
    model=OpenAIChat(id="gpt-5-mini"),
    # Initialize the session state with an empty shopping list (default session state for all sessions)
    session_state={"shopping_list": []},
    db=SqliteDb(db_file="tmp/example.db"),
    tools=[add_item, remove_item, list_items],
    # You can use variables from the session state in the instructions
    instructions=dedent("""\
        Your job is to manage a shopping list.

        The shopping list starts empty. You can add items, remove items by name, and list all items.

        Current shopping list: {shopping_list}
    """),
    markdown=True,
)

# Example usage
agent.print_response("Add milk, eggs, and bread to the shopping list", stream=True)
print(f"Session state: {agent.get_session_state()}")

agent.print_response("I got bread", stream=True)
print(f"Session state: {agent.get_session_state()}")

agent.print_response("I need apples and oranges", stream=True)
print(f"Session state: {agent.get_session_state()}")

agent.print_response("whats on my list?", stream=True)
print(f"Session state: {agent.get_session_state()}")

agent.print_response(
    "Clear everything from my list and start over with just bananas and yogurt",
    stream=True,
)
print(f"Session state: {agent.get_session_state()}")

Agentic Session State

Agno provides a way to allow the Agent to automatically update the session state. Simply set the enable_agentic_state parameter to True.
agentic_session_state.py
from agno.agent import Agent
from agno.models.openai import OpenAIChat
from agno.db.sqlite import SqliteDb

agent = Agent(
    db=SqliteDb(db_file="tmp/agents.db"),
    model=OpenAIChat(id="gpt-5-mini"),
    session_state={"shopping_list": []},
    add_session_state_to_context=True,  # Required so the agent is aware of the session state
    enable_agentic_state=True,  # Adds a tool to manage the session state
)

agent.print_response("Add milk, eggs, and bread to the shopping list", stream=True)
print(f"Session state: {agent.get_session_state()}")
Don’t forget to set add_session_state_to_context=True to make the session state available to the agent’s context.

Using state in instructions

You can reference variables from the session state in your instructions.
Don’t use the f-string syntax in the instructions. Directly use the {key} syntax, Agno substitutes the values for you.
state_in_instructions.py
from textwrap import dedent

from agno.agent import Agent
from agno.models.openai import OpenAIChat
from agno.db.sqlite import SqliteDb


agent = Agent(
    db=SqliteDb(db_file="tmp/agents.db"),
    model=OpenAIChat(id="gpt-5-mini"),
    # Initialize the session state with a variable
    session_state={"user_name": "John"},
    # You can use variables from the session state in the instructions
    instructions="Users name is {user_name}",
    markdown=True,
)

agent.print_response("What is my name?", stream=True)

Changing state on run

When you pass session_id to the agent on agent.run(), the run will be part of the session with the given session_id. The state loaded from the database will be the state for that session. This is useful when you want to continue a session for a specific user.
changing_state_on_run.py
from agno.agent import Agent
from agno.models.openai import OpenAIChat
from agno.db.sqlite import SqliteDb

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

# 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")

Overwriting the state in the db

By default, if you pass session_state to the run methods, this new state will be merged with the session_state in the db. You can change that behavior if you want to overwrite the session_state in the db:
overwriting_session_state_in_db.py
from agno.agent import Agent
from agno.db.sqlite import SqliteDb
from agno.models.openai import OpenAIChat

# Create an Agent that maintains state
agent = Agent(
    model=OpenAIChat(id="gpt-4o-mini"),
    db=SqliteDb(db_file="tmp/agents.db"),
    markdown=True,
    # Set the default session_state. The values set here won't be overwritten - they are the initial state for all sessions.
    session_state={},
    # Adding the session_state to context for the agent to easily access it
    add_session_state_to_context=True,
    # Allow overwriting the stored session state with the session state provided in the run
    overwrite_db_session_state=True,
)

# Let's run the agent providing a session_state. This session_state will be stored in the database.
agent.print_response(
    "Can you tell me what's in your session_state?",
    session_state={"shopping_list": ["Potatoes"]},
    stream=True,
)
print(f"Stored session state: {agent.get_session_state()}")

# Now if we pass a new session_state, it will overwrite the stored session_state.
agent.print_response(
    "Can you tell me what is in your session_state?",
    session_state={"secret_number": 43},
    stream=True,
)
print(f"Stored session state: {agent.get_session_state()}")

Developer Resources