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@asynccontextmanager2async def lifespan(app):3 # This will run before your app starts4 log_info("Starting My FastAPI App")56 yield78 # This will run before your app shuts down9 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.
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 asynccontextmanager23from kern.agent import Agent4from kern.db.postgres import PostgresDb5from kern.models.anthropic import Claude6from kern.os import AgentOS7from kern.utils.log import log_info89# Setup the database10db = PostgresDb(db_url="postgresql+psycopg://ai:ai@localhost:5532/ai")1112# Setup basic agents, teams and workflows13agno_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)202122@asynccontextmanager23async def lifespan(app):24 log_info("Starting My FastAPI App")25 yield26 log_info("Stopping My FastAPI App")272829agent_os = AgentOS(30 description="Example app with custom lifespan",31 agents=[agno_support_agent],32 lifespan=lifespan,33)343536app = agent_os.get_app()3738if __name__ == "__main__":39 """Run your AgentOS.4041 You can see test your AgentOS at:42 http://localhost:7777/docs4344 """45 agent_os.serve(app="custom_lifespan:app")Set up your virtual environment
1uv venv --python 3.122source .venv/bin/activate1uv venv --python 3.122.venv\Scripts\activateSet Environment Variables
1export ANTHROPIC_API_KEY=your_anthropic_api_keyInstall dependencies
1uv pip install -U kern-ai anthropic "fastapi[standard]" uvicorn sqlalchemySetup PostgreSQL Database
1# Using Docker2docker 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:pg17Run Example with Python
1fastapi run custom_lifespan.py1python custom_lifespan.py1python ovecustom_lifespanrride_routes.py