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 Agent
2from kern.db.postgres import PostgresDb
3from kern.models.anthropic import Claude
4from kern.os import AgentOS
5from kern.tools.hackernews import HackerNewsTools
6from fastapi import FastAPI
7
8# Setup the database
9db = PostgresDb(db_url="postgresql+psycopg://ai:ai@localhost:5532/ai")
10
11web_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)
22
23# Custom FastAPI app
24app: FastAPI = FastAPI(
25 title="Custom FastAPI App",
26 version="1.0.0",
27)
28
29
30# Add your own routes
31@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 ]
45
46
47# Setup our AgentOS app by passing your FastAPI app
48# Use route_prefix to avoid conflicts with your custom routes
49agent_os = AgentOS(
50 description="Example app with custom routers",
51 agents=[web_research_agent],
52 base_app=app,
53)
54
55# Alternatively, add all routes from AgentOS app to the current app
56# for route in agent_os.get_routes():
57# app.router.routes.append(route)
58
59app = agent_os.get_app()
60
61
62if __name__ == "__main__":
63 """Run your AgentOS.
64
65 With this setup:
66 - API docs: http://localhost:7777/docs
67
68 """
69 agent_os.serve(app="custom_fastapi:app", reload=True)

Usage

Set up your virtual environment

1uv venv --python 3.12
2source .venv/bin/activate
1uv venv --python 3.12
2.venv\Scripts\activate

Set Environment Variables

1export ANTHROPIC_API_KEY=your_anthropic_api_key

Install dependencies

1uv pip install -U kern-ai anthropic fastapi uvicorn sqlalchemy pgvector psycopg

Setup PostgreSQL Database

1# Using Docker
2docker 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:pg17

Run Example

1python custom_fastapi.py