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 FastAPI
2from kern.agent import Agent
3from kern.models.openai import OpenAIResponses
4from kern.os import AgentOS
5
6# Create your custom FastAPI app
7app = FastAPI(title="My Custom App")
8
9# Add your custom routes
10@app.get("/status")
11async def status_check():
12 return {"status": "healthy"}
13
14# Pass your app to AgentOS
15agent_os = AgentOS(
16 agents=[Agent(id="basic-agent", model=OpenAIResponses(id="gpt-5.2"))],
17 base_app=app # Your custom FastAPI app
18)
19
20# Get the combined app with both AgentOS and your routes
21app = agent_os.get_app()
Tip

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.py
1fastapi run your_app.py --reload
1fastapi run your_app.py --host 0.0.0.0 --port 8000

Running in Production

For production deployments, you can use any ASGI server:

1uvicorn main:app --host 0.0.0.0 --port 8000 --workers 4
1gunicorn main:app -w 4 -k uvicorn.workers.UvicornWorker --bind 0.0.0.0:8000
1fastapi run main.py --host 0.0.0.0 --port 8000

Adding Custom Routers

For better organization, use FastAPI routers to group related endpoints:

1from kern.agent import Agent
2from kern.db.sqlite import SqliteDb
3from kern.models.anthropic import Claude
4from kern.os import AgentOS
5from kern.tools.hackernews import HackerNewsTools
6from fastapi import FastAPI
7
8# Set up the database
9db = SqliteDb(db_file="tmp/agentos.db")
10
11# Set up the agent
12web_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)
22
23# Create custom FastAPI app
24app: FastAPI = FastAPI(
25 title="Custom FastAPI App",
26 version="1.0.0",
27)
28
29# Add your own routes
30@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 ]
44
45
46# Set up the AgentOS app by passing your FastAPI app
47agent_os = AgentOS(
48 description="Example app with custom routers",
49 agents=[web_research_agent],
50 base_app=app,
51)
52
53# Alternatively, add all routes from AgentOS app to the current app
54# for route in agent_os.get_routes():
55# app.router.routes.append(route)
56
57app = agent_os.get_app()
58
59
60if __name__ == "__main__":
61 """Run the AgentOS application.
62
63 You can see the docs at:
64 http://localhost:7777/docs
65
66 """
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, HTTPException
2from fastapi.middleware.cors import CORSMiddleware
3from fastapi.security import HTTPBearer
4
5app = FastAPI()
6
7# Add CORS middleware
8app.add_middleware(
9 CORSMiddleware,
10 allow_origins=["https://yourdomain.com"],
11 allow_credentials=True,
12 allow_methods=["*"],
13 allow_headers=["*"],
14)
15
16# Security dependency
17security = HTTPBearer()
18
19async 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 token
23
24# Protected route
25@app.get("/protected", dependencies=[Depends(verify_token)])
26async def protected_endpoint():
27 return {"message": "Access granted"}
28
29# Integrate with AgentOS
30agent_os = AgentOS(
31 agents=[Agent(id="basic-agent", model=OpenAIResponses(id="gpt-5.2"))],
32 base_app=app
33)
34
35app = 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()
3
4# Get all routes
5routes = agent_os.get_routes()
6
7for route in routes:
8 print(f"Route: {route.path}")
9 if hasattr(route, 'methods'):
10 print(f"Methods: {route.methods}")

Developer Resources