Skip to main content
You will often want to run code before your AgentOS app starts or before it shuts down. This can be done by providing a custom lifespan function via the 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.
See the FastAPI documentation for more information about the lifespan context manager.
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

Set up your virtual environment

3

Set Environment Variables

4

Install dependencies

5

Setup PostgreSQL Database

6

Run Example with Python