State
GraphAI provides a state management system that allows data to persist across node executions. This state is essential for maintaining context throughout the execution of a graph.
State Basics
The graph state is a dictionary that:
- Is initialized when the graph is created
- Persists throughout the execution of the graph
- Can be accessed by nodes during execution
- Can be modified and updated as the graph executes
Initializing State
You can initialize the graph state when creating a Graph:
If no initial state is provided, an empty dictionary is used.
Accessing State Methods
The Graph class provides several methods for working with state:
Accessing State in Nodes
Nodes can access the graph state by including a state
parameter in their function signature:
The state is passed automatically to any node that includes a state
parameter.
Modifying State
There are two ways to modify the graph state:
1. Return State Changes in Node Output
The most common way to modify state is to include state changes in the node’s return value:
When the node returns, any keys in the return dictionary are merged with the current state.
2. Directly Update Graph State
For more complex workflows, you can use graph methods directly:
This approach is less common but provides more flexibility for complex state manipulations.
State Persistence
The state persists for the lifetime of the graph object. If you need to persist state between graph executions:
State Scoping
State is scoped to the graph instance. If you create multiple graph instances, each will have its own independent state:
State vs. Input
It’s important to understand the difference between state and input:
- Input: Data passed to the current node execution
- State: Persistent data that’s available across multiple node executions
For example:
Best Practices
- Keep state serializable: Only store data that can be easily serialized (e.g., dicts, lists, strings, numbers)
- Be selective: Only use state for data that truly needs to persist across nodes
- Document state structure: Create a clear structure for your state and document it
- Consider state size: Don’t let your state grow unbounded, especially for long-running applications