By Abhijith N M · Reviewed 24 October 2026 · Editorial standards
A support agent in production is an HTTP service around a model. The edge — a CLI for local runs, FastAPI for the service — owns everything that must be true regardless of what the model says: authentication, authorisation, validation, request identity, timeouts and error shapes. The agent owns reasoning. Mixing the two is how prompt text ends up deciding whether a customer may see an order.
x-request-id or generate one, keep it in a context variable, log it and return it in the response header so a customer's screenshot matches a trace.One endpoint, one service function, one health check. The handler does not import the provider SDK; it calls run_agent, the single seam where tracing, budgets and the agent live. Keeping that seam means the same agent can also be called from a CLI, a job or a test without the HTTP layer.
import asyncio
from contextvars import ContextVar
from uuid import uuid4
from fastapi import FastAPI, HTTPException, Request
from pydantic import BaseModel, Field
app = FastAPI()
request_id: ContextVar[str] = ContextVar("request_id", default="")
REQUEST_TIMEOUT_SECONDS = 20.0
class TicketRequest(BaseModel):
message: str = Field(min_length=1, max_length=2000)
class TicketReply(BaseModel):
request_id: str
answer: str
async def run_agent(thread_id: str, text: str, rid: str) -> str:
"""The only seam the handler uses; replace the stub with the real agent.
Call `build_agent(...).ainvoke(...)` here, pass the request id and thread
id into the tracer, and let it enforce the token and step budgets.
"""
return "Order #4521 was delivered on Tuesday."
@app.middleware("http")
async def attach_request_id(request: Request, call_next):
rid = request.headers.get("x-request-id") or str(uuid4())
request_id.set(rid)
response = await call_next(request)
response.headers["x-request-id"] = rid
return response
@app.post("/threads/{thread_id}/messages", response_model=TicketReply)
async def send_message(thread_id: str, body: TicketRequest) -> TicketReply:
try:
answer = await asyncio.wait_for(
run_agent(thread_id, body.message, request_id.get()),
timeout=REQUEST_TIMEOUT_SECONDS,
)
except TimeoutError as exc:
raise HTTPException(
status_code=504,
detail="The agent timed out; the ticket has been handed to a human.",
) from exc
return TicketReply(request_id=request_id.get(), answer=answer)
@app.get("/health")
async def health() -> dict[str, str]:
"""Liveness only: cheap, with no model, database or vector-store call."""
return {"status": "ok"}The seam is also where tracing begins: start one run per request with the request id, thread id, prompt version and model name as metadata, then let callbacks attach the model and tool spans beneath it. Return the run id in the reply or in the completion event so a customer report maps to exactly one trace. Trace the failure paths too — timeout, 429, guardrail refusal, approval pending — because those are the runs you will be asked about.
Every network call can hang. Decide the deadline for the whole request first — for a chat turn, 20 to 30 seconds is generous — then make every provider and tool call time out below it, so the handler still has time to write a useful error. The agent's step budget is a separate, earlier stop: a loop that has taken six steps is not going to finish in the remaining seconds.
A 20-second blank screen loses trust. Stream the run as Server-Sent Events: one event kind for agent steps ("looking up order #4521"), one for answer tokens, and one final event with the request id, token usage and any hand-off. Flush early and send a heartbeat during a slow tool call so proxies do not close the connection; on the client, reconnect with the request id instead of starting a second run.
# Same module as the FastAPI app above: add these two definitions.
from collections.abc import AsyncIterator
from fastapi.responses import StreamingResponse
async def agent_events(thread_id: str, text: str) -> AsyncIterator[str]:
"""Yield SSE frames: step progress, answer tokens, then a done frame."""
yield "event: step\ndata: looking up order #4521\n\n"
yield "event: token\ndata: Order #4521 was delivered on Tuesday.\n\n"
yield "event: done\ndata: [DONE]\n\n"
@app.post("/threads/{thread_id}/stream")
async def stream(thread_id: str, body: TicketRequest) -> StreamingResponse:
return StreamingResponse(
agent_events(thread_id, body.message),
media_type="text/event-stream",
headers={"x-request-id": request_id.get()},
)Health checks are not load tests. A liveness probe should answer in milliseconds without touching the model, the vector store or the database; a readiness probe may check those dependencies briefly and report not-ready. Never call the model from a probe: a provider outage would mark every instance unhealthy at the same moment.
Key takeaways
The HTTP edge owns auth, validation, request ids, timeouts and error shapes; the agent owns reasoning.
One seam (run_agent) connects the handler to the agent, so the same agent serves HTTP, a CLI and tests.
Timeout the whole request and every call below it, retry only idempotent work, and degrade to a human hand-off.
Stream steps and tokens, keep health checks cheap, and ship behind a checklist: config, observability, safety, capacity, release, data.
Written and edited by the nexGenCoders team. Spotted a mistake? Tell us and we will fix it.
Don't lose this lesson
Create a free account to save your progress, keep your streak, and work toward a shareable certificate.