Finishing the Local LLM App: Build-Time Env Values, HOSTNAME in Docker, Deleting Chats and a CPU/GPU Picker
Close the four gaps the first test round found in the Gemma chat app: the captcha site key (baked in at build), the container-ID address (HOSTNAME=0.0.0.0), a delete button for chats, and a devices endpoint that lets the user pick CPU or a GPU per message. Then the Django and Flask differences.
What you will learn
- Explain why a NEXT_PUBLIC value change needs an image rebuild, not a restart
- Fix a Next.js container that prints its container ID instead of localhost with HOSTNAME=0.0.0.0
- List the devices torch can see in a FastAPI endpoint and send the chosen one with each message
- Compare how the Django and Flask versions detect and pick the device
Before you start
- Smoke-testing the dockerized LLM app
- React state and fetch
The first test round left a list. Four things still don't work in the Gemma chat app:
- The captcha on the login page, because the app doesn't have the right site key.
- In Docker, the front end prints the container ID with
:3000instead of an address you can open. - There's no way to delete a chat.
- The app should detect the GPUs, show them in a dropdown next to CPU, and run the model on whichever one the user picks.
We hand all four to the coding agent in one prompt. The role and context say what the app is (a FastAPI backend with a Celery worker and a Next.js front end, all in Docker), the task lists the four fixes one line each, and the format asks for the changed files plus a short note on any step you have to take on your own machine. That last line matters, because some GPU steps happen outside the code.
1. The captcha: a value baked in at build time
login-form.tsx reads NEXT_PUBLIC_HCAPTCHA_SITE_KEY. If it's empty, the form shows "Captcha is not configured" instead of the box. The right value is the site ID from your hCaptcha dashboard under Sites, and it goes into .env. The secret stays in Supabase (see hCaptcha on the login page).
Here's the part that's easy to miss. Anything starting with NEXT_PUBLIC_ is written into the browser code when the image is built. Compose passes it as a build argument and the Dockerfile reads it with ARG. So after you change the key you must rebuild the front-end image. Restarting the container isn't enough.
2. The address: HOSTNAME
Docker sets an environment variable called HOSTNAME inside every container, and its value is the container ID. The Next.js standalone server reads HOSTNAME to decide which address to listen on and print. So it printed the container ID with :3000, and your browser doesn't know that address.
The fix is HOSTNAME=0.0.0.0, which means "listen on every network interface in the container". In the FastAPI version it's set in two places. In the compose file:
environment:
HOSTNAME: "0.0.0.0"
and once more in the Dockerfile command, right before the server starts, so Docker's own value can't win:
ENV HOSTNAME=0.0.0.0
COPY --from=builder /app/.next/standalone ./
COPY --from=builder /app/.next/static ./.next/static
EXPOSE 3000
CMD ["sh", "-c", "HOSTNAME=0.0.0.0 node server.js"]
Port 3000 is mapped to your machine, so you open localhost:3000.
3. Deleting a chat
In conversation-sidebar.tsx, each chat gets a trash button that appears on hover. Clicking it runs handleDelete:
async function handleDelete(id: string) {
if (deletingId) return;
if (!window.confirm("Delete this conversation? This can't be undone.")) return;
setError(null);
setDeletingId(id);
try {
await deleteConversation(id);
// If we're viewing the deleted conversation, move off it; then refresh the rail.
if (pathname === `/chat/${id}`) {
router.push("/chat");
}
router.refresh();
} catch (err) {
setError(err instanceof Error ? err.message : "Couldn't delete the conversation.");
} finally {
setDeletingId(null);
}
}
It asks first, because this can't be undone. deleteConversation in chat-api.ts is one Supabase call:
export async function deleteConversation(id: string): Promise<void> {
const supabase = createClient();
const { error } = await supabase.from("conversations").delete().eq("id", id);
if (error) {
throw new Error(error.message || "Couldn't delete the conversation.");
}
}
If you were looking at that chat, the page moves back to /chat, and router.refresh() reloads the list. If Supabase returns an error, its message shows in the sidebar.
4. Choosing where the model runs
On the backend, gemma_core/devices.py has one function:
def list_devices() -> list[dict]:
devices: list[dict] = [{"id": "cpu", "label": "CPU"}]
try:
import torch # noqa: WPS433 - optional ML dep
if torch.cuda.is_available():
for i in range(torch.cuda.device_count()):
try:
name = torch.cuda.get_device_name(i)
except Exception: # noqa: BLE001
name = f"CUDA device {i}"
devices.append({"id": f"cuda:{i}", "label": f"{name} (GPU {i})"})
except Exception: # noqa: BLE001 - torch missing or no driver: CPU only
pass
return devices
It always starts with CPU, then adds every GPU torch can see, with an id like cuda:0. If torch is missing or there's no driver, the list stays CPU only, so the endpoint never fails. routes.py exposes it:
@router.get("/devices", response_model=list[DeviceOut], tags=["meta"])
def get_devices():
"""Compute devices the user can run inference on (CPU + any visible GPUs)."""
return list_devices()
When the chat page opens, it calls the devices endpoint, fills the dropdown and picks the first GPU if there is one, otherwise CPU. The chosen device rides in the device field of the POST /chat; if nothing is sent, it's auto. The worker runs the task with that device, and get_engine caches one engine per weights and device:
def get_engine(hf_id: str, device: str = "auto") -> BaseEngine:
"""Return a cached engine for the given model + device (thread-safe).
The cache is keyed by (weights dir, device) so switching between CPU and a
GPU loads each target once and reuses it afterwards.
"""
if settings.use_fake_engine:
return _engines.setdefault("__fake__", FakeEngine())
location, local_only = resolve_location(hf_id)
key = f"{location}@{device}"
# ...
One detail: the list comes from the api container, but the worker runs the model. Both are built from the same image and need the same GPU access, or the two would disagree.
Rebuild and run the final version
docker compose down
docker compose -f docker-compose.yml -f docker-compose.gpu.yml up --build
The second file adds GPU entries on top of the first. The build takes a while, mostly for torch. When it's up, the front end prints localhost:3000 instead of the container ID.
In Swagger, GET /devices returned one entry, cpu. The api log says why: when the endpoint imports torch, torch warns that the NVIDIA driver on this machine is too old for its CUDA version, so it sees no GPU. The dropdown shows CPU only. (Giving containers the GPU is its own step: GPU for Docker containers.)
We asked "who are you". The log shows the request travel: GET devices, then POST chat accepted, then the worker receiving the task. After a while Gemma introduces itself as a large language model from the Gemma team at Google DeepMind. It's slow on the CPU, but the whole path works: login, queue, model and back. The chat shows under History, with the trash button on hover.
How Django and Flask do it
| FastAPI | Django | Flask | |
|---|---|---|---|
| HOSTNAME | compose environment and the Dockerfile command | once, ENV HOSTNAME=0.0.0.0 in the Dockerfile; command is plain node server.js | once in the Dockerfile; no compose entry |
| Delete chat | sidebar calls deleteConversation helper | handleDelete makes the same Supabase call itself; spinner on the icon; error in an alert | no delete button |
| Device list | GET /api/v1/devices, api imports torch | worker runs publish_capabilities and saves to Redis; api reads it at GET /api/v1/device (signed in only, 401 without a token); worker online false until the worker reports | GET /api/v1/system, one object: accelerator, CUDA available, devices auto, cpu (+ cuda) |
| Picking | device field on every message | POST /api/v1/device saves one choice in Redis for the whole app, every user's next message | Auto / GPU / CPU picker, remembered in the browser, sent with each message; GPU greyed out without CUDA |
| GPU in compose | second file, docker-compose.gpu.yml | in the main file | in the main file, deploy block on api and worker |
On HOSTNAME, the lecture notes for the Django take say Docker only puts the container ID into HOSTNAME when the image doesn't set it, and they checked that it behaves this way. The FastAPI Dockerfile's comment takes the safer view and sets it again in the command. Either works for this app.
Flask also hit a redirect problem: after sign-in the browser landed on 0.0.0.0:3000. The FastAPI version builds every redirect from one configured address, NEXT_PUBLIC_SITE_URL. Flask repairs the address it sees instead: in middleware.ts, if the request host starts with 0.0.0.0, it sets the hostname to localhost and redirects, and the auth callback and sign-in actions do the same swap.
Common mistakes
- Restarting after a key change.
NEXT_PUBLIC_needs a rebuild. - Opening the address the container prints. If it's a container ID, set
HOSTNAME=0.0.0.0. - Giving the GPU to the worker but not the api (FastAPI version). The api lists devices, so it would report CPU only.
- Deleting without a confirm. It can't be undone.
Quick recap
| Problem | Fix |
|---|---|
| Captcha not configured | Real site key in .env, then rebuild the front end |
| Container ID instead of localhost | HOSTNAME=0.0.0.0 |
| No delete | supabase.from("conversations").delete().eq("id", id) behind a confirm |
| Where the model runs | list_devices(), a dropdown, the device on each message, get_engine keyed by weights and device |
Try it yourself
Pick CPU in the dropdown, send a message, and look for the device field in the POST request in your browser's network tab.
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.
