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.- The
Agenthas asession_stateparameter. - We add our state variables to this
session_statedictionary. - We update the
session_statedictionary in tool calls or other functions. - We share the current
session_statewith the Model in thedescriptionandinstructions. - The
session_stateis 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 toagent.run(), the state is loaded and available. - You can also pass
session_stateto the agent onagent.run(), effectively overriding any state that was set on Agent initialization.
session_state.py
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
Using state in instructions
You can use variables from the session state in the instructions by settingadd_state_in_messages=True.
state_in_instructions.py
Changing state on run
When you passsession_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