Building AI Agent APIs with FastAPI
Build a production-ready AI agent API with FastAPI: async endpoints, structured outputs, SSE streaming, a bounded tool-calling loop, concurrency limits and a deployment checklist.
📜 Table of Contents
📖 Keep reading
Building an AI Agent API with FastAPI: Full 2026 Tutorial
FastAPI fits agent backends for three reasons: every core operation is I/O bound so async pays off, Pydantic v2 turns "the model must return this shape" into real validation, and OpenAPI docs come free.
1. Project layout
Keep routing, the agent loop and tool implementations in separate files. Routing should only validate input, call the agent and map errors.
2. Minimal endpoint
client = AsyncOpenAI(base_url=os.environ["LLM_BASE"], api_key=os.environ["LLM_KEY"])
@app.post("/v1/ask", response_model=AskResponse)
async def ask(req: AskRequest):
r = await client.chat.completions.create(model=os.environ["LLM_MODEL"],
messages=[{"role": "user", "content": req.question}], timeout=30)
return AskResponse(answer=r.choices[0].message.content, tokens=r.usage.total_tokens)
Use AsyncOpenAI, never the sync client inside async code.
3. Structured output
Define a Pydantic model with Literal fields so unexpected values fail validation instead of silently reaching your database. Retry once on validation error, then return 422.
4. Streaming
Server-sent events are enough. Two traps: nginx buffers responses by default (disable proxy_buffering or send X-Accel-Buffering: no), and generators keep running after the client disconnects unless you check request.is_disconnected().
5. Tool-calling loop
Loop model call → execute tools → feed results back. Always cap iterations (6 is a sane default); a failing tool otherwise makes the model retry until your quota is gone. Truncate tool output before appending it to the conversation.
6. Concurrency
| Setting | Starting point |
|---|---|
| Workers | CPU cores × 1–2 |
| Request timeout | 30–60s, aligned with upstream |
| Concurrency cap | asyncio.Semaphore at module level |
| Retries | 2, exponential backoff, 5xx only |
7. Deployment
Run gunicorn with uvicorn.workers.UvicornWorker, supervise with systemd, set proxy_read_timeout above your app timeout, and expose a /healthz endpoint.
FAQ
- Sync
requestsblocks the event loop — usehttpx.AsyncClient. - Store conversation history in Redis with a TTL, not in a process dict.
- Summarize old turns instead of dropping them when the context budget fills.
Model names, parameters and quotas change; check vendor docs for current values.
Written by our editorial team; tools listed here are tested or verified against public sources. Links point to official sites or GitHub repos for reference only — no paid placements.