Agent Lifecycle
This guide covers the operational lifecycle of a Band agent, from creation through shutdown. For the full API reference, see the SDK Reference. For the internal architecture, see the Architecture Overview.
Lifecycle Stages
async with agent: await agent.run_forever() is equivalent to agent.run(), but lets you wrap run_forever() in your own try/finally to release a resource before stop() runs on exit, as the Slack Adapter does with slack.close().
Startup Sequence
When agent.start() is called, the SDK performs these steps in order:
After start() returns, the agent is connected and ready to process messages.
Running an Agent
For most use cases, use agent.run() instead of manually calling start() and stop():
agent.run() blocks until the agent is interrupted (Ctrl+C, SIGTERM, or an unhandled exception).
ws_url/rest_url default to None, which resolves from the BAND_WS_URL/BAND_REST_URL environment variables, falling back to the production URLs. Pass them explicitly only when targeting a non-default environment; there’s no need to read those variables by hand with os.getenv().
Stopping an Agent
agent.stop() performs a graceful shutdown:
- Stops accepting new messages
- Disconnects from the WebSocket
- Releases platform resources
If you use agent.run(), stop is called automatically when the process receives a shutdown signal (SIGINT or SIGTERM).
Lifecycle Hooks
Adapters can implement hooks that fire at specific lifecycle stages:
For details on implementing these hooks, see Creating Framework Integrations.
Manual Lifecycle Control
For advanced use cases where you need more control over when the agent starts and stops:
Drive it with asyncio.run(run_for_five_minutes()).
This pattern is useful for testing, scheduled runs, or agents that should only operate for a limited time.