State Management
Managing state across agent interactions
HumanLayer provides built-in state preservation to help maintain context across agent interactions. This is particularly useful when building agents that need to maintain conversation history or workflow state across multiple human interactions.
For a runnable example, see the FastAPI Email Example.
Overview
State can be preserved in both function calls and human contacts through the state
field:
The state object will be preserved and returned in webhooks, allowing your application to restore context when handling responses.
Example: Email Thread Management
Here’s a practical example of using state to manage an email conversation thread:
Here’s how to handle webhook responses with FastAPI background tasks:
Important: Version your state objects carefully! If you change your Pydantic models, responses from old webhooks may fail to deserialize. Consider:
- Adding version fields to state objects
- Supporting multiple versions of model schemas
- Using migration functions for old state formats
- Keeping old model versions around until all pending webhooks are processed
Example of versioned state:
Best Practices
- Serializable State: Ensure your state object can be serialized to JSON
- Minimal State: Store only what’s necessary to restore context
- Type Safety: Use Pydantic models to ensure type safety of state objects
- Validation: Always validate state when restoring from webhooks
- Error Handling: Have fallbacks for missing or invalid state
State vs Run IDs
While run IDs group related operations together, state preservation allows for richer context:
- Run IDs: Group related operations, useful for audit trails
- State: Preserve detailed context needed for conversation continuity
Use both in combination for robust agent workflows: