Custom Lifespan

Customize the lifespan of your AgentOS app to handle startup and shutdown logic.

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:

1@asynccontextmanager
2async def lifespan(app):
3 # This will run before your app starts
4 log_info("Starting My FastAPI App")
5
6 yield
7
8 # This will run before your app shuts down
9 log_info("Stopping My FastAPI App")

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.

Tip

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

Code

1from contextlib import asynccontextmanager
2
3from kern.agent import Agent
4from kern.db.postgres import PostgresDb
5from kern.models.anthropic import Claude
6from kern.os import AgentOS
7from kern.utils.log import log_info
8
9# Setup the database
10db = PostgresDb(db_url="postgresql+psycopg://ai:ai@localhost:5532/ai")
11
12# Setup basic agents, teams and workflows
13agno_support_agent = Agent(
14 id="example-agent",
15 name="Example Agent",
16 model=Claude(id="claude-sonnet-4-0"),
17 db=db,
18 markdown=True,
19)
20
21
22@asynccontextmanager
23async def lifespan(app):
24 log_info("Starting My FastAPI App")
25 yield
26 log_info("Stopping My FastAPI App")
27
28
29agent_os = AgentOS(
30 description="Example app with custom lifespan",
31 agents=[agno_support_agent],
32 lifespan=lifespan,
33)
34
35
36app = agent_os.get_app()
37
38if __name__ == "__main__":
39 """Run your AgentOS.
40
41 You can see test your AgentOS at:
42 http://localhost:7777/docs
43
44 """
45 agent_os.serve(app="custom_lifespan:app")

Set up your virtual environment

1uv venv --python 3.12
2source .venv/bin/activate
1uv venv --python 3.12
2.venv\Scripts\activate

Set Environment Variables

1export ANTHROPIC_API_KEY=your_anthropic_api_key

Install dependencies

1uv pip install -U kern-ai anthropic "fastapi[standard]" uvicorn sqlalchemy

Setup PostgreSQL Database

1# Using Docker
2docker run -d \
3 --name kern-postgres \
4 -e POSTGRES_DB=ai \
5 -e POSTGRES_USER=ai \
6 -e POSTGRES_PASSWORD=ai \
7 -p 5532:5432 \
8 pgvector/pgvector:pg17

Run Example with Python

1fastapi run custom_lifespan.py
1python custom_lifespan.py
1python ovecustom_lifespanrride_routes.py