Course contents · Lesson 15 of 16

Add a Simple Web UI to Your LLM App, Hands-On

Ship It · Lesson 15 of 16 · 12 min Hands-on

Your handbook assistant answers well, but only in a terminal. The people team wants to try it, and they will not make a virtual environment or type python3 ask_with_sources.py. In this lesson you add a web UI to your LLM app: a small web service with a POST /ask endpoint, one page where the answer appears word by word, and errors a person can understand.

The counter and the kitchen

A web app has two halves, a frontend and a backend. Here the frontend is one HTML page with a little JavaScript that runs in the browser. The backend is a web service, a program that waits on a port for HTTP requests and answers them. Only the backend runs your RAG code and talks to Ollama.

You write the backend with FastAPI, a Python framework that turns ordinary functions into endpoints: a method plus a path, such as POST /ask, that a client can call. Uvicorn is the server that runs it: it listens on port 8000 and hands each request to FastAPI.

Flowchart of one question. Top row, left to right: 1, the browser page, where someone types a question; 2, POST /ask with a JSON body holding the question; 3, FastAPI checks whether it is empty or too long; 4, retrieve embeds the question and takes the top 4 chunks; 5, Ollama writes the answer. Dashed branches: a failed check gives HTTP 400, and Ollama being down during retrieve gives HTTP 503, each with a message on the page. Bottom row, right to left: 6, FastAPI relays each piece token by token as one JSON event per line, first sources, then token events such as You and get, then done with cited 1; 7, the page updates and the words appear live. Footer: the browser talks only to FastAPI on port 8000, and FastAPI talks to Ollama on port 11434.
The question goes out as one request; the answer comes back as many small pieces.

The aha is the U-turn: one request goes out, and the answer returns as a stream of small events, each shown the moment it arrives. A failed check ends the request early with a message instead.

The lab, course-labs/building-llm-apps/15-web-ui, reuses the kitchen of lessons 9 and 10: retrieve(), the numbered chunks, the refusal rule for a best score under 0.5, and check_citations(), behind a new app.py and static/index.html.

A FastAPI app with a POST /ask endpoint

The endpoint is a plain function whose parameter is a pydantic model, as in lesson 4. FastAPI reads the JSON body into it and answers HTTP 422 by itself if there is no question string. The other checks are yours. Simplified from app.py:

class AskRequest(BaseModel):
    question: str
    stream: bool = True

@app.post("/ask")
def ask(request: AskRequest):
    question = request.question.strip()
    if not question:
        raise HTTPException(400, "Please type a question first.")
    if len(question) > MAX_QUESTION_CHARS:  # 1,000
        raise HTTPException(400, f"Your question is {len(question):,} characters long. ...")
    try:
        retrieved = retrieve(question, get_index(), TOP_K)   # the first call to Ollama
    except OllamaError as error:
        log.warning("POST /ask: %s", error)  # the details, in the uvicorn terminal
        raise HTTPException(503, "The assistant is not available right now: ...")
    ...                                      # then stream the answer

HTTPException ends the request with an HTTP status code (lesson 2) and a body such as {"detail":"Please type a question first."}. 400 means the request is wrong; 503, Service Unavailable, means the server cannot help right now. The page shows detail; the technical reason goes to your terminal, not to the reader.

The function uses def, not async def, so FastAPI runs it in a separate thread and the blocking calls to Ollama do not hold up other requests. With "stream": false, it returns one JSON object with answer and sources instead.

Stream the answer so words appear as they are written

Without streaming, nobody sees a word until the model has written the last one, often several seconds on a laptop CPU. Streaming shows the first words as soon as they exist, the time to first token of lesson 12. The total time is the same; the wait feels much shorter.

answer_events() is a generator, a function that hands out values one at a time with yield. Each value is an event: the sources, then one token per piece from Ollama, then done. Simplified:

def answer_events(question, retrieved):
    yield {"type": "sources", "sources": [...]}   # chunks [1] to [4]
    answer = ""
    for piece in chat_stream(build_messages(question, retrieved), CHAT_MODEL):
        answer += piece
        yield {"type": "token", "text": piece}
    yield {"type": "done", "cited": [...],
           "problems": check_citations(answer, [], len(retrieved))}

lines = (json.dumps(event) + "\n" for event in answer_events(question, retrieved))
return StreamingResponse(lines, media_type="application/x-ndjson")

StreamingResponse sends each line the moment it is yielded, in the newline-delimited JSON Ollama itself streams; chat_stream() is lesson 2's streaming loop as a generator. The model writes plain text with [n] markers, not lesson 10's JSON, because JSON can only be parsed once complete. The server checks the markers at the end and reports them in done.

One catch: status 200 is sent as the stream starts, before the first line. If Ollama fails halfway, it is too late for a 503, so the server sends a last error event, as Ollama does.

A plain HTML page that keeps answers as text

static/index.html is one file with no framework, which FastAPI serves at GET /.

Wireframe of the page in a browser at localhost:8000, titled Ask the Kettle and Leaf handbook. From the top: a text box holding How many days of sick leave do I get?, a green Ask button, the status line Done., the Answer box holding the answer that has just streamed in, You get 8 days of paid sick leave per year [1]., and the Sources list with [1] 03-leave.md, Sick leave, above a note that answers can be wrong. Callouts: the server allows questions of up to 1,000 characters; the Ask button sends POST /ask, then waits; the status line shows progress, or the error in red; the answer is filled with textContent, never innerHTML, as it arrives; at the end, Sources keeps only the chunks the answer cites.
Every part of the page is filled as text, never as HTML.

The script posts the question with fetch() and reads the reply as it arrives. A read can stop mid-line, so it keeps the unfinished end for the next one:

const reader = response.body.getReader();
const decoder = new TextDecoder();
let buffer = "";
while (true) {
  const {done, value} = await reader.read();
  if (done) break;
  buffer += decoder.decode(value, {stream: true});
  const lines = buffer.split("\n");
  buffer = lines.pop();                  // half a line: keep it
  for (const line of lines) if (line.trim()) handle(JSON.parse(line));
}
// in handle(), each token is added as text:
answer.textContent += event.text;

That last line is a security decision. innerHTML parses a string as HTML; textContent shows it as plain characters. If the poisoned document of lesson 13 talks the model into writing <img src=x onerror="...">, innerHTML would run that handler, as MDN warns. That is cross-site scripting (XSS): someone else's code running in your page. So every string from the server goes in with textContent.

Run it with uvicorn, and break it on purpose

This lab needs Python 3.11 or newer: FastAPI 0.165.0 and uvicorn 0.55.0 no longer install on 3.10. With Ollama on port 11434 and both models pulled, run:

cd course-labs/building-llm-apps/15-web-ui
python3 -m venv .venv && . .venv/bin/activate
pip install -r requirements.txt
python3 index.py data/handbook
uvicorn app:app --port 8000

index.py should cut the same 34 chunks as before. It worked when uvicorn prints Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit). address already in use means another program holds port 8000: stop it, or use --port 8001.

Now break it. An empty question gets HTTP 400, and so does one over 1,000 characters: long input costs tokens and time, and can crowd the chunks out of the context window (lesson 3). A limit on the text box alone would not help, because curl never sees the page. FastAPI's max_body_size also refuses any body over 16 KB with HTTP 413. With Ollama stopped, retrieval cannot embed the question: 503.

Limits for a demo: keep it on localhost

This app has no login, so anyone who can reach it can use it, and no rate limit, a cap on how many requests one client may send per minute. Each question keeps your CPU busy for seconds, so one looping script could tie it up.

Box diagram of one laptop, where every port listens on 127.0.0.1 only. The browser at localhost:8000 sends HTTP on port 8000 to the FastAPI app, which uvicorn runs as a Python process. FastAPI reads index.json, 34 chunks plus vectors, once, and sends HTTP on port 11434 to Ollama, which runs in a Docker container with llama3.2:3b and nomic-embed-text and keeps its models in the ollama-models named volume. Outside the laptop, other devices on your network cannot connect. Footer: the page never calls Ollama, only the app does.
Two servers, two ports, and neither reachable from outside your laptop.

Uvicorn listens on 127.0.0.1 unless you pass --host; its settings docs say --host 0.0.0.0 makes the app available on your local network. Leave that off until you add a login, a rate limit and lesson 13's input checks, which this lab skips to stay short.

Check yourself

A teammate adds maxlength="1000" to the text box and deletes the length check in app.py. Are very long questions still stopped?

No. maxlength only limits that page; curl or a script can send anything. Only a check on the server sees every request.

Ollama crashes halfway through a streamed answer. Why can the server no longer send a 503, and how does the page find out?

The status code was sent before the first line and cannot be changed. So the server sends a final error event, and the page shows its message.

Your system prompt tells the model never to write HTML. Is it then safe to insert the answer with innerHTML?

No. A prompt is a request, not a lock, and a poisoned document can talk the model round. textContent keeps whatever the model writes as text.