AgentOS Custom FastAPI
AgentOS where you provide your own FastAPI app
Here is a full example of an AgentOS where you provide your own FastAPI app.
Code
1from kern.agent import Agent2from kern.db.postgres import PostgresDb3from kern.models.anthropic import Claude4from kern.os import AgentOS5from kern.tools.hackernews import HackerNewsTools6from fastapi import FastAPI78# Setup the database9db = PostgresDb(db_url="postgresql+psycopg://ai:ai@localhost:5532/ai")1011web_research_agent = Agent(12 id="web-research-agent",13 name="Web Research Agent",14 model=Claude(id="claude-sonnet-4-0"),15 db=db,16 tools=[HackerNewsTools()],17 add_history_to_context=True,18 num_history_runs=3,19 add_datetime_to_context=True,20 markdown=True,21)2223# Custom FastAPI app24app: FastAPI = FastAPI(25 title="Custom FastAPI App",26 version="1.0.0",27)282930# Add your own routes31@app.post("/customers")32async def get_customers():33 return [34 {35 "id": 1,36 "name": "John Doe",37 "email": "john.doe@example.com",38 },39 {40 "id": 2,41 "name": "Jane Doe",42 "email": "jane.doe@example.com",43 },44 ]454647# Setup our AgentOS app by passing your FastAPI app48# Use route_prefix to avoid conflicts with your custom routes49agent_os = AgentOS(50 description="Example app with custom routers",51 agents=[web_research_agent],52 base_app=app,53)5455# Alternatively, add all routes from AgentOS app to the current app56# for route in agent_os.get_routes():57# app.router.routes.append(route)5859app = agent_os.get_app()606162if __name__ == "__main__":63 """Run your AgentOS.6465 With this setup:66 - API docs: http://localhost:7777/docs6768 """69 agent_os.serve(app="custom_fastapi:app", reload=True)Usage
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 uvicorn sqlalchemy pgvector psycopgSetup 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
1python custom_fastapi.py