Agent States
Every MoFA agent goes through a defined lifecycle with the following states:State Transitions
Core Lifecycle Methods
TheMoFAAgent trait defines the core lifecycle interface.
Method Signatures
initialize
Prepare the agent for execution. Called once before the agent can process tasks.- Load configuration files
- Establish database/network connections
- Initialize ML models
- Allocate resources
- Validate prerequisites
execute
The main task execution method. Processes input and returns output.- Always update state to
Executingat start - Check for interrupts periodically for long-running tasks
- Emit events to report progress
- Return state to
Readyon success - Handle errors gracefully
shutdown
Gracefully terminate the agent and release resources.- Save state/checkpoints
- Close database connections
- Flush buffers
- Release memory
- Clean up temporary files
interrupt
Handle interrupt signals during execution.Acknowledged: Interrupt accepted, execution stoppedDeferred: Will stop after current stepIgnored: Agent cannot be interrupted
Extended Lifecycle (Optional)
TheAgentLifecycle trait provides additional control methods.
pause
Temporarily suspend execution while preserving state.Complete Lifecycle Example
Here’s a complete agent with full lifecycle management:Best Practices
Always transition states correctly
Always transition states correctly
Update
self.state at appropriate points to reflect the agent’s current status. This is crucial for monitoring and debugging.Handle errors in initialization
Handle errors in initialization
If initialization fails, set state to
Failed and return a descriptive error.Support interrupts for long-running tasks
Support interrupts for long-running tasks
Check for interrupts periodically and respond appropriately.
Graceful shutdown with cleanup
Graceful shutdown with cleanup
Always clean up resources in the shutdown method, even if errors occur.
Emit lifecycle events
Emit lifecycle events
Use the event bus to communicate state changes for monitoring.
Next Steps
Capabilities & State
Learn how to define and manage agent capabilities
API Reference
Explore the complete lifecycle API documentation