update_from_lifespan.py
"""
Update From Lifespan
====================
Demonstrates update from lifespan.
"""
from contextlib import asynccontextmanager
from agno.agent.agent import Agent
from agno.db.postgres.postgres import PostgresDb
from agno.os import AgentOS
from agno.tools.mcp import MCPTools
# ---------------------------------------------------------------------------
# Create Example
# ---------------------------------------------------------------------------
db = PostgresDb(id="basic-db", db_url="postgresql+psycopg://ai:ai@localhost:5532/ai")
# First agent. We will add this to the AgentOS on initialization.
agent1 = Agent(
name="First Agent",
markdown=True,
)
# Second agent. We will add this to the AgentOS in the lifespan function.
agent2 = Agent(
id="second-agent",
name="Second Agent",
tools=[MCPTools(transport="streamable-http", url="https://docs.agno.com/mcp")],
markdown=True,
db=db,
)
# Lifespan function receiving the AgentOS instance as parameter.
@asynccontextmanager
async def lifespan(app, agent_os):
# Add the new Agent
agent_os.agents.append(agent2)
# Resync the AgentOS
agent_os.resync(app=app)
yield
# Setup our AgentOS with the lifespan function and the first agent.
agent_os = AgentOS(
lifespan=lifespan,
agents=[agent1],
mcp_server=True,
)
# Get our app.
app = agent_os.get_app()
# Serve the app.
# ---------------------------------------------------------------------------
# Run Example
# ---------------------------------------------------------------------------
if __name__ == "__main__":
agent_os.serve(app="update_from_lifespan:app", reload=True)
Run the Example
1
Set up your virtual environment
uv venv --python 3.12
source .venv/bin/activate
uv venv --python 3.12
.venv\Scripts\activate
2
Install dependencies
uv pip install -U "agno[mcp,os]" "psycopg[binary]" openai
3
Export your OpenAI API key
export OPENAI_API_KEY="your_openai_api_key_here"
$Env:OPENAI_API_KEY="your_openai_api_key_here"
4
Run PgVector
docker run -d \
-e POSTGRES_DB=ai \
-e POSTGRES_USER=ai \
-e POSTGRES_PASSWORD=ai \
-e PGDATA=/var/lib/postgresql \
-v pgvolume:/var/lib/postgresql \
-p 5532:5432 \
--name pgvector \
agnohq/pgvector:18
docker run -d `
-e POSTGRES_DB=ai `
-e POSTGRES_USER=ai `
-e POSTGRES_PASSWORD=ai `
-e PGDATA=/var/lib/postgresql `
-v pgvolume:/var/lib/postgresql `
-p 5532:5432 `
--name pgvector `
agnohq/pgvector:18
5
Run the example
Save the code above as
update_from_lifespan.py, then run:python update_from_lifespan.py