When to Use State
Use state when:- Multiple agents need access to the same data
- You’re tracking workflow progress
- You need to accumulate results across agents
- Prop drilling becomes cumbersome
- Simple data passing between adjacent agents (use outputs instead)
- Data that only one agent needs
- Temporary calculations
Basic State
Define Schema
Read State
Write State
State Patterns
Pattern 1: Accumulator
Build up results across agents:Pattern 2: Configuration State
Share configuration across agents:Pattern 3: Error Tracking
Track errors across the workflow:Pattern 4: Multi-Step Context
Build context across multiple AI calls:State vs Outputs
Use Outputs For
Simple data passing between adjacent agents:Use State For
Data needed by multiple non-adjacent agents:State Persistence
KV-Backed State
Persist state across executions:D1-Backed State
For complex queries and relationships:State Scoping
Ensemble-Level State
Shared across all agents in the ensemble:Agent-Level State
Each agent has its own state (for custom agents):Best Practices
- Minimize State Usage - Use outputs for simple data passing
- Clear Schema - Define types explicitly
- Declare Dependencies - Always use
use:andset: - Persist When Needed - Use KV/D1 for long-running workflows
- Avoid Circular Dependencies - Don’t create state loops
- Initialize State - Provide defaults (
|| 0,|| []) - Test State Logic - Unit test state transformations
- Monitor State Size - Keep state compact
Performance Considerations
State Access Cost
Reading state is fast (in-memory):State Write Cost
Writing to persistent backends has latency:Debugging State
Log State Changes
Output State
Include state in ensemble output for debugging:Next Steps
Flow Control
Control execution flow
A/B Testing
Test multiple variants
Operations
Learn about operations
Playbooks
Real-world examples

