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: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 astate
parameter in their function signature:
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:2. Directly Update Graph State
For more complex workflows, you can use graph methods directly: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
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