Agent State
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 asession_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 thedescription
andinstructions
. - The
session_state
is stored with Agent sessions and is persisted in a database. Meaning, it is available across execution cycles.
Here’s an example of an Agent managing a shopping list:
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.
We love how elegantly we can maintain and pass on state 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.
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.