Skip to main content
State is any kind of data the Agent needs to maintain throughout runs.
A simple yet common use case for Agents is to manage lists, items and other “information” for a user. For example, a shopping list, a todo list, a wishlist, etc.This can be easily managed using the session_state. The Agent updates the session_state in tool calls and exposes them to the Model in the description and instructions.
Agno’s provides a powerful and elegant state management system, here’s how it works:
  • The Agent has a session_state parameter.
  • We add our state variables to this session_state dictionary.
  • We update the session_state dictionary in tool calls or other functions.
  • We share the current session_state with the Model in the description and instructions.
  • The session_state is stored with Agent sessions and is persisted in a database. Meaning, it is available across execution cycles. This also means when switching sessions between calls to agent.run(), the state is loaded and available.
  • You can also pass session_state to the agent on agent.run(), effectively overriding any state that was set on Agent initialization.
Here’s an example of an Agent managing a shopping list:
session_state.py
This is as good and elegant as state management gets.

Maintaining state across multiple runs

A big advantage of sessions is the ability to maintain state across multiple runs. For example, let’s say the agent is helping a user keep track of their shopping list.
By setting add_state_in_messages=True, the keys of the session_state dictionary are available in the description and instructions as variables.Use this pattern to add the shopping_list to the instructions directly.
shopping_list.py
State is a great way to control context across multiple runs.

Using state in instructions

You can use variables from the session state in the instructions by setting add_state_in_messages=True.
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

Changing state on run

When you pass session_id to the agent on agent.run(), it will switch to the session with the given session_id and load any state that was set on that session. This is useful when you want to continue a session for a specific user.
changing_state_on_run.py

Persisting state in database

session_state is part of the Agent session and is saved to the database after each run if a storage driver is provided. Here’s an example of an Agent that maintains a shopping list and persists the state in a database. Run this script multiple times to see the state being persisted.
session_state_storage.py