lifespan parameter.
This is how a lifespan function looks like:
FastAPI Lifespan
The custom lifespan function you provide will be used as the lifespan context manager for the FastAPI app used by your AgentOS. Remember to decorate it with@asynccontextmanager as shown in the examples.
If you are using a custom FastAPI app, you don’t need to worry about overwriting its lifespan.
The lifespan you provide will wrap the existing lifespan of the app, letting you combine all.
Common Use Cases
Lifespan control is useful to handle typical startup and shutdown tasks, such as:- Resource Initialization: databases, third party services, caches… or anything else needed by your app.
- Cleanup: Close connections, store data or release resources before shut down.
- Health Checks: Verify dependencies are available before serving requests
- Background Tasks: Start/stop background processes
Example
1
Code
custom_lifespan.py
2
Create a virtual environment
Open the
Terminal and create a python virtual environment.3
Set Environment Variables
4
Install libraries
5
Setup PostgreSQL Database
6
Run Example with Python