Wrapping the agent in a web app
Turn the terminal agent into a FastAPI service with a chat endpoint and a minimal browser UI.
A terminal agent is great for you; a URL is what you share. We wrap the same AnalyticsAgent in FastAPI — a small Python web framework — exposing a chat endpoint and serving a simple HTML chat page. No rewrite: the agent code you built is reused as-is.
The service
import os
import sys
from fastapi import FastAPI
from fastapi.responses import FileResponse
from pydantic import BaseModel
# Make the sibling agent/ folder importable, same trick as the other modules.
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "agent")))
from agent import AnalyticsAgent
app = FastAPI()
agent = AnalyticsAgent()
class ChatRequest(BaseModel):
message: str
history: list = []
@app.post("/api/chat")
def chat(req: ChatRequest):
result = agent.answer(req.message, req.history)
return {
"reply": result["text"],
"tool_calls": result["tool_calls"],
"history": _trim_history(result["messages"]),
}
@app.get("/")
def index():
return FileResponse(os.path.join(os.path.dirname(__file__), "static", "index.html"))That's the whole backend. The browser posts a message plus its saved history to /api/chat; the endpoint runs the agent loop; the reply, the tool calls, and the updated history come back as JSON so follow-up questions keep their context. The shipped file's _trim_history helper reduces that history to plain text turns before returning it — raw Anthropic message objects (tool_use, thinking blocks) aren't JSON-serializable. The static index.html is a lightweight chat UI — an input box, a message list, and a fetch call. It even shows which semantic-layer tools each answer used, so the governance is visible to the user.
Run it locally first
uvicorn is the server program that runs FastAPI apps — app.main:app means "the app object inside app/main.py."
pip install -r requirements.txt
export ANTHROPIC_API_KEY=sk-ant-...
uvicorn app.main:app --reload
# open http://localhost:8000Get it working on localhost — click the suggested questions, confirm answers and the tool badges appear — before you deploy. Debugging is ten times easier locally than in a cloud log. Deployment should be boring because the app already works.