Customize the lifespan context manager of the AgentOS. This allows you to run code before and after the AgentOS is started and stopped. For example, you can use this to:
  • Connect to a database
  • Log information
  • Setup a monitoring system

Code

cookbook/agent_os/custom_lifespan.py

from contextlib import asynccontextmanager

from agno.agent import Agent
from agno.db.postgres import PostgresDb
from agno.models.anthropic import Claude
from agno.os import AgentOS
from agno.utils.log import log_info

# Setup the database
db = PostgresDb(db_url="postgresql+psycopg://ai:ai@localhost:5532/ai")

# Setup basic agents, teams and workflows
agno_support_agent = Agent(
    id="example-agent",
    name="Example Agent",
    model=Claude(id="claude-sonnet-4-0"),
    db=db,
    markdown=True,
)


@asynccontextmanager
async def lifespan(app):
    log_info("Starting My FastAPI App")
    yield
    log_info("Stopping My FastAPI App")


agent_os = AgentOS(
    description="Example app with custom lifespan",
    agents=[agno_support_agent],
    lifespan=lifespan,
)


app = agent_os.get_app()

if __name__ == "__main__":
    """Run your AgentOS.

    You can see test your AgentOS at:
    http://localhost:7777/docs

    """
    # Don't use reload=True here, this can cause issues with the lifespan
    agent_os.serve(app="custom_lifespan:app")

Usage

1

Create a virtual environment

Open the Terminal and create a python virtual environment.
python3 -m venv .venv
source .venv/bin/activate
2

Set Environment Variables

export ANTHROPIC_API_KEY=your_anthropic_api_key
export DATABASE_URL=postgresql+psycopg://ai:ai@localhost:5532/ai  # Optional
3

Install libraries

pip install -U agno anthropic fastapi["standard"] uvicorn sqlalchemy pgvector psycopg
4

Setup PostgreSQL Database

# Using Docker
docker run -d \
  --name agno-postgres \
  -e POSTGRES_DB=ai \
  -e POSTGRES_USER=ai \
  -e POSTGRES_PASSWORD=ai \
  -p 5532:5432 \
  pgvector/pgvector:pg17
5

Run Example with FastAPI CLI

fastapi run cookbook/agent_os/custom_lifespan.py
6

Run Example with Python

python cookbook/agent_os/custom_lifespan.py