Bring Your Own FastAPI App
Integrate your own FastAPI app with AgentOS.
AgentOS is built on FastAPI, which means you can easily integrate your existing FastAPI applications or add custom routes and routers to extend your agent's capabilities.
Quick Start
The simplest way to bring your own FastAPI app is to pass it to the AgentOS constructor:
1from fastapi import FastAPI2from kern.agent import Agent3from kern.models.openai import OpenAIResponses4from kern.os import AgentOS56# Create your custom FastAPI app7app = FastAPI(title="My Custom App")89# Add your custom routes10@app.get("/status")11async def status_check():12 return {"status": "healthy"}1314# Pass your app to AgentOS15agent_os = AgentOS(16 agents=[Agent(id="basic-agent", model=OpenAIResponses(id="gpt-5.2"))],17 base_app=app # Your custom FastAPI app18)1920# Get the combined app with both AgentOS and your routes21app = agent_os.get_app()Your custom FastAPI app can have its own middleware and dependencies.
If you have your own CORS middleware, it will be updated to include the AgentOS allowed origins, to make the AgentOS instance compatible with the Control Plane. Otherwise, the appropriate CORS middleware will be added to the app.
Adding Middleware
You can add any FastAPI middleware to your custom FastAPI app and it will be respected by AgentOS.
Kern also provides some built-in middleware for common use cases, including authentication.
See the Middleware page for more details.
Running with FastAPI CLI
AgentOS applications are compatible with the FastAPI CLI for development.
First, install the FastAPI CLI:
1uv pip install "fastapi[standard]"Then run the app:
1fastapi run your_app.py1fastapi run your_app.py --reload1fastapi run your_app.py --host 0.0.0.0 --port 8000Running in Production
For production deployments, you can use any ASGI server:
1uvicorn main:app --host 0.0.0.0 --port 8000 --workers 41gunicorn main:app -w 4 -k uvicorn.workers.UvicornWorker --bind 0.0.0.0:80001fastapi run main.py --host 0.0.0.0 --port 8000Adding Custom Routers
For better organization, use FastAPI routers to group related endpoints:
1from kern.agent import Agent2from kern.db.sqlite import SqliteDb3from kern.models.anthropic import Claude4from kern.os import AgentOS5from kern.tools.hackernews import HackerNewsTools6from fastapi import FastAPI78# Set up the database9db = SqliteDb(db_file="tmp/agentos.db")1011# Set up the agent12web_research_agent = Agent(13 name="Basic 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# Create custom FastAPI app24app: FastAPI = FastAPI(25 title="Custom FastAPI App",26 version="1.0.0",27)2829# Add your own routes30@app.post("/customers")31async def get_customers():32 return [33 {34 "id": 1,35 "name": "John Doe",36 "email": "john.doe@example.com",37 },38 {39 "id": 2,40 "name": "Jane Doe",41 "email": "jane.doe@example.com",42 },43 ]444546# Set up the AgentOS app by passing your FastAPI app47agent_os = AgentOS(48 description="Example app with custom routers",49 agents=[web_research_agent],50 base_app=app,51)5253# Alternatively, add all routes from AgentOS app to the current app54# for route in agent_os.get_routes():55# app.router.routes.append(route)5657app = agent_os.get_app()585960if __name__ == "__main__":61 """Run the AgentOS application.6263 You can see the docs at:64 http://localhost:7777/docs6566 """67 agent_os.serve(app="custom_fastapi_app:app", reload=True)Middleware and Dependencies
You can add middleware and dependencies to your custom FastAPI app:
1from fastapi import FastAPI, Depends, HTTPException2from fastapi.middleware.cors import CORSMiddleware3from fastapi.security import HTTPBearer45app = FastAPI()67# Add CORS middleware8app.add_middleware(9 CORSMiddleware,10 allow_origins=["https://yourdomain.com"],11 allow_credentials=True,12 allow_methods=["*"],13 allow_headers=["*"],14)1516# Security dependency17security = HTTPBearer()1819async def verify_token(token: str = Depends(security)):20 if token.credentials != "your-secret-token":21 raise HTTPException(status_code=401, detail="Invalid token")22 return token2324# Protected route25@app.get("/protected", dependencies=[Depends(verify_token)])26async def protected_endpoint():27 return {"message": "Access granted"}2829# Integrate with AgentOS30agent_os = AgentOS(31 agents=[Agent(id="basic-agent", model=OpenAIResponses(id="gpt-5.2"))],32 base_app=app33)3435app = agent_os.get_app()Access AgentOS Routes
You can programmatically access and inspect the routes added by AgentOS:
1agent_os = AgentOS(agents=[agent])2app = agent_os.get_app()34# Get all routes5routes = agent_os.get_routes()67for route in routes:8 print(f"Route: {route.path}")9 if hasattr(route, 'methods'):10 print(f"Methods: {route.methods}")