Support Copilot Architecture and Starter Kit: One Folder, Settings in .env, Postgres Before the API, and a Four-Event Contract With React
The foundation of a support copilot for an online shop: the browser only talks to FastAPI, Compose starts Postgres with pgvector before the API, get_model() and current_user() are the two seams, and a contract of four calls and four stream events (agent, token, sources, done) lets React and the API grow separately.
What you will learn
- Describe the shape of an AI support copilot: React page, FastAPI, Postgres with pgvector, and a model behind one function
- Keep every setting in .env and switch between a stand-in and a hosted model without changing code
- Start Postgres before the API with a Docker Compose health check and depends_on
- Write an API contract (four calls, four stream events) that a React developer can build against
Before you start
- FastAPI for AI Services
- Docker for AI Apps
- Streaming LLM Answers From FastAPI
Before an AI app can answer anything, it needs a base: a folder layout, settings, a database, an API and a clear agreement with the front end. In this article we lay that base for the Support Copilot, an assistant for an online shop's support team. Everything runs on a stand-in test model, so no key is needed; put a key in .env and the same code calls a hosted model.
The use case: a copilot for a shop's support team
A customer writes: "I was charged twice for order 1042." Someone on the support team has to read it, then check the order and its payments. Another customer asks how to reset a password, and that answer already sits in the help-centre pages. The copilot helps with both. It answers from the help centre, looks up the order and its payments, and drafts a refund that a human approves.
The finished app is built from parts you may already know. A supervisor (built with LangGraph) reads each question and sends it to a RAG agent for help-centre questions or to a ticket agent that uses MCP tools for orders and refunds. A refund waits for a person to approve it, and LangSmith traces every step. It is built in eight stages: starter kit, knowledge base, agent graph, MCP tools, human approval, streaming chat UI, tracing and evals, and deploy. This article is stage one. It's like building a house on a foundation that's already poured: FastAPI, a Supabase-style login, Postgres and Docker are the slab, and every later stage stands on it.
The shape of the app
On the left is the React page the support person uses. It sends every request to FastAPI, which runs in a container called api, published on port 8010. FastAPI talks to Postgres with pgvector in a second container called db, and asks the chat model through one function, get_model(). The page can't reach the database directly. Every request goes through FastAPI, which is where the login is checked.
Settings live in .env, not in the code
"""All settings in one place. Values come from environment variables or the .env file."""
from pydantic_settings import BaseSettings, SettingsConfigDict
class Settings(BaseSettings):
model_config = SettingsConfigDict(env_file=(".env", "../.env"), extra="ignore")
env: str = "dev"
database_url: str = "postgresql://copilot:copilot@localhost:5433/copilot"
# Supabase signs its login tokens (JWT) with a shared secret; we check them with the same one.
jwt_secret: str = "dev-only-secret-change-me-please-32-bytes"
# "fake" = the stand-in test model (no key needed). "openai" / "anthropic" use a real model.
model_provider: str = "fake"
model_name: str = ""
allowed_origins: str = "http://localhost:5173,http://localhost:3000"
settings = Settings()
There is one Settings class for the whole app, and env_file tells it to read .env. The defaults are local development values only. model_provider defaults to fake, the stand-in test model. In .env.example, MODEL_PROVIDER=fake is set too, so a fresh copy runs offline. Its comments show the other way: set the provider, a model name and the matching key, install requirements-real.txt, and get_model() picks a hosted model. Nothing else in the project changes.
Docker Compose: the database first
services:
db:
build: ./db # pgvector + init.sql baked in (a bind mount does not work from a Google Drive folder)
environment:
POSTGRES_USER: copilot
POSTGRES_PASSWORD: ${DB_PASSWORD:-copilot}
POSTGRES_DB: copilot
ports:
- "${DB_PORT:-5433}:5432"
volumes:
- pgdata:/var/lib/postgresql/data
healthcheck:
test: ["CMD-SHELL", "pg_isready -U copilot -d copilot"]
interval: 3s
timeout: 3s
retries: 20
The db/Dockerfile starts from pgvector/pgvector:pg17 (Postgres 17 with vector search built in) and copies init.sql inside. We'll need vector search later for the help-centre pages. ${DB_PASSWORD:-copilot} means "take the value from .env, or fall back to the word after the dash". The named volume pgdata keeps the data across restarts, and init.sql runs only once, the first time that volume is empty. The health check asks Postgres every three seconds whether it's ready.
The API service waits for a healthy database
api:
build:
context: .
dockerfile: api/Dockerfile
environment:
DATABASE_URL: postgresql://copilot:${DB_PASSWORD:-copilot}@db:5432/copilot
JWT_SECRET: ${JWT_SECRET:-dev-only-secret-change-me-please-32-bytes}
MODEL_PROVIDER: ${MODEL_PROVIDER:-fake}
MODEL_NAME: ${MODEL_NAME:-}
ports:
- "${API_PORT:-8010}:8000"
depends_on:
db:
condition: service_healthy
Look at the database address: the host is just db, the service name. Inside Compose, services find each other by name. depends_on with condition: service_healthy means the API starts only after the database's health check passes. The API's Dockerfile starts from python:3.13-slim, installs the requirements once in a base stage, and its last stage copies the app and starts uvicorn on port 8000 (published as 8010).
docker compose up --build -d --wait
docker compose ps
curl localhost:8010/health
{"status":"ok","db":"up","model":"fake"}
docker compose ps shows both services healthy. The db field in the health answer matters: if Postgres stops, status stays ok but db says down, and the first test checks exactly that.
Sample data for the stories to come
init.sql creates an orders table and a payments table and fills in four sample orders: 1042, 1043 and 1044 for [email protected] and 1050 for [email protected]. Payments have one row per card charge:
INSERT INTO payments (order_id, amount_cents, created_at) VALUES
(1042, 8900, now() - interval '6 days'),
(1042, 8900, now() - interval '6 days' + interval '2 minutes'), -- the double charge
(1043, 2400, now() - interval '2 days'),
(1044, 5600, now() - interval '40 days'),
(1050, 12900, now() - interval '1 day');
Order 1042 has two charges. That's the customer who was charged twice, ready for the refund stage. The offline tests (python -m pytest) don't even need Docker: 5 passed.
main.py: three endpoints and a chat stream
def sse(event: str, data: dict) -> str:
"""One Server-Sent Event: "event: name", "data: json", then a blank line."""
return f"event: {event}\ndata: {json.dumps(data)}\n\n"
@app.get("/health")
def health() -> dict:
return {"status": "ok", "db": "up" if db_is_up() else "down", "model": settings.model_provider}
@app.post("/api/dev/token")
def dev_token(email: str = "[email protected]") -> dict:
"""Local-only sign in. A real deployment uses Supabase Auth instead (see README)."""
if settings.env != "dev":
return {"error": "disabled outside dev"}
return {"access_token": make_dev_token(email), "email": email}
@app.get("/api/me")
def me(user: dict = Depends(current_user)) -> dict:
return user
@app.post("/api/chat")
def chat(req: ChatRequest, user: dict = Depends(current_user)) -> StreamingResponse:
"""The contract the React page relies on. Events: agent, token, sources, done."""
def events():
yield sse("agent", {"name": "supervisor"})
for chunk in get_model().stream(req.message):
yield sse("token", {"text": chunk.content})
yield sse("sources", {"items": []})
yield sse("done", {"thread_id": req.thread_id or "demo"})
return StreamingResponse(events(), media_type="text/event-stream")
The dev token endpoint is a local sign-in that mints the same kind of token Supabase Auth would; outside dev it is switched off. /api/me depends on current_user: with the token you get [email protected] and the role customer, without one you get 401. /api/chat sends an agent event, then the answer from get_model() one small piece at a time as token events (here the text is a test model reply), then sources and done. For how a React page reads a stream like this, see Streaming LLM Answers From FastAPI.
The API contract between React and FastAPI
docs/API-CONTRACT.md is the most important file for a team. A React developer only needs it to start building the screen.
| Method and path | Who calls it | What it does |
|---|---|---|
GET /health | Docker, you | {"status":"ok","db":"up","model":"fake"} |
POST /api/dev/token | React (dev) | Local sign-in; returns an access token and the email. Disabled when ENV is not dev. |
GET /api/me | React | Who am I: email and role |
POST /api/chat | React | Send {"message": "...", "thread_id": "optional"}, get a stream of events |
event: name, data: json and a blank line. These four names are the whole promise to the front end.FastAPI also writes the OpenAPI description, and the paths it lists match the table one for one; the same list powers the /docs page. React builds against the contract, not against our code.
Two seams: the model and the login
@lru_cache
def get_model() -> BaseChatModel:
provider = settings.model_provider.lower()
if provider == "fake":
return StandInChatModel()
# Real models need the optional packages from requirements-real.txt.
from langchain.chat_models import init_chat_model
return init_chat_model(settings.model_name, model_provider=provider, temperature=0)
def current_user(creds: HTTPAuthorizationCredentials | None = Depends(bearer)) -> dict:
if creds is None:
raise HTTPException(401, "Missing bearer token")
try:
claims = jwt.decode(creds.credentials, settings.jwt_secret, algorithms=["HS256"],
audience="authenticated")
except jwt.PyJWTError as exc:
raise HTTPException(401, f"Invalid token: {exc}") from exc
return {"email": claims["email"], "role": claims.get("role", "customer")}
Every part of the app calls get_model(), and every protected route depends on current_user(). To swap the model or the login, you change one file, and the rest of the app stays as it is. The stand-in is a real LangChain chat model (both invoke and stream work) whose replies are scripted.
Common mistakes
- Letting the browser reach the database. Every request goes through the API, which checks the token. The page never gets a database URL.
- Starting the API before Postgres is ready. Use a health check plus
condition: service_healthy, not a sleep. - Using
localhostinside Compose. From theapicontainer, the database host isdb. - Expecting
init.sqlto run again. It runs only when the volume is empty.docker compose down -vremoves the volume and starts fresh. - Changing event names later. Add new events (like
approval) instead of renaming the four the page already relies on.
Quick recap
| Piece | Job |
|---|---|
config.py + .env | All settings in one place; MODEL_PROVIDER=fake runs offline |
db service | pgvector Postgres, a named volume, init.sql once, a health check |
api service | Reaches the database as db; starts only when it's healthy |
get_model(), current_user() | The two seams: swap the model or the login in one file |
| API contract | Four calls and four events: agent, token, sources, done |
The next stage fills Postgres with the help centre: see RAG on pgvector in FastAPI, which includes the copilot's loader, chunker and reindex. Tracing and evals for the finished copilot are in LangSmith Tracing for a LangGraph App. For a supervisor routing work to agents, see Multi-Agent Patterns: Hub and Spoke.
Try it yourself
Stop only the database with docker compose stop db and call /health again: status should still say ok while db says down. Then add a fifth endpoint of your own to main.py, add one row for it to API-CONTRACT.md, and check that it appears on the /docs page.
Related course on Udemy
The Python Architect Masterclass: Full Stack to AI Engineer
Python, Django, FastAPI, React, Docker, AWS, LLMs, RAG, agents and MCP, from first steps to AI engineer.View on Udemy ↗: The Python Architect Masterclass: Full Stack to AI Engineer (paid course, opens in a new tab)Related posts
Fallback Models for an LLM App: A Chain That Checks Region and Fit, Flags Degraded Answers and Gets Rehearsed
When the main model goes down, the backup has to be allowed to take the data, able to read the whole request and tested before the bad day. A simulated four-model chain for an EU customer: a 6,000-token request lands on mid-eu, flagged degraded; a 10,000-token request is served by nobody, on purpose.
Back Pressure for LLM Traffic: Bound the Queue, Give Chat Its Own Lane, Count Tokens, Cancel When the Caller Leaves
A bulk upload buries the chat. In a small simulation, one shared queue grows to 199 waiting and the middle chat answer takes 80.2 s. A bound plus a chat lane brings it to 0.35 s while 178 bulk jobs are told to retry in 10 s, and cancelling abandoned calls saves 21,000 wasted tokens.
Load Balancing LLM Traffic: Count the Work, Weigh the Prefix Cache, Check Real Health, Drain Before Deploys
Six GPU replicas, two at 95% and four at 30%: round robin counts requests, and requests aren't equal. In a small simulation, least outstanding requests cuts p95 from 6.52 s to 3.05 s, prefix affinity lifts cache hits to 95% but pushes p95 to 11.45 s, a real health check takes errors from 48 to 2, and draining cuts 0 answers instead of 4.
A Message Queue for Document Ingestion: At Least Once, Leases, an Idempotent Consumer and a Dead Letter Queue
A queue doesn't lose a document, but it can hand one out twice. In a small simulation, a worker crash makes document two go from 3 to 6 chunks and the index holds 11 when the documents hold 8. An idempotent consumer brings it back to 8 with the same two deliveries, and a limit of three tries moves a poison file to a dead letter queue.
