Leveraging shared state across tools and agents.
shared_state
is a centralized Python dictionary accessible by all tools and agents. It allows you to control execution flow, share data, and provide instructions to the agents based on certain conditions or actions performed by other agents.
Shared state is only available when tools are deployed together with agents (see Deployment to Production guide). If tools are deployed as separate APIs, they won’t share the same state, and you’ll need to implement your own state management solution.
Shared state is particularly useful when your agents interact with multiple tools that need to exchange information. Here’s why:
Tool A
collects data that Tool B
needs. The agent must explicitly pass this data as a parameter to Tool B
.Tool A
can store the required data in the shared state, and Tool B
can get it without needing direct parameter passing. This approach reduces complexity and minimizes the risk of errors.The two basic operations are:
shared_state.set('key', value)
shared_state.get('key')
You can use shared state in your tools and agents. Here’s how:
To set a value in the shared state within a tool, use the self._shared_state.set
inside your tool. For example, you can store the context retrieved from a database in the shared state:
To set a value in the shared state within a tool, use the self._shared_state.set
inside your tool. For example, you can store the context retrieved from a database in the shared state:
To get a value from the shared state within a tool, use self._shared_state.get
. Continuing the previous example, you can ensure that the Agent has called the QueryDatabase
tool before proceeding:
You can use the shared state within your agent’s response_validator
method to validate responses. For example, you can verify if the agent’s response matches content stored in the shared state: