State Schemas
TypedDict State
The most common approach is using TypedDict:Pydantic Models
For validation and complex data structures, use Pydantic:State Reducers
Reducers define how state updates are merged with existing state.Built-in Reducers
add_messages
For message-based workflows:add_messages reducer:
- Appends new messages to the list
- Updates messages with matching IDs
- Supports message deletion with
RemoveMessage
Operator Reducers
Use operators for simple reductions:Custom Reducers
Define custom reducer functions:Updating State
Returning Updates
Nodes return dictionaries with state updates:Multiple Updates
Return multiple state fields:Conditional Updates
Update state conditionally based on logic:State Channels
LangGraph uses channels internally to manage state.Channel Types
- LastValue: Stores the most recent value (default)
- BinaryOperatorAggregate: Applies a binary operator (e.g.,
add) - Topic: For pub/sub patterns
Ephemeral State
Some state doesn’t need persistence:Input and Output Schemas
Define separate schemas for input and output:- Input: Only accepts
question - Output: Only returns
answer - Internal: Full state available to nodes
Context Schema
Use context for runtime configuration:State Inspection
Inspect state during execution:Advanced Patterns
Managed Values
LangGraph provides managed values that are automatically handled:IsLastStep: Boolean indicating if this is the last stepRemainingSteps: Number of remaining steps
Dynamic Send
Send dynamic updates to specific nodes:Command Pattern
UseCommand for advanced control flow:
Best Practices
- Keep state flat: Avoid deeply nested structures
- Use type hints: Enable better IDE support and validation
- Choose the right reducer: Match the reducer to your data merging needs
- Separate concerns: Use input/output schemas for clean APIs
- Document state fields: Add docstrings to state classes
- Validate state: Use Pydantic for runtime validation when needed
Next Steps
- Learn about Persistence to save state across executions
- Explore Memory for long-term state storage
- Add Interrupts to modify state during execution