▚ The AI Engineer's Field Manual
Module 05b · Act II — ML Foundations

Full-Stack AI Apps — FastAPI, React and Streaming, From Model to Screen

"A model nobody can reach is a notebook. A model behind a search box, with the answer typing itself out, is a product."

~5 hours Builds on: Module 05 (the ticket data and model), Module 01 (Python tooling) Tools: FastAPI · Pydantic · React 19 · Vite 8 · TypeScript · Next.js 16 · SSE Job-spec line it unlocks: "build and demo a working full-stack AI prototype (React/Next.js + FastAPI) in 48 hours"

01 · The hookA Model in a Notebook Cannot Win a Client

Field report · Client memo

"Your triage model from last quarter is great. I have seen the confusion matrix. But nobody outside your team can touch it. It lives in a notebook.

Here is what my agents actually lose time on: when a ticket comes in, they spend about six minutes digging through old tickets for 'how did we fix this last time?' Across 8,000 tickets a day that is the next big cost after tagging.

I need a search box that finds similar past tickets, and a button that types out a suggested reply while the agent watches. Northwind Logistics are on a call with us in 48 hours. If they can click it, we win the renewal. If it is a notebook, we do not."

— Maya Lin, Chief Customer Officer at "HelpDeskAI"

You know how to build a backend. Nine years of that is the one thing in Maya's memo you do not need help with. What you may not have is the other half: a screen that updates while a model is still thinking, and a way to ship the whole thing before Thursday.

So this module builds one small product, end to end, in the order you would build it for real. We start from the ticket data you met in Module 05 and finish with a page you can click, a test suite that passes, and a checklist for the 48-hour sprint.

You already know this
You know (backend)It becomes (this module)
A REST endpoint with a request DTOA FastAPI endpoint with a Pydantic model. The model is the DTO and the validator and the OpenAPI schema.
A DB query ordered by an indexA search that orders past tickets by a similarity score.
Chunked HTTP response, long pollingServer-Sent Events: one open response, many small messages.
A template engine rendering HTMLA React component: a function from data to a piece of screen.
Same-origin policy, CORS headers on a gatewayThe same CORS, now the first error you will hit.

02 · The shape of the appThree Boxes and Two Streets Between Them

A full-stack AI app is three programs that talk in a line: a browser page, an API server, and the model or search index behind it. Without that picture, every bug looks like "the AI is broken" when it is usually one wire between two boxes.

Maya has given us one deadline (48 hours) and one product (a search box plus a reply that types itself). The model already exists. Before we write any code, we need the map of who talks to whom, because the first hour of a prototype is lost to guessing where the problem sits.

Start with the abstract picture. Three boxes sit in a row. The browser shows things and listens for clicks. The API checks input and decides what to call. The model and index do the AI work. Each arrow between them carries one kind of message.

1 2 3 Browser React + TypeScript API FastAPI + Pydantic Model + index MiniLM or TF-IDF JSON request SSE tokens query text top-3 tickets 13 keystrokes become 1 request 2 endpoints 7 tests pass 25 past tickets 384 numbers per ticket the same three boxes appear again, with real files, in Table 5b.1
Fig. 5b.1 — The abstract shape: a browser, an API and a model, joined by two streets, one for requests and one for replies.
  1. The browser. It owns the screen and nothing else. In our demo an agent types 13 characters, and the page turns those 13 keystrokes into a single request (the debounce, built later in this module).
  2. The API. It is the only box allowed to touch the model. It has 2 endpoints, /search and /suggest, and 7 automated tests guard them. Everything the browser may ask for is listed here and nowhere else.
  3. The model and the index. 25 past tickets, each turned into a list of numbers. The MiniLM model gives 384 numbers per ticket; the offline fallback, TF-IDF, gives one number per known word. Either way, one query becomes one list of numbers to compare.

Read the two arrows in each gap. The upper arrow is the question. The lower arrow is the answer. For /search the answer is one JSON message. For /suggest the answer is a stream: many small messages over one open connection, so the screen can start filling before the model has finished.

The same picture again, with real files in it

The abstract picture tells you where things live. When something breaks at 2 a.m. before the demo, you need to know which file and which command touches each box. Here is the same row of boxes, one line per stage, with the names this module uses.

Table 5b.1. The same three boxes, with the real files, calls and outputs
StageThe file you openThe call that runsWhat flows out
Browserfrontend/src/SearchPage.tsxfetch(API + '/search', {method: 'POST', ...})A JSON body such as {"query": "...", "k": 5}
Wire(browser dev tools, Network tab)An OPTIONS preflight, then the real POSTHeaders; the CORS answer decides whether the page may read the reply
APIbackend/app.py@app.post("/search") then top_hits()A SearchResponse: query, backend name, list of hits
Model + indexbuild_index() in app.pyMATRIX @ ENCODE([query])[0]One score per past ticket, highest first
API, streamingbackend/app.py@app.post("/suggest", response_class=EventSourceResponse)event: token lines, one per word
Browser, streamingfrontend/src/sse.tsreadSse(res), an async generatorReact state reply growing one word at a time
🧠 Brain power

Before reading on: why not let the browser call the model directly? Think about what would go wrong with the API key, with the 25 tickets, and with a second client (a mobile app) next year.

Reveal the answer

Three things break. First, any key you put in browser code is public, because the user can open dev tools. Second, every client would need its own copy of the "search and build a prompt" logic, so a fix has to ship three times. Third, you could not limit or log what is asked. The API is the one place where secrets, rules and logs live.

This is the same reason your database is never exposed to the browser. The model is just another backend resource.

Browser box
Shows data, collects input, never holds secrets.
API box
Validates input, calls the model, shapes the reply. The only box with keys.
Model + index box
Turns text into numbers and finds the nearest past tickets.
Request street
One JSON message, usually POST.
Reply street
One JSON message (search) or a stream of small events (suggest).
Why a stream
A model writes a reply in seconds; streaming lets the screen start after the first word instead of the last.

03 · Two ideasSearch by Meaning, Stream by Event

Two ideas carry the whole demo. Search by meaning finds old tickets that say the same thing in different words. Streaming sends the reply one small piece at a time so the screen never sits blank.

We now have the map in Fig. 5b.1. The agents' pain is the middle and right boxes: find a similar ticket, then write something. Both need one new idea each, and both are small enough to try by hand first, so that is where we start.

Search by meaning, with three arrows and a pencil

A new ticket says "database keeps timing out". We hold three solved tickets. We need a number for "how alike are these two pieces of text", and we need it to work even when the words differ. Here is the smallest version of that number you can compute on paper.

Imagine every ticket is an arrow on a flat page. The arrow points toward "money words" if the ticket is mostly about payments, and toward "machine words" if it is mostly about servers. A ticket about both points in between. Every arrow has length 1, so only the direction carries meaning.

Two tickets that mean the same thing point the same way. To measure "same way", multiply the arrows' two coordinates and add. That is the dot product (multiply matching numbers, then add the results). For arrows of length 1, a bigger dot product means the arrows point more alike. That one number is the score the search sorts by.

You have not been told how real text becomes an arrow yet. Do not worry. The next sections show both ways (counting words, and a small neural model). Here we only practise the scoring step, with arrows we made up.

Sharpen your pencil

The new ticket Q is the arrow (0.6, 0.8). Score each of the three solved tickets by the rule "multiply the first numbers, multiply the second numbers, add". Then rank them. Two rows are done for you.

A: double charged on an invoice = (0.96, 0.28)0.96 × 0.6 + 0.28 × 0.8 = 0.576 + 0.224 = 0.800
B: connection pool exhausted = (0.28, 0.96)
C: payment gateway is down = (0.80, 0.60)
Which ticket should the search show first?
Check your answers
A: double charged on an invoice = (0.96, 0.28)0.800. Mostly money words, so it points away from Q.
B: connection pool exhausted = (0.28, 0.96)0.28 × 0.6 + 0.96 × 0.8 = 0.168 + 0.768 = 0.936.
C: payment gateway is down = (0.80, 0.60)0.80 × 0.6 + 0.60 × 0.8 = 0.480 + 0.480 = 0.960.
Which ticket should the search show first?C, with 0.960, then B with 0.936, then A with 0.800.

Surprised that C beats B? C is about a machine (a gateway) and about money, and Q's arrow sits between both. A good search does not match topics; it matches direction. If you got 0.936 and 0.960, you can already run the real thing.

Here is the same check as a program. Run it and compare with your pencil.

Step-by-step: what toy_cosine.py does, in plain English
  1. Import numpy, the library for lists of numbers.
  2. Make the query arrow Q as a two-number array, (0.6, 0.8).
  3. Make a dictionary of three tickets, each with its own two-number arrow.
  4. Loop over the tickets. For each, np.linalg.norm gives the arrow's length (should be 1.00).
  5. query @ vec is the dot product: multiply matching numbers and add. That is the score.
  6. Print the ticket name, its length and its score, to three decimal places.
toy_cosine.pyruns offline
# pip install "numpy>=2.5,<2.6"
"""Search by meaning in two dimensions, small enough for a pencil.
Axis 1 = "money words", axis 2 = "machine words". Every arrow has length 1."""
import numpy as np

query = np.array([0.6, 0.8])  # "database keeps timing out"
tickets = {
    "A double charged on an invoice": np.array([0.96, 0.28]),
    "B connection pool exhausted": np.array([0.28, 0.96]),
    "C payment gateway is down": np.array([0.80, 0.60]),
}

for name, vec in tickets.items():
    print(f"{name:32} length {np.linalg.norm(vec):.2f}  score {query @ vec:.3f}")
output
A double charged on an invoice   length 1.00  score 0.800
B connection pool exhausted      length 1.00  score 0.936
C payment gateway is down        length 1.00  score 0.960
money words → machine words ↑ B pool exhausted 1 Q database timing out 2 C payment gateway down A double charged 3 SCORE = Q · ticket A 0.96×0.6 + 0.28×0.8 = 0.800 B 0.28×0.6 + 0.96×0.8 = 0.936 C 0.80×0.6 + 0.60×0.8 = 0.960 every arrow has length 1.00, so only direction matters
Fig. 5b.2 — The new ticket Q and three solved tickets as arrows of length 1. The winner is the arrow closest in direction to Q, not the one with the same topic word.
  1. Q, the new ticket. Its arrow is (0.6, 0.8): a little money, mostly machines. Every other arrow is compared against this one.
  2. C, the closest direction. (0.80, 0.60) is only a small turn away from Q, so its score is 0.960, the highest. A payment gateway is a machine that handles money, so it sits between the two axes like Q does.
  3. The score list. Each score is Q's first number times the ticket's first number, plus the same for the second. A 1.000 would mean "exactly the same direction". Here C at 0.960 beats B at 0.936 by a hair and A at 0.800 by a lot.

Where the arrows come from: words counted, or meaning learned

Maya's agents do not type arrows. They type "prod Postgres cluster throwing 500s and timing out". We need a function that turns that sentence into an arrow. Module 05 already showed one answer (count the words). The module also showed why it fails. Let us see how it fails on this exact ticket.

The offline fallback is TF-IDF (term frequency times inverse document frequency: a score that favours words which are common in one ticket and rare across all tickets). Each known word is one axis. A ticket becomes an arrow over thousands of axes, usually only a few non-zero. Module 05 covers the idea in full; here it is a tool.

Step-by-step: what why_tfidf_misses.py does, in plain English
  1. Build a TF-IDF vectoriser over the 25 past ticket texts (words and two-word pairs; word counts are damped with sublinear_tf).
  2. Turn the outage query into an arrow and list which of its words the vocabulary knows at all.
  3. For tickets 122, 121 and 109, turn the ticket into an arrow too.
  4. Multiply the query and ticket arrows axis by axis. Any axis that survives is a shared word; print it with its contribution.
  5. Add the contributions. That sum is the cosine score the search used.
why_tfidf_misses.pyruns offline
"""Which words made TF-IDF pick the wrong tickets for the outage query?
Runs offline: python why_tfidf_misses.py"""
from sklearn.feature_extraction.text import TfidfVectorizer

from tickets import PAST_TICKETS

query = "prod Postgres cluster throwing 500s and timing out"
texts = [t for _, _, t, _ in PAST_TICKETS]
vec = TfidfVectorizer(ngram_range=(1, 2), sublinear_tf=True).fit(texts)
names = vec.get_feature_names_out()
q = vec.transform([query]).toarray()[0]
print("query words the vocabulary knows:", [names[i] for i in q.nonzero()[0]])
print(f"query words in total: {len(query.split())}, known to the vocabulary: {len(q.nonzero()[0])}")

for tid in (122, 121, 109):
    row = vec.transform([next(t for i, _, t, _ in PAST_TICKETS if i == tid)]).toarray()[0]
    shared = [(names[i], round(float(q[i] * row[i]), 4)) for i in (q * row).nonzero()[0]]
    print(f"#{tid} shares {shared} -> cosine {sum(s for _, s in shared):.4f}")
output
query words the vocabulary knows: ['and', 'out']
query words in total: 8, known to the vocabulary: 2
#122 shares [('out', 0.1752)] -> cosine 0.1752
#121 shares [('and', 0.155)] -> cosine 0.1550
#109 shares [] -> cosine 0.0000

Read the output. Of the query's 8 words, the index knows only two: "and" and "out". "Postgres", "cluster", "throwing" and "timing" never appear in the 25 tickets, so they vanish. The top hit, ticket 122, is about a locked-out phone number. It matched on the word "out". Ticket 109, the real database ticket, shares nothing and scores zero.

The fix is a model that maps text to arrows by meaning. MiniLM (all-MiniLM-L6-v2, a small sentence-embedding model from the sentence-transformers library, about 22 million parameters) turns any sentence into 384 numbers. Sentences that mean similar things get arrows that point the same way, even with no shared words. Module 08 covers embeddings and vector stores in depth.

Step-by-step: what search_backends.py does, in plain English
  1. Set HF_HUB_OFFLINE=1 so the library uses the cached model and never reaches for the network.
  2. Import build_index from the API rung that supports both backends, and the ticket list.
  3. Define three queries: the outage one, a locked-out-after-new-phone one, and a "money taken twice" one.
  4. For each backend, tfidf then minilm, build the index (this loads the model once).
  5. For each query, multiply the ticket matrix by the query arrow to get one score per ticket, sort, and print the top two ids with scores.
search_backends.pyruns offline (needs the cached MiniLM model)
"""Same queries, two search backends: TF-IDF words vs MiniLM meaning.
Loads the sentence-transformers model once. Offline: needs all-MiniLM-L6-v2 cached
(run it once with internet, or: HF_HUB_OFFLINE=1 python search_backends.py)."""
import os

os.environ.setdefault("HF_HUB_OFFLINE", "1")  # never reach for the network

from app_4_minilm import build_index  # noqa: E402
from tickets import PAST_TICKETS  # noqa: E402

QUERIES = [
    "prod Postgres cluster throwing 500s and timing out",
    "customer cannot get into the portal after swapping phones",
    "money taken twice from my card",
]

for backend in ("tfidf", "minilm"):
    encode, matrix = build_index(backend)
    print(f"--- {backend}")
    for q in QUERIES:
        scores = matrix @ encode([q])[0]
        best = scores.argsort()[::-1][:2]
        shown = ", ".join(f"#{PAST_TICKETS[i][0]} ({scores[i]:.3f})" for i in best)
        print(f"{q[:52]:52} -> {shown}")
output
--- tfidf
prod Postgres cluster throwing 500s and timing out   -> #122 (0.175), #121 (0.155)
customer cannot get into the portal after swapping p -> #114 (0.181), #122 (0.168)
money taken twice from my card                       -> #102 (0.324), #107 (0.132)
--- minilm
prod Postgres cluster throwing 500s and timing out   -> #112 (0.331), #109 (0.295)
customer cannot get into the portal after swapping p -> #122 (0.497), #125 (0.322)
money taken twice from my card                       -> #102 (0.556), #106 (0.475)
query: prod Postgres cluster throwing 500s and timing out 1 TF-IDF: counts shared words #122 Account 0.175 #121 Account 0.155 shares only "out" and "and" the words that matter are unknown 2 MiniLM: compares meaning #112 Technical 0.331 #109 Technical 0.295 both top hits are outages (Technical) no shared word needed 3 0.175 and 0.331 cannot be compared: each model has its own scale
Fig. 5b.3 — The same outage query through two backends. TF-IDF returns two Account tickets; MiniLM returns two Technical tickets, including the real database ticket #109.
  1. TF-IDF's top two. Tickets 122 (0.175) and 121 (0.155) are both Account tickets. They win by sharing one common word each ("out" and "and"). An agent who clicked them would be reading about a phone number and a GDPR export.
  2. MiniLM's top two. Tickets 112 (0.331, a container killed for memory) and 109 (0.295, a database pool exhausted) are both Technical. Neither shares a word with the query beyond common ones. MiniLM saw "cluster, timing out, 500s" and found tickets about servers failing.
  3. The scale warning. A score is only meaningful inside one backend. Do not set a rule like "show hits above 0.3" and then swap the backend. Re-measure the cut-off on your own tickets after any swap.

Honesty check. MiniLM is not perfect here: it put the memory ticket (112) above the database ticket (109), and its best score is only 0.331. It got the family right (Technical) on all three queries; TF-IDF got it right only on the money query. For a prototype that is the difference between a demo and an apology.

"Isn't this just Elasticsearch with extra steps? I have shipped search before."

— a nine-year engineer, right about now

Half of it is exactly that. You have an index, a query, a ranked list, a top-k. The new half is how the index is built: instead of tokenising and weighting words, a model turns each ticket into a fixed-length list of numbers, and ranking is arrow comparison. Elasticsearch can store those arrows too, so the two are not rivals.

The honest downside: keyword search is better when the user types an exact error code or an order number, because meaning-search blurs exact strings. Production systems often run both and merge the lists. Module 08 builds that hybrid.

The math behind the score: cosine similarity (optional depth)

For two arrows a and b, the angle between them is found from cos θ = (a·b) / (‖a‖ ‖b‖). The top is the dot product: Σ aᵢbᵢ, multiplying matching coordinates and adding. The bottom is the two arrows' lengths multiplied.

Symbol key: θ (theta) is the angle between the arrows; cos θ (cosine of theta) is 1 when the angle is 0 and 0 at a right angle; a·b is the dot product; ‖a‖ is the length of a, which is √(a₁² + a₂² + …); Σ (sigma) means "add up over every coordinate"; aᵢ (a-sub-i) is the i-th coordinate.

If both arrows have length 1, the bottom is 1 × 1 = 1 and cosine equals the dot product. That is why the code asks for normalize_embeddings=True and why TF-IDF rows are already unit length: the search is then one matrix-times-vector product. For Q and C: (0.6 × 0.80) + (0.8 × 0.60) = 0.960, so θ = arccos(0.960) ≈ 16.3°.

Streaming by event: what actually goes over the wire

Search is solved enough for a demo. The second half of Maya's ask is the reply that types itself. A real model needs several seconds to finish a reply, and a blank button for several seconds looks broken. The fix is to send the reply in small pieces as they are made. Here is what a piece looks like.

Server-Sent Events (SSE) is a plain-text format for sending many messages over one open HTTP response. Each message is a few lines of name: value, and a blank line ends the message. The response has the content type text/event-stream. That is the whole format. No new protocol, no upgrade handshake.

1 ON THE WIRE event: token data: {"text": "Hi, "} (blank line) event: token data: {"text": "thanks "} (blank line) event: done data: {"tokens": 45} (blank line) split at blank line 2 THREE EVENTS token {text: "Hi, "} token {text: "thanks "} done {tokens: 45} append 3 REACT STATE reply = "Hi, thanks " 45 words in the reply, so 45 token events, then one done event that carries the count
Fig. 5b.4 — What an SSE reply looks like: plain text lines, cut at blank lines into events, each token event appended to the reply the screen shows.
  1. The wire. Every message is an event: line plus a data: line, then a blank line. The data here is JSON, so a word with a trailing space, like "Hi, ", survives intact. These exact lines came from our running server.
  2. Events. The browser code cuts the incoming text at each blank line. Each piece becomes one event with a name (token, done) and a decoded payload.
  3. State. The page keeps a string called reply. Each token event appends its text. After two events the screen shows "Hi, thanks ", and it grows until the done event arrives.

Compare this with what you may already use. A normal response is one blob sent when the server finishes. A WebSocket is a different protocol, with its own handshake, where both sides send freely. SSE is the lightweight middle: still HTTP, one direction (server to browser), and every proxy and load balancer already knows how to carry it. For "the model talks, the user watches" it is the standard choice. The stack table later in this module lists when to pick WebSockets instead.

Embedding
A fixed-length list of numbers (an arrow) that represents a piece of text.
Dot product
Multiply matching numbers, add the results. For length-1 arrows it equals cosine similarity.
Score
A rank, not a probability. Scales differ per model; never reuse a cut-off after swapping models.
TF-IDF
Word-counting arrows. Offline, instant, blind to words it never saw.
MiniLM
all-MiniLM-L6-v2, 384 numbers per text, learns meaning, needs a cached model.
SSE
Plain-text events over one HTTP response, content type text/event-stream, a blank line ends an event.
Why JSON in data:
Words carry spaces and newlines; JSON keeps them exact.

04 · Build the APIFastAPI in Seven Small Chunks

The API is a Python file that turns an HTTP request into a checked Python object, runs the search or the model, and turns the result back into JSON or a stream. We build it one runnable chunk at a time.

We know the two ideas now: rank by arrow direction, and send the reply as events. The next event in Maya's 48 hours is the API that offers both to a browser. We build it from the smallest possible server upward, so that at every step something runs and you can see what changed.

What FastAPI and Pydantic give you

FastAPI is a Python web framework where you write a function and attach a route to it with a decorator. The function's type hints are not decoration. FastAPI reads them to decide how to parse the request, how to validate it and how to describe the endpoint in an auto-generated documentation page.

Pydantic is the library that does the checking. You describe a shape as a class (query: str, k: int), and Pydantic refuses any input that does not fit, with a clear error. If you have used Java Bean Validation or a TypeScript schema library, it is the same job. The difference is that here one class is the request object, the validator and the documentation at once.

The next block is the whole finished API, shown before you have built it. You are not expected to understand every line yet. Guess first, then read the answers; each line is rebuilt slowly in the seven chunks right after.

Sharpen your pencil

Below are ten lines lifted from app.py (the finished file, shown in full after the seven chunks). Three are annotated for you. In the blank rows, write what you think each line does, in plain English, before you open the answers.

query: str = Field(min_length=2, max_length=300)The request must carry a text field called query, 2 to 300 characters long; anything else is rejected.
k: int = Field(default=3, ge=1, le=10)An optional whole number k, 3 if missing, never below 1 or above 10.
@app.post("/search", response_model=SearchResponse)Attach the function below to POST /search and shape its return value like SearchResponse.
scores = MATRIX @ ENCODE([query])[0]
best = scores.argsort()[::-1][:k]
... for i in best if scores[i] > 0]
@app.post("/suggest", response_class=EventSourceResponse)
yield ServerSentEvent(event="token", data={"text": piece})
yield ServerSentEvent(event="done", data={"tokens": count})
allow_origins=ORIGINS
Check your answers
query: str = Field(min_length=2, max_length=300)The request must carry a text field called query, 2 to 300 characters long; anything else is rejected.
k: int = Field(default=3, ge=1, le=10)An optional whole number k, 3 if missing, never below 1 or above 10.
@app.post("/search", response_model=SearchResponse)Attach the function below to POST /search and shape its return value like SearchResponse.
scores = MATRIX @ ENCODE([query])[0]Turn the query into an arrow, then score all 25 tickets at once: the matrix has one row per ticket, and the dot product gives one number per ticket.
best = scores.argsort()[::-1][:k]argsort gives ticket positions from lowest to highest score; [::-1] flips that to highest first; [:k] keeps the first k.
... for i in best if scores[i] > 0]Build a hit only for tickets that scored above zero, so a query with no overlap returns an empty list instead of nonsense.
@app.post("/suggest", response_class=EventSourceResponse)POST /suggest answers as text/event-stream: the function below is a generator whose every yield becomes one event on the wire.
yield ServerSentEvent(event="token", data={"text": piece})Send one event named token whose JSON data holds one piece of the reply, for example "Hi, ".
yield ServerSentEvent(event="done", data={"tokens": count})Send the final event, which tells the browser the stream is complete and how many tokens were sent.
allow_origins=ORIGINSTell the CORS middleware which web page addresses may read our replies; by default only http://localhost:5173.

If you got the search lines right you already read Python plus NumPy; if the yield lines made sense, you have the streaming idea. Both are taken slowly below.

CORS: the wall that only the browser sees

The sharpen exercise ended on allow_origins. That is the line that decides whether the demo works the first time you open it, so we explain it before building. It is the very first error a backend engineer meets when they add a browser page.

A page loaded from http://localhost:5173 is allowed to talk to its own origin freely. An origin is scheme plus host plus port. Our API runs on port 8000, so it is a different origin. By default the browser lets the page send the request but refuses to hand the reply to the page's JavaScript, unless the server says "that origin is allowed".

This is CORS, cross-origin resource sharing. The key fact for debugging: curl and your tests never hit it, because only browsers enforce it. The server sees a perfectly normal request. The failure is the browser throwing the reply away.

page at :5173 API at :8000 1 OPTIONS /search Origin: http://localhost:5173 2 200 OK access-control-allow-origin: http://localhost:5173 3 POST /search (the real request) 4 200 + JSON hits wrong origin: no allow-origin header, so the browser discards the reply
Fig. 5b.5 — A browser asks permission first (the preflight), then sends the real request. The API's answer to the preflight is the whole CORS decision.
  1. The preflight question. Because our request has a JSON body and a custom Content-Type, the browser first sends OPTIONS, naming the page's origin. No data moves yet.
  2. The permission slip. The API answers with access-control-allow-origin: http://localhost:5173. We measured this on our running server: status 200 and that exact header. A request from http://evil.example got 400 Bad Request and no allow-origin header.
  3. The real request. Only after the slip does the browser send the POST. It also costs one extra round trip, so the server caches the answer: access-control-max-age: 600 seconds.
  4. The reply. The JSON arrives and the page's code may read it. If the allow-origin header is missing or names another origin, the browser hides the reply and the console prints a CORS error, while the server log shows a happy 200.

The CORS fix is three settings: which origins (never "*" with credentials), which methods, which headers. We read the origin list from an environment variable, so the deployed demo adds its real address without a code change.

Build it in chunks

We build app.py in seven chunks. Each chunk is saved as its own runnable file (app_1_hello.py to app_7_cors.py) in code/05b-fullstack-ai-apps/backend/. Every check below was run, and the whole file comes after the seventh chunk.

  1. Chunk 1 — a server that answers one question

    We start with the smallest thing that is still an API, so that every later chunk has something to stand on. A health endpoint is also what a load balancer and your demo-day panic check both call.

    Step-by-step: what chunk 1 does, in plain English
    1. Import the FastAPI class.
    2. Create the app object. Everything else attaches to it.
    3. @app.get("/health") registers the function below it for GET requests to /health.
    4. The function returns a dict; FastAPI turns it into JSON.
    app_1_hello.pyruns offline
    # pip install "fastapi>=0.141,<1" "uvicorn>=0.30"
    from fastapi import FastAPI
    
    app = FastAPI(title="HelpDeskAI search")
    
    
    @app.get("/health")
    def health() -> dict:
        return {"status": "ok"}

    @app.get(path) — a decorator that attaches a function to a URL and an HTTP method.

    python rung_checks.py prints rung 1 /health -> {'status': 'ok'}. To see it live: uvicorn app_1_hello:app --port 8000, then curl localhost:8000/health.

  2. Chunk 2 — describe the request and the response with Pydantic

    Before any AI, fix the contract: what may come in, what goes out. A stub returns the first tickets so the browser team can start work against a real shape while the search is still unwritten.

    Step-by-step: what chunk 2 adds, in plain English
    1. SearchRequest says a request needs query (2 to 300 characters) and may carry k (1 to 10, default 3).
    2. Hit is one search result: id, category, text, resolution, score.
    3. SearchResponse wraps the query, the backend's name and a list of hits.
    4. The /search endpoint takes a SearchRequest. FastAPI parses the JSON body for us and answers 422 if it does not fit.
    5. The stub builds hits from the first k tickets with score 0, and names the backend "stub".
    app_2_models.py (added to chunk 1; also needs the import lines at the top of the file)runs offline
    from fastapi import FastAPI
    from pydantic import BaseModel, Field
    
    from tickets import PAST_TICKETS
    
    class SearchRequest(BaseModel):
        query: str = Field(min_length=2, max_length=300)
        k: int = Field(default=3, ge=1, le=10)
    
    
    class Hit(BaseModel):
        id: int
        category: str
        text: str
        resolution: str
        score: float
    
    
    class SearchResponse(BaseModel):
        query: str
        backend: str
        hits: list[Hit]
    
    @app.post("/search", response_model=SearchResponse)
    def search(req: SearchRequest) -> SearchResponse:
        # Placeholder: the first k tickets with score 0. Chunk 3 makes it real.
        hits = [Hit(id=i, category=c, text=t, resolution=r, score=0.0)
                for i, c, t, r in PAST_TICKETS[: req.k]]
        return SearchResponse(query=req.query, backend="stub", hits=hits)

    BaseModel and Field(...) — a Pydantic class whose type hints are enforced, with limits such as min_length and ge (greater or equal).

    python rung_checks.py prints rung 2 /search -> 200 [101, 102] stub, then rung 2 bad input -> 422 String should have at least 2 characters.

  3. Chunk 3 — real search with TF-IDF, offline

    Now the stub becomes real, using the fallback that needs no model download. We build the index once when the server starts, then each request is one matrix-times-vector product.

    Step-by-step: what chunk 3 adds, in plain English
    1. build_index() collects the 25 ticket texts and fits a TF-IDF vectoriser on them.
    2. It returns two things: an encode function (text to arrows) and the matrix of all 25 ticket arrows.
    3. ENCODE, MATRIX = build_index() runs once at import time, not per request, so a request does not re-train anything.
    4. top_hits() encodes the query, multiplies the matrix by it (25 scores), sorts, keeps the best k and drops zero scores.
    5. The /search endpoint now calls top_hits() and reports the backend as "tfidf". This replaces chunk 2's stub body.
    app_3_search.py (chunk 3 lines; the stub search from chunk 2 is replaced)runs offline
    def build_index():
        """Return (encode, matrix): encode(list[str]) -> unit-length vectors."""
        from sklearn.feature_extraction.text import TfidfVectorizer
        texts = [t for _, _, t, _ in PAST_TICKETS]
        vec = TfidfVectorizer(ngram_range=(1, 2), sublinear_tf=True).fit(texts)
        encode = lambda xs: vec.transform(xs).toarray()  # rows are unit length
        return encode, encode(texts)
    
    
    ENCODE, MATRIX = build_index()  # built once at start-up, not per request
    
    def top_hits(query: str, k: int) -> list[Hit]:
        scores = MATRIX @ ENCODE([query])[0]  # dot of unit vectors = cosine
        best = scores.argsort()[::-1][:k]  # indices of the k best, best first
        return [Hit(id=PAST_TICKETS[i][0], category=PAST_TICKETS[i][1],
                    text=PAST_TICKETS[i][2], resolution=PAST_TICKETS[i][3],
                    score=round(float(scores[i]), 4)) for i in best if scores[i] > 0]  # drop zero-overlap
    
    
    @app.post("/search", response_model=SearchResponse)
    def search(req: SearchRequest) -> SearchResponse:
        return SearchResponse(query=req.query, backend="tfidf",
                              hits=top_hits(req.query, req.k))

    MATRIX @ vector — NumPy's matrix-times-vector: one dot product per row, all at once. argsort returns positions in score order.

    python rung_checks.py prints rung 3 /search -> tfidf [(122, 0.1752), (121, 0.155)] for the outage query, then rung 3 no overlap -> [] for "zzzz qqqq". The first line is the wrong answer from Fig. 5b.3; chunk 4 fixes it.

  4. Chunk 4 — a switch for real embeddings (MiniLM), with the offline fallback kept

    Chunk 3 proved the plumbing. Chunk 4 swaps in a better brain without touching the endpoint. The environment variable keeps the offline path alive for tests and for laptops without the model cached.

    Step-by-step: what chunk 4 changes, in plain English
    1. Read SEARCH_BACKEND from the environment, defaulting to "tfidf".
    2. build_index(backend) now takes the name. If it is "minilm", it imports sentence_transformers late, loads all-MiniLM-L6-v2 and encodes text with normalize_embeddings=True so every arrow has length 1.
    3. Otherwise it builds the same TF-IDF encoder as chunk 3.
    4. The index is built from BACKEND, and the response reports that name instead of the fixed "tfidf".
    app_4_minilm.py (changed and added lines)runs offline (MiniLM path needs the cached model)
    import os
    
    BACKEND = os.environ.get("SEARCH_BACKEND", "tfidf")  # "tfidf" or "minilm"
    
    def build_index(backend: str):
        """Return (encode, matrix): encode(list[str]) -> unit-length vectors."""
        texts = [t for _, _, t, _ in PAST_TICKETS]
        if backend == "minilm":  # real embeddings, meaning-aware (needs the model cached)
            from sentence_transformers import SentenceTransformer
            model = SentenceTransformer("all-MiniLM-L6-v2")
            encode = lambda xs: model.encode(xs, normalize_embeddings=True)
        else:  # offline fallback: word counts, no model, deterministic
            from sklearn.feature_extraction.text import TfidfVectorizer
            vec = TfidfVectorizer(ngram_range=(1, 2), sublinear_tf=True).fit(texts)
            encode = lambda xs: vec.transform(xs).toarray()  # rows are unit length
        return encode, encode(texts)
    
    
    ENCODE, MATRIX = build_index(BACKEND)  # built once at start-up, not per request
    
    @app.post("/search", response_model=SearchResponse)
    def search(req: SearchRequest) -> SearchResponse:
        return SearchResponse(query=req.query, backend=BACKEND,
                              hits=top_hits(req.query, req.k))

    SentenceTransformer(name).encode(texts, normalize_embeddings=True) — text in, unit-length arrows out. The import sits inside the branch so the offline path never loads the 1 to 2 GB of PyTorch.

    HF_HUB_OFFLINE=1 python search_backends.py prints the two blocks you saw in the output above: for the outage query, tfidf gives #122 (0.175), #121 (0.155) and minilm gives #112 (0.331), #109 (0.295). python rung_checks.py prints rung 4 default backend -> tfidf.

  5. Chunk 5 — stream a suggested reply with Server-Sent Events (offline fake model)

    The reply street. We write a fake model with the same interface a real one has: a generator that hands out words one at a time. The endpoint does not know or care which is behind it.

    Step-by-step: what chunk 5 adds, in plain English
    1. Two new imports: asyncio for sleep, and EventSourceResponse plus ServerSentEvent from fastapi.sse.
    2. SuggestRequest needs a ticket text of 2 to 2,000 characters.
    3. draft_reply() is the offline stand-in for an LLM: it rewrites the best past resolution as a polite reply, or hands over to a person if nothing similar was found.
    4. fake_stream() is an async generator: it yields the reply one word at a time and waits 20 ms between words.
    5. suggest() finds the top 3 similar tickets and yields a context event with their ids.
    6. It then yields one token event per word, counting them, and finishes with a done event holding the count.
    app_5_stream.py (added lines; plus two new imports at the top)runs offline
    import asyncio
    
    from fastapi.sse import EventSourceResponse, ServerSentEvent
    
    class SuggestRequest(BaseModel):
        ticket: str = Field(min_length=2, max_length=2000)
    
    
    def draft_reply(hits: list[Hit]) -> str:
        """Offline stand-in for an LLM: rewrite the best past resolution as a reply."""
        if not hits:  # nothing similar was found: hand over to a person
            return "Thanks for reaching out. We found no similar past ticket, so a person will pick this up."
        best = hits[0]
        fix = best.resolution[0].lower() + best.resolution[1:]
        return (f"Hi, thanks for reaching out. We have seen this before "
                f"(ticket #{best.id}, {best.category}). Last time we {fix} "
                f"Let us know if that does not fix it and we will dig deeper.")
    
    
    async def fake_stream(hits: list[Hit]):
        for word in draft_reply(hits).split(" "):
            yield word + " "
            await asyncio.sleep(0.02)  # pretend the model is thinking
    
    
    @app.post("/suggest", response_class=EventSourceResponse)
    async def suggest(req: SuggestRequest):
        hits = top_hits(req.ticket, 3)
        yield ServerSentEvent(event="context", data={"ids": [h.id for h in hits]})
        count = 0
        async for piece in fake_stream(hits):
            count += 1
            yield ServerSentEvent(event="token", data={"text": piece})
        yield ServerSentEvent(event="done", data={"tokens": count})

    async def with yield — an async generator. response_class=EventSourceResponse tells FastAPI (0.141 and later) to send each yielded ServerSentEvent as one SSE message, with keep-alive pings.

    python rung_checks.py prints rung 5 /suggest -> 47 events; first 3 and last: then the lines event: context / data: {"ids": [101, 108, 105]}, two token events ("Hi, ", "thanks ") and finally event: done / data: {"tokens": 45}. 47 events = 1 context + 45 tokens + 1 done.

  6. Chunk 6 — the real LLM behind the same stream (needs API key)

    A demo with a fake model is honest only if the real one can plug into the same hole. The real function is also an async generator, so suggest() only needs a switch. This chunk needs an Anthropic key; we did not run it in this course build.

    Step-by-step: what chunk 6 adds, in plain English
    1. claude_stream() imports AsyncAnthropic late, so offline runs do not need the SDK installed.
    2. It creates a client (the key comes from ANTHROPIC_API_KEY) and writes a prompt: the new ticket plus the similar solved tickets with their resolutions.
    3. client.messages.stream(...) opens a streaming call; the model id comes from ANTHROPIC_MODEL, defaulting to claude-sonnet-5. Check the current model list before relying on that default.
    4. async for text in stream.text_stream yields each piece of text as it arrives.
    5. In suggest(), LLM=claude picks claude_stream; otherwise the fake streamer runs. The rest of the endpoint is unchanged.
    app_6_claude.py (added lines)needs API key
    async def claude_stream(ticket: str, hits: list[Hit]):
        """Real LLM path. needs API key (ANTHROPIC_API_KEY); not run in this course build."""
        from anthropic import AsyncAnthropic  # imported late so offline runs need no SDK
        client = AsyncAnthropic()  # reads ANTHROPIC_API_KEY from the environment
        past = "\n".join(f"- #{h.id}: {h.text} -> {h.resolution}" for h in hits)
        prompt = (f"New support ticket:\n{ticket}\n\nSimilar solved tickets:\n{past}\n\n"
                  "Write a short, polite reply to the customer using what worked before.")
        async with client.messages.stream(
            model=os.environ.get("ANTHROPIC_MODEL", "claude-sonnet-5"),
            max_tokens=400,
            messages=[{"role": "user", "content": prompt}],
        ) as stream:
            async for text in stream.text_stream:
                yield text
    
    
    
    @app.post("/suggest", response_class=EventSourceResponse)
    async def suggest(req: SuggestRequest):
        hits = top_hits(req.ticket, 3)
        yield ServerSentEvent(event="context", data={"ids": [h.id for h in hits]})
        count = 0
        if os.environ.get("LLM") == "claude":
            source = claude_stream(req.ticket, hits)
        else:
            source = fake_stream(hits)
        async for piece in source:

    client.messages.stream() and stream.text_stream — the Messages API's streaming helper. Module 06 teaches the SDK itself; here it is a plug.

    python rung_checks.py prints rung 6 claude_stream is function (needs API key to run), which proves it imports and is wired. With a key, LLM=claude uvicorn app_6_claude:app streams real text with the identical event format. Not run here: no API key in this environment.

  7. Chunk 7 — CORS, so the browser may read the replies

    Last, the permission slip from Fig. 5b.5. Four lines, and the difference between "works in curl" and "works on the page".

    Step-by-step: what chunk 7 adds, in plain English
    1. Import CORSMiddleware.
    2. Read CORS_ORIGINS from the environment (comma-separated), defaulting to the Vite dev address.
    3. app.add_middleware wraps every response: it answers preflight OPTIONS requests and adds access-control-allow-origin for listed origins only.
    4. Only GET and POST, and only the Content-Type header, are allowed: the smallest list that works.
    app_7_cors.py (added lines)runs offline
    from fastapi.middleware.cors import CORSMiddleware
    
    ORIGINS = os.environ.get("CORS_ORIGINS", "http://localhost:5173").split(",")
    
    app.add_middleware(CORSMiddleware, allow_origins=ORIGINS,
                       allow_methods=["GET", "POST"], allow_headers=["Content-Type"])

    CORSMiddleware — Starlette's CORS handler. Middleware sits around every route, so no endpoint needs to know about it.

    python rung_checks.py prints rung 7 preflight -> 200 http://localhost:5173. The same OPTIONS request from http://evil.example gets no allow-origin header.

The whole program

Chunk 1 is the imports and the /health route. Chunk 2 is the three Pydantic classes. Chunks 3 and 4 are the block from BACKEND to /search (chunk 4 turned build_index into a switch). Chunk 5 is the first half of the suggest block, chunk 6 inserts claude_stream and the choice inside suggest(), and chunk 7 is the four CORS lines near the top. Each chunk starts with a # ── chunk n ── comment.

app.pyruns offlineLLM=claude needs API key
# pip install "fastapi>=0.141,<1" "uvicorn>=0.30" "scikit-learn>=1.5,<2"
# optional: pip install "sentence-transformers>=5,<7"   (for SEARCH_BACKEND=minilm)
# ── chunk 1: a FastAPI app with one endpoint ──
import asyncio
import os

from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware  # chunk 7
from fastapi.sse import EventSourceResponse, ServerSentEvent
from pydantic import BaseModel, Field

from tickets import PAST_TICKETS

# ── chunk 7: CORS, so the browser on :5173 may call :8000 ──
ORIGINS = os.environ.get("CORS_ORIGINS", "http://localhost:5173").split(",")
app = FastAPI(title="HelpDeskAI search")
app.add_middleware(CORSMiddleware, allow_origins=ORIGINS,
                   allow_methods=["GET", "POST"], allow_headers=["Content-Type"])


@app.get("/health")
def health() -> dict:
    return {"status": "ok"}


# ── chunk 2: request and response models ──
class SearchRequest(BaseModel):
    query: str = Field(min_length=2, max_length=300)
    k: int = Field(default=3, ge=1, le=10)


class Hit(BaseModel):
    id: int
    category: str
    text: str
    resolution: str
    score: float


class SearchResponse(BaseModel):
    query: str
    backend: str
    hits: list[Hit]


# ── chunk 3 (TF-IDF) and chunk 4 (the MiniLM branch): search by similarity ──
BACKEND = os.environ.get("SEARCH_BACKEND", "tfidf")  # "tfidf" or "minilm"


def build_index(backend: str):
    """Return (encode, matrix): encode(list[str]) -> unit-length vectors."""
    texts = [t for _, _, t, _ in PAST_TICKETS]
    if backend == "minilm":  # real embeddings, meaning-aware (needs the model cached)
        from sentence_transformers import SentenceTransformer
        model = SentenceTransformer("all-MiniLM-L6-v2")
        encode = lambda xs: model.encode(xs, normalize_embeddings=True)
    else:  # offline fallback: word counts, no model, deterministic
        from sklearn.feature_extraction.text import TfidfVectorizer
        vec = TfidfVectorizer(ngram_range=(1, 2), sublinear_tf=True).fit(texts)
        encode = lambda xs: vec.transform(xs).toarray()  # rows are unit length
    return encode, encode(texts)


ENCODE, MATRIX = build_index(BACKEND)  # built once at start-up, not per request


def top_hits(query: str, k: int) -> list[Hit]:
    scores = MATRIX @ ENCODE([query])[0]  # dot of unit vectors = cosine
    best = scores.argsort()[::-1][:k]  # indices of the k best, best first
    return [Hit(id=PAST_TICKETS[i][0], category=PAST_TICKETS[i][1],
                text=PAST_TICKETS[i][2], resolution=PAST_TICKETS[i][3],
                score=round(float(scores[i]), 4)) for i in best if scores[i] > 0]  # drop zero-overlap


@app.post("/search", response_model=SearchResponse)
def search(req: SearchRequest) -> SearchResponse:
    return SearchResponse(query=req.query, backend=BACKEND,
                          hits=top_hits(req.query, req.k))


# ── chunk 5: stream a suggested reply with Server-Sent Events ──
class SuggestRequest(BaseModel):
    ticket: str = Field(min_length=2, max_length=2000)


def draft_reply(hits: list[Hit]) -> str:
    """Offline stand-in for an LLM: rewrite the best past resolution as a reply."""
    if not hits:  # nothing similar was found: hand over to a person
        return "Thanks for reaching out. We found no similar past ticket, so a person will pick this up."
    best = hits[0]
    fix = best.resolution[0].lower() + best.resolution[1:]
    return (f"Hi, thanks for reaching out. We have seen this before "
            f"(ticket #{best.id}, {best.category}). Last time we {fix} "
            f"Let us know if that does not fix it and we will dig deeper.")


# ── chunk 6: the real LLM, next to the fake one ──
async def claude_stream(ticket: str, hits: list[Hit]):
    """Real LLM path. needs API key (ANTHROPIC_API_KEY); not run in this course build."""
    from anthropic import AsyncAnthropic  # imported late so offline runs need no SDK
    client = AsyncAnthropic()  # reads ANTHROPIC_API_KEY from the environment
    past = "\n".join(f"- #{h.id}: {h.text} -> {h.resolution}" for h in hits)
    prompt = (f"New support ticket:\n{ticket}\n\nSimilar solved tickets:\n{past}\n\n"
              "Write a short, polite reply to the customer using what worked before.")
    async with client.messages.stream(
        model=os.environ.get("ANTHROPIC_MODEL", "claude-sonnet-5"),
        max_tokens=400,
        messages=[{"role": "user", "content": prompt}],
    ) as stream:
        async for text in stream.text_stream:
            yield text


async def fake_stream(hits: list[Hit]):
    for word in draft_reply(hits).split(" "):
        yield word + " "
        await asyncio.sleep(0.02)  # pretend the model is thinking


@app.post("/suggest", response_class=EventSourceResponse)
async def suggest(req: SuggestRequest):
    hits = top_hits(req.ticket, 3)
    yield ServerSentEvent(event="context", data={"ids": [h.id for h in hits]})
    count = 0
    if os.environ.get("LLM") == "claude":
        source = claude_stream(req.ticket, hits)
    else:
        source = fake_stream(hits)
    async for piece in source:
        count += 1
        yield ServerSentEvent(event="token", data={"text": piece})
    yield ServerSentEvent(event="done", data={"tokens": count})

The seven chunks are in one file now. Before we test it, follow a single request through the finished program, with the real values from our outage query, so you can see where each line of app.py takes part.

1 2 3 4 5 JSON body 8-word query k = 2 SearchRequest 2 to 300 chars: ok k in 1 to 10: ok ENCODE 8 words in 2 known: and, out MATRIX @ q 25 scores 2 above zero top_hits(k=2) #122 0.1752 #121 0.1550 too short, or k = 99? 422 + message the whole HTTP call took 22 ms, measured with curl on this laptop
Fig. 5b.6 — One /search request through the finished app.py, with the real values from the outage query.
  1. The body. The browser sends the query text and k. Nothing has been checked yet.
  2. The check. Pydantic compares the body with SearchRequest. A 1-character query or k of 99 stops here with a 422 and a plain message, and the search code never runs.
  3. Encode. The query becomes an arrow. Of its 8 words only "and" and "out" are in the ticket vocabulary, so only those two axes are non-zero.
  4. Score. One matrix-times-vector call gives 25 scores, one per past ticket. Only 2 tickets share a word with the query, so only 2 scores are above zero.
  5. Pick. The best 2 scores become Hit objects: tickets 122 (0.1752) and 121 (0.1550), the wrong-family answer that MiniLM later corrects.

That was the search street. The reply street has a design choice in it that is worth a picture of its own: the endpoint does not know whether the words come from a fake or a real model.

1 fake_stream 45 words, 20 ms each offline, always works 2 claude_stream Messages API text_stream needs API key pieces of text 3 suggest() async for piece in source LLM=claude picks the real one SSE browser 1 context, 45 token, 1 done event measured with the fake source: first byte after 4 ms, whole reply in 0.92 s
Fig. 5b.7 — Two sources of text, one endpoint. The browser sees the same event stream whichever source is behind it.
  1. The fake source. It rewrites the best past resolution as a reply and hands out 45 words, 20 ms apart, so a whole reply takes about 0.9 s. It needs nothing installed beyond the API itself.
  2. The real source. It builds a prompt from the new ticket and the similar solved tickets and yields whatever the Anthropic Messages stream produces. It needs an API key, and we did not run it in this course build.
  3. The endpoint. suggest() only loops over "pieces of text". Because both sources are async generators with the same shape, swapping them changes one line, and the 4 ms to first byte comes from streaming, not from which source was chosen.

Run it once with uvicorn app:app --port 8000 (from the backend folder) and open http://localhost:8000/docs. FastAPI has already written an interactive page listing /health, /search and /suggest, with the Pydantic limits shown as the schema. That page is free documentation for the frontend team, and a good thing to put on screen in a client demo.

Proof it works: the tests and a real end-to-end run

Seven chunks, each checked in isolation. Before anyone builds a screen on this, the demo needs a safety net: a small suite that fails loudly if a change breaks the contract. A day-two edit at 2 a.m. is exactly when you will want it.

FastAPI's TestClient (built on the httpx HTTP library) calls the app in-process: no port, no server. That makes tests fast and means they cannot clash with anything on your laptop. The streaming endpoint is tested by reading the event stream and checking its shape.

Step-by-step: what test_app.py does, in plain English
  1. Create one TestClient around the real app.
  2. parse_sse() splits a stream body at blank lines and turns each block into an (event name, JSON data) pair.
  3. The health test checks the JSON.
  4. The search test posts the database query and checks that ticket 109 is first and the scores are sorted.
  5. The no-overlap test checks that gibberish returns an empty list, not an error.
  6. The bad-input test posts a 1-character query and a k of 99, and expects 422 both times.
  7. The stream tests check the content type, the event order (context first, done last, token count equals the done count) and the hand-over message.
  8. The CORS test sends a preflight from the Vite origin (must be allowed) and from evil.example (must not).
test_app.pyruns offline
# pip install pytest httpx   (FastAPI's TestClient is built on httpx)
import json

from fastapi.testclient import TestClient

from app import app

client = TestClient(app)


def parse_sse(raw: str) -> list[tuple[str, dict]]:
    """Split a text/event-stream body into (event, data) pairs."""
    events = []
    for block in raw.strip().split("\n\n"):
        fields = dict(line.split(": ", 1) for line in block.splitlines() if ": " in line)
        if "event" in fields:
            events.append((fields["event"], json.loads(fields["data"])))
    return events


def test_health():
    assert client.get("/health").json() == {"status": "ok"}


def test_search_finds_the_database_ticket_first():
    r = client.post("/search", json={"query": "database connection pool exhausted", "k": 3})
    assert r.status_code == 200
    hits = r.json()["hits"]
    assert hits[0]["id"] == 109  # the only ticket that shares these words
    assert [h["score"] for h in hits] == sorted((h["score"] for h in hits), reverse=True)


def test_search_with_no_overlap_returns_an_empty_list():
    r = client.post("/search", json={"query": "zzzz qqqq"})
    assert r.json()["hits"] == []


def test_search_rejects_bad_input():
    assert client.post("/search", json={"query": "x"}).status_code == 422  # too short
    assert client.post("/search", json={"query": "refund", "k": 99}).status_code == 422


def test_suggest_streams_context_tokens_done():
    with client.stream("POST", "/suggest", json={"ticket": "I was charged twice for my invoice"}) as r:
        assert r.headers["content-type"].startswith("text/event-stream")
        raw = "".join(r.iter_text())
    events = parse_sse(raw)
    names = [e for e, _ in events]
    assert names[0] == "context" and names[-1] == "done"
    assert names.count("token") == events[-1][1]["tokens"] > 5


def test_cors_preflight_allows_the_vite_origin():
    r = client.options("/search", headers={
        "Origin": "http://localhost:5173",
        "Access-Control-Request-Method": "POST",
        "Access-Control-Request-Headers": "content-type"})
    assert r.headers["access-control-allow-origin"] == "http://localhost:5173"
    r2 = client.options("/search", headers={
        "Origin": "http://evil.example", "Access-Control-Request-Method": "POST"})
    assert "access-control-allow-origin" not in r2.headers


def test_suggest_with_no_similar_ticket_hands_over_to_a_person():
    with client.stream("POST", "/suggest", json={"ticket": "zzzz qqqq"}) as r:
        events = parse_sse("".join(r.iter_text()))
    reply = "".join(d["text"] for e, d in events if e == "token")
    assert "a person will pick this up" in reply
output of: pytest -v test_app.py
test_app.py::test_health PASSED
test_app.py::test_search_finds_the_database_ticket_first PASSED
test_app.py::test_search_with_no_overlap_returns_an_empty_list PASSED
test_app.py::test_search_rejects_bad_input PASSED
test_app.py::test_suggest_streams_context_tokens_done PASSED
test_app.py::test_cors_preflight_allows_the_vite_origin PASSED
test_app.py::test_suggest_with_no_similar_ticket_hands_over_to_a_person PASSED
7 passed

Tests run in-process, so they prove the logic but not the real server. One more check, on the real thing: start uvicorn, call it with curl, and stop it. We did exactly this and these are the real outputs.

terminal: end-to-end with curl (uvicorn app:app --port 8000)
$ curl -s -X POST localhost:8000/search -H 'Content-Type: application/json' \
       -d '{"query":"money taken twice from my card","k":2}'
{"query":"money taken twice from my card","backend":"tfidf","hits":[{"id":102,"category":"Billing","text":"Payment failed but my card still shows an active charge","resolution":"The charge was only a pending hold; it drops off by itself within 48 hours.","score":0.3238},{"id":107,"category":"Billing","text":"Can I switch from monthly to annual billing mid-cycle?","resolution":"Yes. We credit the unused monthly days and start the annual term today.","score":0.1317}]}

$ curl -sN -X POST localhost:8000/suggest -H 'Content-Type: application/json' \
       -d '{"ticket":"I was charged twice for invoice 9001"}'
event: context
data: {"ids": [101, 108, 105]}

event: token
data: {"text": "Hi, "}

event: token
data: {"text": "thanks "}
...
event: done
data: {"tokens": 45}

Read the output. The search reply is one JSON message. The two Billing hits are sensible for "money taken twice". The suggest reply opens with a context event naming the three tickets used, then one small event per word. Measured on this laptop: /search took 22 ms, the first /suggest byte arrived after 4 ms, and the full reply took 0.92 s, because the fake model waits 20 ms per word. With a real model, the first token is the number users feel.

Three kinds of check have now seen the app, and each can see bugs the others cannot. The picture below shows what each one is blind to, using the numbers we measured.

1 2 3 pytest, in-process 7 tests pass in 2.7 s sees: logic, 422s, event order blind to: real ports, the browser's CORS rule curl, real server 3 calls, real timings sees: headers, 22 ms search, 4 ms to first byte blind to: what a page may read real browser 2 renders of the built page sees: CORS, layout, loading and streaming states blind to: nothing, but the slowest each step to the right is closer to the user, slower to run, and sees more kinds of bug
Fig. 5b.8 — Three checks, three blind spots. Run the cheap ones constantly and the expensive one before every demo.
  1. pytest. It calls the app in the same process, so it is fast (7 tests in 2.7 s) and catches logic, validation and event-order bugs. It cannot see a CORS block, because no browser is involved.
  2. curl. It talks to the real uvicorn, so it shows real headers and real timings (22 ms for a search, 4 ms to the first suggest byte). It still enforces no origin rule, so it also cannot see a CORS block.
  3. A real browser. Only it applies CORS, runs the React code and shows what a person sees. It is the slowest check, so it is the one to run last and always before a demo.
Failure mode

The classic day-one failure: everything passes in curl, the page shows nothing, and the browser console says "blocked by CORS policy". We reproduced the server side. A preflight from http://evil.example gets 400 Bad Request and no access-control-allow-origin header, so a real browser would throw the reply away, while the server log would show nothing wrong. Check the Network tab first, then the CORS_ORIGINS value, before suspecting the model.

Anatomy of the streaming endpoint — the lines to know by heart
@app.post("/suggest",1 response_class=EventSourceResponse)2
async def suggest(req: SuggestRequest):3
    yield4 ServerSentEvent(event="token",5 data={"text": piece})6
  1. POST, not GET. The ticket text goes in the body, not the URL. People pick GET here because the browser's built-in EventSource only does GET, then find tickets too long for a URL.
  2. The response class. It sets Content-Type: text/event-stream and turns each yielded value into SSE text. Forget it and FastAPI returns one JSON list when the generator ends, with no streaming at all.
  3. The function is async. While it waits for the model, the server can serve other requests. A plain def that sleeps would hold a worker thread per open stream.
  4. yield, not return. Each yield sends one event and keeps the function alive. A return ends the response. This is the single easiest word to get wrong.
  5. The event name. It becomes the event: line. The browser dispatches on it, which is how it tells token events from the final done event. Leave it out and the name defaults to message.
  6. The data. It is serialised to JSON, even a plain string. That is why "Hi, " arrives with its trailing space intact. A newline inside data would have split the event; JSON escapes it.
Fireside chat

Tonight's talk: the browser and the API argue over the question, "Who is the real product?"

The browser page
The API

Nobody at Northwind will ever see you. They see me: the box, the list, the text typing itself out. I have the 13 keystrokes and I turn them into one request, as in Fig. 5b.1, marker 1. You cannot do that.

The page owns what the client actually sees and how many requests get sent (13 keystrokes become 1).

And I am why you work at all. I validate, I rank 25 tickets, I hold the key. When you forget to ask nicely, I am the one who says 422, or hides the reply behind CORS, as in Fig. 5b.5, marker 2.

The API enforces the rules the page cannot be trusted with: input limits, secrets, and who may read replies.

Rules are invisible. When the demo is slow, the client sees a spinner on my screen, not your log. I pick the metric: time to first word, which is about 4 ms of your 920.

Users judge by what appears on screen and when; the first-word time (4 ms here) matters more than the full 0.92 s.

Time to first word is mine too: I decide to stream instead of waiting. And my metric is the one that costs money: a wrong ticket returned fast is still wrong. Let us see what the evaluation module says about whose fault the next bad answer is.

Both sides own speed; only the API owns correctness. The answer waits for the evals module.

FastAPI route
@app.get / @app.post on a function; type hints are the contract.
Pydantic BaseModel
The request/response shape; violations return 422 automatically.
Build once
Fit the index at start-up (ENCODE, MATRIX = build_index()), never per request.
SSE endpoint
response_class=EventSourceResponse, an async def that yields ServerSentEvent.
Event order
One context, N token, one done in this app.
CORS
Only browsers enforce it; fix on the server with CORSMiddleware; list exact origins.
Offline switch
SEARCH_BACKEND (tfidf/minilm), LLM=claude. Defaults run with no model and no key.
Tests
TestClient is in-process; test the stream by parsing its text body.

05 · The browser sideTypeScript, React and Streaming, From Zero

The browser side is three skills: TypeScript (JavaScript with checked shapes), React (a screen described as functions of data), and reading a stream. Each is small. We take them one tiny program at a time before the lab puts them together.

The API runs, tests pass, and curl prints events. Maya cannot use curl, and neither can Northwind. The next event in the 48 hours is the screen. You may have written browser JavaScript years ago; here we assume only that you read code fluently and that React and TypeScript are new.

TypeScript in ten minutes: only the types you need

JavaScript has no types, so a typo in a field name is found by a user. TypeScript adds type labels that a checker reads before the code runs, then removes them. The browser still runs plain JavaScript. Node 24 can even run a .ts file directly by stripping the labels.

You do not need to learn all of TypeScript. This one file uses the four ideas the app needs: an object type, a union of words, typed functions and narrowing. Read it, run it, and move on.

Step-by-step: what types_in_10_minutes.ts does, in plain English
  1. type Hit = {...} names a shape: id and score are numbers, text is a string, and note? may be missing.
  2. type Status = 'idle' | 'loading' | 'error' | 'done' says a value is exactly one of these four words. Anything else is a compile error.
  3. label(h: Hit): string takes a Hit and returns a string. Pass it the wrong shape and the checker complains.
  4. describe checks s === 'done' and the list length. After a check, TypeScript knows more: this is called narrowing.
  5. Build a one-item list typed as Hit[] and print four results. The last comment shows an error the checker would catch.
frontend/examples/types_in_10_minutes.tsruns offline (Node 24)
// Run: node types_in_10_minutes.ts   (Node 24 strips the types itself; no build step)

// 1. A type is a shape for data. This one mirrors the API's Hit model.
type Hit = {
  id: number
  category: string
  text: string
  score: number
  note?: string // the ? means "may be missing"
}

// 2. A union: the value is exactly one of these words, nothing else.
type Status = 'idle' | 'loading' | 'error' | 'done'

// 3. Types on function inputs and output. Mistakes become red squiggles, not bugs.
function label(h: Hit): string {
  return `#${h.id} [${h.category}] ${h.score.toFixed(2)}`
}

// 4. Narrowing: after the check, TypeScript knows the shorter type.
function describe(s: Status, hits: Hit[]): string {
  if (s === 'done' && hits.length === 0) return 'no similar tickets'
  if (s === 'done') return `${hits.length} similar tickets`
  return s
}

const hits: Hit[] = [{ id: 109, category: 'Technical', text: 'Database pool exhausted', score: 0.43 }]
console.log(label(hits[0]))
console.log(describe('done', hits))
console.log(describe('done', []))
console.log(describe('loading', []))
// label({ id: '109' })   <- uncomment: tsc says string is not assignable to number
output of: node types_in_10_minutes.ts
#109 [Technical] 0.43
1 similar tickets
no similar tickets
loading

Read the output. Four calls, four lines. The Status union is the most useful idea for this app: our page is always in exactly one of four states (idle, loading, error, done), and the type makes "loading and error at once" unrepresentable. For more JavaScript depth, see the engineering track's JavaScript primer.

One more payoff of types: the API and the page must agree on the shape of a hit. We copy the Pydantic model into a TypeScript type by hand, field by field, and the compiler then checks every use of it.

backend/app.py (Pydantic) 1 SearchPage.tsx (TypeScript) 2 id: int id: number int → number category: str category: string str → string text: str text: string str → string resolution: str resolution: string str → string score: float score: number float → number hits: list[Hit] hits: Hit[] list → array 3 rename a field on one side and the build fails, not a customer
Fig. 5b.9 — The API's Hit model and the page's Hit type describe the same six pieces of data in two languages.
  1. The Pydantic side. The shape lives in app.py. Pydantic enforces it at run time on every response.
  2. The TypeScript side. A hand-copied type of the same shape. Python int and float both become TypeScript number; str becomes string; list[Hit] becomes Hit[].
  3. Why copy it. The copy lets the compiler check every h.score.toFixed(2) on the page. Tools such as an OpenAPI type generator can write the copy for you from /openapi.json; for a 48-hour demo, typing six lines is faster.

React in four ideas: component, props, state, effect

We have a typed vocabulary. The next piece Maya's search box needs is a screen that redraws itself when data arrives. React is the library that does that redrawing, and its core is four small ideas that you can see in two tiny files.

A component is a function that returns a piece of screen, written in JSX (HTML-like tags inside JavaScript). Props are its inputs, like function arguments. State is a value React remembers between calls; when you change it through the setter, React calls the function again and updates the screen. That is the whole redraw model: you change data, React redraws.

Step-by-step: what counter.tsx does, in plain English
  1. Import useState, React's tool for remembered values.
  2. The component is an exported function; React calls it to get the screen.
  3. useState(0) returns a pair: the current value (count) and a function to change it (setCount). The first time, count is 0.
  4. It returns a button. Clicking calls setCount(count + 1).
  5. React sees the state changed, calls the function again with the new count and updates the button text. Nothing else touches the screen.
frontend/examples/counter.tsxtype-checks offline
import { useState } from 'react'

// State: a value React remembers between renders. Changing it re-draws the component.
export default function Counter() {
  const [count, setCount] = useState(0) // [current value, function that changes it]
  return <button onClick={() => setCount(count + 1)}>clicked {count} times</button>
}

The picture below follows the counter through two clicks. The function is called once per render, and state is the one thing that survives between calls.

1 2 3 render 1 count = 0 clicked 0 times render 2 count = 1 clicked 1 times render 3 count = 2 clicked 2 times click click setCount(0 + 1) setCount(1 + 1) the function runs again for each render; only the text that changed is touched on screen
Fig. 5b.10 — Two clicks on the counter produce three calls of the same function, each with the state React remembered.
  1. The first render. React calls Counter() once. useState(0) gives count = 0, so the button says "clicked 0 times".
  2. After a click. The click handler runs setCount(0 + 1). React stores 1 and calls Counter() again, and useState now returns 1 instead of 0, so the button says "clicked 1 times".
  3. After the second click. The same happens with setCount(1 + 1). You never edit the screen yourself; you change the number and React redraws.

An effect is code that must run because something rendered, and that talks to the outside world: a timer, a network call, a subscription. You declare it with useEffect, plus a list of values it depends on. The effect re-runs when any of those values change. It may return a cleanup function, which React calls before the next run or when the component disappears.

Step-by-step: what ticker.tsx does, in plain English
  1. seconds is remembered state that starts at 0.
  2. useEffect runs after the first screen is drawn. It starts a timer that adds 1 to seconds every 1,000 ms.
  3. setSeconds((s) => s + 1) uses the previous value, so quick updates do not lose counts.
  4. The returned function clears the timer. React calls it when the component goes away, so timers never leak.
  5. The empty list [] means "no dependencies": run once, at the start.
  6. The component returns a paragraph showing the current count.
frontend/examples/ticker.tsxtype-checks offline
import { useEffect, useState } from 'react'

// Effect: code that talks to the world outside rendering (timers, network).
export default function Ticker() {
  const [seconds, setSeconds] = useState(0)

  useEffect(() => {
    const timer = setInterval(() => setSeconds((s) => s + 1), 1000)
    return () => clearInterval(timer) // cleanup: runs when the component goes away
  }, []) // [] = run once, when the component first appears

  return <p>open for {seconds} s</p>
}

Both files are checked by npx tsc -p tsconfig.examples.json --noEmit, which prints nothing when everything is well typed. For design and layout of real screens, the engineering track's frontend design chapter goes further; here we only need the four ideas.

A search box fires too often: debounce

Our search box will call /search from an effect that depends on what the agent typed. That means an effect run per keystroke, and each run is a request. The API answered in 22 ms, so it can take it, but a real model-backed search costs money per call. Let us count how bad it gets.

Debouncing means "wait until the user stops, then act". On every key you cancel the previous timer and start a new one of 300 ms. Only a pause longer than 300 ms lets a timer finish. The cleanup function from the effect idea above is exactly the cancel button.

1 NO DEBOUNCE: every key calls the API, 13 calls 2 DEBOUNCE 300 ms: only the pause calls the API, 1 call last key at 1440 ms 1 call at 1740 ms 0 ms 600 1200 1800 ms 3 typing "database pool": one key every 120 ms; every key restarts the 300 ms timer
Fig. 5b.11 — The same 13 keystrokes with and without a 300 ms debounce. The coloured bar is the timer that survives because no key follows it.
  1. No debounce. Typing "database pool" at one key per 120 ms (the 13th key lands at 1,440 ms) makes 13 requests, 12 of which are for half-typed words nobody wants answers for.
  2. Debounce. Each key restarts a 300 ms timer. Keys are only 120 ms apart, so no timer ever finishes until the last key. The surviving timer (the bar) fires at 1,440 + 300 = 1,740 ms and makes 1 request.
  3. The rule of thumb. The wait must be longer than the gap between keys and short enough to feel instant. 300 ms is the common default. The numbers come from running debounce_sim.ts.
Step-by-step: what debounce_sim.ts does, in plain English
  1. Type the text "database pool" at one key every 120 ms: build a list of key times (0, 120, 240, … 1440).
  2. Print the key count (13) and the last key time. Without debounce, every key is one call.
  3. Walk the key times. Before each key, if the previous key was at least 300 ms ago, that pending timer would have fired: count one call.
  4. Each key replaces the pending timer (pendingSince = t).
  5. After the loop, the last timer survives and fires: count one more call, and print its time (last key + 300).
frontend/examples/debounce_sim.tsruns offline (Node 24)
// Run: node debounce_sim.ts
// Simulate a user typing "database pool" at one key every 120 ms.
// Without debounce every key calls the API. With a 300 ms debounce, a call
// fires only after the typing pauses.
const text = 'database pool'
const gapMs = 120
const waitMs = 300

const keyTimes = [...text].map((_, i) => i * gapMs)
console.log(`keys typed: ${keyTimes.length}, last key at ${keyTimes.at(-1)} ms`)
console.log(`no debounce: ${keyTimes.length} API calls`)

let calls = 0
let pendingSince: number | null = null
for (const t of keyTimes) {
  if (pendingSince !== null && t - pendingSince >= waitMs) calls++ // the pause was long enough
  pendingSince = t // every key restarts the timer
}
calls++ // the final timer survives and fires
console.log(`debounce ${waitMs} ms: ${calls} API call, at ${keyTimes.at(-1)! + waitMs} ms`)
output of: node debounce_sim.ts
keys typed: 13, last key at 1440 ms
no debounce: 13 API calls
debounce 300 ms: 1 API call, at 1740 ms
BE the debounce timer

Your turn to play the timer. The wait is 300 ms. A key press cancels any pending timer and starts a new one. A timer that reaches 300 ms with no key makes one API call. These are the keystroke times of a different agent, who pauses to think:

  1. Key at 0 ms
  2. Key at 100 ms
  3. Key at 200 ms
  4. Key at 700 ms
  5. Key at 800 ms

At what times does the API get called, and how many calls would there be without debounce?

Check your answer

Two calls. The keys at 0, 100 and 200 ms each restart the timer; the last of them (200 ms) leaves a timer due at 500 ms, and nothing cancels it, so call 1 fires at 500 ms. The key at 700 ms starts a fresh timer, 800 ms restarts it for 1,100 ms, and call 2 fires at 1,100 ms. Without debounce there would be 5 calls. A pause longer than 300 ms is what separates one call from the next.

Reading a stream in the browser: EventSource or fetch

The search box now fires sensibly. The second screen job is the reply that types itself, and that means reading a response while it is still arriving. The browser has two tools for this, and our POST endpoint rules one of them out. Here is the choice.

Table 5b.2. Two ways to read an SSE stream in a browser
OptionWhat it promisesChoose it when
EventSourceBuilt in. Parses events for you. Reconnects by itself and resends Last-Event-ID.A plain GET stream, no custom headers: live notifications, a public feed.
fetch + ReadableStreamAny method, any body, any header (auth tokens). You parse the text yourself (about 20 lines) and handle reconnects.A POST with a ticket in the body or a bearer token: our case, and nearly every LLM chat.
A helper library (@microsoft/fetch-event-source, the Vercel AI SDK)The fetch approach, with parsing and retry written for you.You want fewer lines and accept a dependency. Fine for production; for learning, write the 20 lines once.

We use fetch. The reply body of a fetch call is a ReadableStream: you ask a reader for the next chunk of bytes in a loop. Chunks are cut wherever the network cut them, not where our events end. So the reader code keeps a leftover buffer. The lab builds exactly that, as a small file called sse.ts.

Open the POST.

Read the body in pieces.

Cut at the blank line.

Keep the tail for next time.

Append each token.

Open the POST: the fetch call, because EventSource cannot send our ticket in a body. Pieces: chunks of bytes, arbitrary sizes. Blank line: the event separator in Fig. 5b.4. Tail: the half-event kept in the buffer (see the next questions). Token: the text appended to the reply state in marker 3 of that figure.

"I could have done this in 20 lines of Streamlit. Why am I learning React and TypeScript for a search box?"

— the engineer who has used Streamlit for a dashboard

For an internal tool for five analysts, you are right, and you should use Streamlit or Gradio: it ships in an afternoon and Python is all you write. A dashboard over a model's results is a good fit. The stack table below says exactly when each tool is the right pick.

The honest downside of Streamlit: it re-runs the script on every interaction, gives you little control over layout, loading states and streaming behaviour, and it does not give you the client-facing, branded, deployable app a Northwind demo implies. When a customer will click it, the browser stack pays for itself.

Questions you might be asking now

Four questions that come up when the browser side first meets a stream. They reuse the three small streams from sse_demo.ts: three network chunks that cut the events in the wrong places.

Why can't I just use EventSource? It looks simpler.

Because EventSource can only send a GET request with no body and no custom headers. Our endpoint needs the ticket text in a POST body, and most real APIs need an Authorization header.

You can work around it by putting the ticket in the URL, but then:

  1. URL length. A long ticket may exceed limits (many servers cap a URL at about 8,000 characters), and logs record every URL.
  2. Secrets. A token in the URL ends up in server logs and browser history.
  3. The upside you give up. EventSource reconnects on its own and tells the server where it stopped (Last-Event-ID). With fetch you write that yourself, or skip it.

EventSource is simplest for GET streams; the moment you need a POST body or a header, use fetch and read the stream yourself.

What if the network cuts an event in half? How does the reader cope?

It keeps the unfinished tail in a buffer and glues the next chunk onto it before looking for a blank line. An event is only handed on once its blank line has been seen.

Follow the three chunks that sse_demo.ts sends. The reader does this for every chunk:

  1. Add the new chunk to the end of buffer.
  2. Split the buffer at every blank line (\n\n).
  3. The last piece has no blank line after it yet, so remove it from the list and keep it as the new buffer (blocks.pop()).
  4. Every remaining piece is a complete event: read its event: and data: lines and yield it.
1 A CHUNK ARRIVES (↵ = newline) 2 EVENTS YIELDED 3 KEPT IN BUFFER chunk 1 event: context↵data: {"ids": [102, 107]}↵↵event: tok context "event: tok" chunk 2 (buffer already holds "event: tok") en↵data: {"text": "Hi, "}↵↵eve token "Hi, " "eve" chunk 3 (buffer already holds "eve") nt: token↵data: {"text": "thanks "}↵↵ event: done↵data: {"tokens": 2}↵↵ token "thanks " done "" (empty)
Fig. 5b.12 — Three chunks that cut events in the wrong places. The buffer carries the unfinished tail across, so every event is yielded whole.
  1. The chunk. Chunk 1 ends in the middle of the word "token"; chunk 2 starts with "en". The network does not respect event boundaries.
  2. The events. Chunk 1 yields one whole event (context). Chunk 2 yields token "Hi, " because its tail from chunk 1 plus its own start made a complete block. Chunk 3 yields two events, token "thanks " and done.
  3. The tail. After chunk 1 the buffer holds "event: tok"; after chunk 2 it holds "eve"; after chunk 3 it is empty. Without this buffer, the page would try to parse "event: tok" as an event and break.

The result, printed by node sse_demo.ts in the lab: four events (context, token, token, done), none torn, from three chunks.

Network chunks and events are different cuts of the same text; the buffer is what lets the reader rebuild whole events.

When does the search effect run? Does it run on every keystroke?

The effect function runs after any render in which a value in its dependency list changed. Our dependency list is [query], so it runs once per keystroke, but with debounce each run only schedules a call that the next keystroke cancels.

Trace "db" typed at 0 and 100 ms, then a pause:

  1. Key "d" at 0 ms. query becomes "d" (fewer than 2 characters), so the effect sets status to idle and returns without a timer.
  2. Key "b" at 100 ms. query becomes "db". React first runs the cleanup of the previous effect run (nothing to cancel), then runs the effect again: it starts a 300 ms timer for 400 ms.
  3. Quiet until 400 ms. The timer fires and calls /search.
  4. If "o" arrived at 250 ms. React runs the cleanup first: it clears the 400 ms timer and aborts any request in flight. Then the effect starts a new timer due at 550 ms.

The picture below draws exactly this trace with the "o" key added at 250 ms.

1 2 3 d 0 ms b 100 ms o 250 ms timer 2: due at 400, cancelled at 250 ms timer 3: due at 550 ms call at 550 ms 0 ms 200 400 600 ms key d starts no timer (under 2 characters); key b starts timer 2; key o cancels it and starts timer 3
Fig. 5b.13 — Three keystrokes, three effect runs, one API call. The cancelled timer never fires.
  1. The keys. "d" at 0 ms, "b" at 100 ms and "o" at 250 ms. Each change of query re-runs the effect, so there are three effect runs.
  2. The cancelled timer. Timer 2 was due at 400 ms. The "o" key at 250 ms made React run the cleanup first, which cleared it. The dashed part is the time it never got to use.
  3. The surviving timer. Timer 3 started at 250 ms and is due at 250 + 300 = 550 ms. No key follows it, so it fires and makes the one /search call, for the text "dbo".

Each keystroke re-runs the effect, but its cleanup cancels the last one, so only the last pause makes a call.

What is AbortController for? The timer already stops old calls.

The timer stops calls that have not started. AbortController stops calls that have started but not finished. Without it, a slow old reply can arrive after a newer one and overwrite it.

  1. The race. The agent types "refund", the call starts and takes 800 ms. They keep typing " policy"; a second call starts later and is quick, finishing in 100 ms.
  2. Without abort. The second reply arrives first and the screen shows the new results; then the slow first reply arrives and overwrites them with results for the old text.
  3. With abort. The cleanup calls controller.abort() on the first request. Its fetch throws an AbortError, which the code ignores, so only the latest reply can ever reach the screen.

Timers cancel the waiting; abort cancels the in-flight call, so a slow old reply cannot overwrite a newer one.

Type / union
A named shape; a value that is exactly one of several words. Checked before running, erased at runtime.
Component
A function from data to screen. Props are its inputs.
useState
A remembered value plus a setter. Changing it redraws the component.
useEffect
Code run after render for outside-world work. Depends on a list; its returned function cleans up.
Debounce
Restart a timer on each key; only a pause calls the API. 13 keys became 1 call in our measurement.
EventSource vs fetch
EventSource: GET only. fetch: any method and headers, parse it yourself.
Stream buffer
Keep the unfinished tail between chunks; yield only events whose blank line has arrived.
AbortController
Cancels an in-flight request so stale replies cannot overwrite fresh ones.

06 · The labBuild the React Search Page in Six Chunks

The lab is the screen: a search box that finds similar tickets as you type and a button that types out a suggested reply. We build it in six small chunks, each of which compiles and runs.

The API is solid, and we now own the four ideas the browser needs: types, state, an effect with cleanup, and a stream reader. Maya's demo needs them as one page. The order below is the order you would write it on day one: draw something, fetch something, handle the bad cases, stop hammering the server, and only then stream.

LAB 05b — HelpDeskAI search: semantic search in a full-stack app

Mission: a React + FastAPI app where an agent types a ticket description, sees the five most similar past tickets with their resolutions, and clicks "Suggest a reply" to watch a drafted reply stream in. It must work offline (TF-IDF and the fake streamer) and with MiniLM and a real LLM switched on by environment variables.

  • npm run build passes (TypeScript and Vite) at every one of the six chunks.
  • Typing 13 characters sends one /search request, not 13 (check the browser's Network tab).
  • The page shows distinct loading, error (API stopped) and empty ("No similar tickets") states.
  • The reply grows word by word; the button is disabled while it streams.
  • Measurement: run the three queries from search_backends.py with both backends and write down which family (Billing, Technical, Account) each top hit belongs to.
  • README documents: the screenshot, three failure modes you hit (CORS, empty state, a stale reply) and the fix for each.

Stretch goal: add a "Was this reply useful?" button that POSTs to a new /feedback endpoint and logs it, then plan how Module 07 would use those logs.

Build it in chunks

We build SearchPage.tsx in six chunks. Each chunk is a runnable snapshot saved in code/05b-fullstack-ai-apps/frontend/ladder/: copy it to src/SearchPage.tsx and run npm run build. Chunk 5 is a separate file, src/sse.ts. The finished page comes after chunk 6.

  1. Chunk 1 — draw a static list of hits

    Start with the data shape and the picture, no network. If the card looks wrong, you want to find out before any fetch can confuse the issue.

    Step-by-step: what chunk 1 does, in plain English
    1. type Hit copies the API's Hit model: id, category, text, resolution, score.
    2. SAMPLE is a fixed list of two hits written by hand, using real tickets 109 and 112.
    3. SearchPage is the component. It returns a page title and a list.
    4. SAMPLE.map(...) turns each hit into one <li>. The key (the ticket id) lets React track each item when the list changes.
    5. Each card shows the category badge, the text, the score to two decimals and the resolution.
    ladder/SearchPage.1-static.tsxbuilds offline
    type Hit = {
      id: number
      category: string
      text: string
      resolution: string
      score: number
    }
    
    const SAMPLE: Hit[] = [
      { id: 109, category: 'Technical', score: 0.43,
        text: 'Database connection pool exhausted, error 5503',
        resolution: 'A leaked connection in the export job. Restarted the job and raised the pool to 40.' },
      { id: 112, category: 'Technical', score: 0.31,
        text: 'Container keeps restarting, OOM-killed after 40 seconds',
        resolution: 'The memory limit was 256 MB. Raised it to 1 GB and the restarts stopped.' },
    ]
    
    export default function SearchPage() {
      return (
        <main className="page">
          <h1>Similar past tickets</h1>
          <ul className="hits">
            {SAMPLE.map((h) => (
              <li key={h.id}>
                <span className="cat">{h.category}</span>
                {h.text}
                <span className="score">{h.score.toFixed(2)}</span>
                <small>{h.resolution}</small>
              </li>
            ))}
          </ul>
        </main>
      )
    }

    list.map(item => <li key=...>) — render a list. The key must be a stable unique value, never the array position.

    npm run build ends with dist/assets/index-Cj2fi5VK.js 220.29 kB │ gzip: 68.94 kB and ✓ built. Opened in a browser it shows two cards: tickets 109 and 112, scores 0.43 and 0.31.

  2. Chunk 2 — fetch real hits when the button is clicked

    Replace the fixed list with a call to the API. State now holds what the agent typed and what came back. We keep the button for now, so the trigger is obvious while we learn the call.

    Step-by-step: what chunk 2 changes, in plain English
    1. Import useState.
    2. API is the server address: the VITE_API_URL environment value if set, else http://localhost:8000.
    3. query remembers what is typed; hits remembers the last results (starting empty).
    4. runSearch POSTs {query, k: 5} as JSON to /search and waits for the reply.
    5. res.json() parses the body; setHits(data.hits) stores it, and React redraws the list.
    6. The input is controlled: its value comes from state and every keystroke updates state. The button calls runSearch. The list now maps over hits instead of SAMPLE.
    ladder/SearchPage.2-fetch.tsx (changed and added lines)builds offline
    import { useState } from 'react'
    
    const API = import.meta.env.VITE_API_URL ?? 'http://localhost:8000'
    
      const [query, setQuery] = useState('')
      const [hits, setHits] = useState<Hit[]>([])
    
      async function runSearch() {
        const res = await fetch(`${API}/search`, {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({ query, k: 5 }),
        })
        const data = await res.json()
        setHits(data.hits)
      }
    
          <input value={query} onChange={(e) => setQuery(e.target.value)}
                 placeholder="Describe the new ticket..." />
          <button onClick={runSearch}>Search</button>

    fetch(url, {method, headers, body}) — the browser's HTTP call. It returns a promise; await pauses until the reply arrives.

    npm run build ends with index-DrtFZGfS.js 220.31 kB │ gzip: 68.95 kB. With uvicorn app:app running, typing a description and clicking Search lists the hits. If the browser console says "blocked by CORS policy", go back to chunk 7 of the API.

  3. Chunk 3 — loading, error and empty states

    A real user will meet a slow server, a stopped server and a query with no matches. Without states, those look like a frozen page. A four-word type makes the page handle each case on purpose.

    Step-by-step: what chunk 3 changes, in plain English
    1. type Status says the page is exactly one of: idle, loading, error, done.
    2. A status state starts as idle.
    3. runSearch sets loading first, then wraps the call in try/catch.
    4. If the server answers with a non-OK status, throw jumps to catch, which sets error. A stopped server also lands in catch.
    5. On success it stores the hits and sets done.
    6. Three conditional lines draw the right message: cond && <p> renders the paragraph only when the condition is true. The button is disabled while loading.
    ladder/SearchPage.3-states.tsx (changed and added lines)builds offline
    type Status = 'idle' | 'loading' | 'error' | 'done'
    
      const [status, setStatus] = useState<Status>('idle')
    
      async function runSearch() {
        setStatus('loading')
        try {
          const res = await fetch(`${API}/search`, {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ query, k: 5 }),
          })
          if (!res.ok) throw new Error(`server said ${res.status}`)
          const data = await res.json()
          setHits(data.hits)
          setStatus('done')
        } catch {
          setStatus('error')
        }
      }
    
          <button onClick={runSearch} disabled={status === 'loading'}>Search</button>
          {status === 'loading' && <p className="status">Searching...</p>}
          {status === 'error' && <p className="status error">Search failed. Is the API running?</p>}
          {status === 'done' && hits.length === 0 && <p className="status">No similar tickets.</p>}

    try { ... } catch { ... } and cond && <element> — handle failure, and draw something only when a condition holds.

    npm run build ends with index-BGCBD_4W.js 220.73 kB │ gzip: 69.09 kB. Stop uvicorn and click Search: the page shows "Search failed. Is the API running?". Search "zzzz qqqq" with the API running: it shows "No similar tickets."

  4. Chunk 4 — search as you type, with a debounce and a cancel

    The button is a crutch. Now the search runs by itself 300 ms after the last keystroke, using exactly the effect, cleanup and abort ideas from the previous section. The button disappears.

    Step-by-step: what chunk 4 changes, in plain English
    1. Import useEffect. The starting value of query reads ?q= from the page address, so a link can pre-fill the box (handy for screenshots and demos).
    2. The effect depends on [query]: it runs after every change of the text.
    3. If the text has fewer than 2 characters (the API's minimum), reset to idle with no hits and stop.
    4. Otherwise create an AbortController and start a 300 ms timer.
    5. When the timer fires it sets loading, calls /search with signal attached, then stores the hits and sets done.
    6. An AbortError is expected when we cancel, so it must not show the error message.
    7. The returned cleanup clears the timer and aborts the request. React calls it before the next run, so each key cancels the previous one.
    ladder/SearchPage.4-debounce.tsx (changed and added lines; runSearch and the Search button are removed)builds offline
    import { useEffect, useState } from 'react'
    
      const [query, setQuery] = useState(new URLSearchParams(location.search).get('q') ?? '')
    
      useEffect(() => {
        if (query.trim().length < 2) {
          setStatus('idle')
          setHits([])
          return
        }
        const controller = new AbortController() // lets us cancel an outdated request
        const timer = setTimeout(async () => {
          setStatus('loading')
          try {
            const res = await fetch(`${API}/search`, {
              method: 'POST',
              headers: { 'Content-Type': 'application/json' },
              body: JSON.stringify({ query, k: 5 }),
              signal: controller.signal,
            })
            if (!res.ok) throw new Error(`server said ${res.status}`)
            setHits((await res.json()).hits)
            setStatus('done')
          } catch (err) {
            if ((err as Error).name !== 'AbortError') setStatus('error')
          }
        }, 300) // wait for 300 ms of silence before calling the API
        return () => {
          clearTimeout(timer) // typed again: cancel the waiting call
          controller.abort() // ...and the one already in flight
        }
      }, [query])

    useEffect(fn, [query]) with a returned cleanup, and AbortController with signal — debounce plus cancellation.

    npm run build ends with index-BFWL-EQ-.js 220.88 kB │ gzip: 69.18 kB. Type "database pool" at normal speed and watch the Network tab: one /search request. node debounce_sim.ts printed debounce 300 ms: 1 API call, at 1740 ms for the same text.

  5. Chunk 5 — a stream reader (a new file, sse.ts)

    Reading a stream is the one piece of browser code with real subtlety, so it gets its own file and its own test. It knows nothing about React: it takes a response and yields events, as in Fig. 5b.12.

    Step-by-step: what sse.ts does, in plain English
    1. SseEvent is the shape handed back: an event name and its decoded data.
    2. readSse is an async generator (async function*): it can yield many values over time.
    3. Get a reader for the response body and a decoder that turns bytes into text. buffer starts empty.
    4. Loop: ask the reader for the next chunk; when it says done, stop.
    5. Decode the chunk and append it to buffer (stream: true keeps a half-finished character for next time).
    6. Split the buffer at blank lines. The last piece may be half an event, so pop() removes it and it becomes the new buffer.
    7. For each whole block, read its event: and data: lines, parse the data as JSON and yield the event.
    frontend/src/sse.tsruns offline
    // Read a text/event-stream response that arrives as the body of a POST.
    // EventSource cannot send a POST body, so we read the stream by hand.
    export type SseEvent = { event: string; data: unknown }
    
    export async function* readSse(res: Response): AsyncGenerator<SseEvent> {
      const reader = res.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 blocks = buffer.split('\n\n') // a blank line ends one event
        buffer = blocks.pop() ?? '' // the last piece may be half an event: keep it
        for (const block of blocks) {
          let event = 'message'
          let data = ''
          for (const line of block.split('\n')) {
            if (line.startsWith('event: ')) event = line.slice(7)
            else if (line.startsWith('data: ')) data += line.slice(6)
          }
          if (data) yield { event, data: JSON.parse(data) }
        }
      }
    }

    async function* and for await — produce and consume values that arrive over time. TextDecoder turns bytes into text.

    node sse_demo.ts (in frontend/examples) feeds three torn chunks and prints network chunks: 3, then context {"ids":[102,107]}, token {"text":"Hi, "}, token {"text":"thanks "} and done {"tokens":2}. Four whole events from three torn chunks. The component is unchanged, so npm run build still gives 220.88 kB, because nothing imports sse.ts yet.

  6. Chunk 6 — stream the suggested reply onto the page

    The last chunk joins the stream reader to a button and a piece of state. The reply starts empty, grows by one token per event, and the button is disabled while it does.

    Step-by-step: what chunk 6 changes, in plain English
    1. Import readSse from the new file.
    2. Two new pieces of state: reply (the text so far) and streaming (are we mid-reply).
    3. suggest() clears the reply, sets streaming, then POSTs the typed text to /suggest.
    4. for await (const ev of readSse(res)) loops once per event as they arrive.
    5. On a token event, setReply((r) => r + text) appends the new word to the previous value.
    6. finally sets streaming back to false even if the call fails.
    7. The page gets a "Suggest a reply" button (disabled while streaming or when the text is too short) and a paragraph for the reply.
    ladder/SearchPage.6-streamed.tsx (changed and added lines)builds offline
    import { readSse } from './sse'
    
      const [reply, setReply] = useState('')
      const [streaming, setStreaming] = useState(false)
    
      async function suggest() {
        setReply('')
        setStreaming(true)
        try {
          const res = await fetch(`${API}/suggest`, {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ ticket: query }),
          })
          for await (const ev of readSse(res)) {
            if (ev.event === 'token') setReply((r) => r + (ev.data as { text: string }).text)
          }
        } finally {
          setStreaming(false)
        }
      }
    
          <button onClick={suggest} disabled={streaming || query.trim().length < 2}>
            Suggest a reply
          </button>
          {reply && <p className="reply">{reply}</p>}

    setReply((r) => r + text) — the "functional update": build the new state from the previous one, which is safe when updates arrive quickly.

    npm run build ends with index-Cy1AYesN.js 221.68 kB │ gzip: 69.48 kB. In the browser, typing a ticket and clicking "Suggest a reply" fills the reply box word by word.

The whole program

Chunk 1 is the Hit type and the list markup at the bottom. Chunk 2 is the API constant, the query and hits state and the input. Chunk 3 is Status and the three message lines. Chunk 4 is the effect block. Chunk 5 is the separate file src/sse.ts, imported at the top. Chunk 6 is the suggest function, the button and the reply paragraph. Each chunk starts with a // ── chunk n ── comment.

frontend/src/SearchPage.tsxbuilds offline
// ── chunk 2 adds useState and fetch; chunk 4 adds useEffect ──
import { useEffect, useState } from 'react'

// ── chunk 5: the stream reader lives in sse.ts ──
import { readSse } from './sse'

// ── chunk 1: the shape of one hit, and the list that draws it ──
type Hit = {
  id: number
  category: string
  text: string
  resolution: string
  score: number
}

// ── chunk 3: loading / error / empty states ──
type Status = 'idle' | 'loading' | 'error' | 'done'

const API = import.meta.env.VITE_API_URL ?? 'http://localhost:8000'

export default function SearchPage() {
  const [query, setQuery] = useState(new URLSearchParams(location.search).get('q') ?? '')
  const [hits, setHits] = useState<Hit[]>([])
  const [status, setStatus] = useState<Status>('idle')
  const [reply, setReply] = useState('')
  const [streaming, setStreaming] = useState(false)

  // ── chunk 4: debounce, and cancel outdated requests ──
  useEffect(() => {
    if (query.trim().length < 2) {
      setStatus('idle')
      setHits([])
      return
    }
    const controller = new AbortController() // lets us cancel an outdated request
    const timer = setTimeout(async () => {
      setStatus('loading')
      try {
        const res = await fetch(`${API}/search`, {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({ query, k: 5 }),
          signal: controller.signal,
        })
        if (!res.ok) throw new Error(`server said ${res.status}`)
        setHits((await res.json()).hits)
        setStatus('done')
      } catch (err) {
        if ((err as Error).name !== 'AbortError') setStatus('error')
      }
    }, 300) // wait for 300 ms of silence before calling the API
    return () => {
      clearTimeout(timer) // typed again: cancel the waiting call
      controller.abort() // ...and the one already in flight
    }
  }, [query])

  // ── chunk 6: stream the suggested reply ──
  async function suggest() {
    setReply('')
    setStreaming(true)
    try {
      const res = await fetch(`${API}/suggest`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ ticket: query }),
      })
      for await (const ev of readSse(res)) {
        if (ev.event === 'token') setReply((r) => r + (ev.data as { text: string }).text)
      }
    } finally {
      setStreaming(false)
    }
  }

  return (
    <main className="page">
      <h1>Similar past tickets</h1>
      <input value={query} onChange={(e) => setQuery(e.target.value)}
             placeholder="Describe the new ticket..." />
      <button onClick={suggest} disabled={streaming || query.trim().length < 2}>
        Suggest a reply
      </button>
      {reply && <p className="reply">{reply}</p>}
      {status === 'loading' && <p className="status">Searching...</p>}
      {status === 'error' && <p className="status error">Search failed. Is the API running?</p>}
      {status === 'done' && hits.length === 0 && <p className="status">No similar tickets.</p>}
      <ul className="hits">
        {hits.map((h) => (
          <li key={h.id}>
            <span className="cat">{h.category}</span>
            {h.text}
            <span className="score">{h.score.toFixed(2)}</span>
            <small>{h.resolution}</small>
          </li>
        ))}
      </ul>
    </main>
  )
}

Before the proof, one picture of the state that chunks 3 and 4 introduced. The page is always in exactly one of four states, and every line of the effect moves it along one arrow.

1 2 3 4 idle shows: nothing loading shows: "Searching..." done cards, or "No similar tickets." error "Search failed." 300 ms pause 200 + hits typed again server down or 5xx text under 2 characters from any state: back to idle with no hits
Fig. 5b.14 — The four states of the search page and what moves it between them. The page is always in exactly one.
  1. idle. Nothing typed, or under 2 characters. The page shows only the box. A 300 ms pause with enough text moves it to loading.
  2. loading. The call is in flight. The page shows "Searching..." and the earlier hits are still visible, so the list does not flash empty.
  3. done. The reply arrived with status 200. The page shows the cards, or "No similar tickets." when the list is empty (for example the query "zzzz qqqq"). Typing again goes back to loading.
  4. error. The server was unreachable or answered with an error status. The page shows "Search failed. Is the API running?". An aborted call is not an error: the next search simply replaces it.

Read the program. One idea runs through it: every piece of changing data lives in state (query, hits, status, reply, streaming), and the screen is a function of that state. The effect is the only place that talks to the network for search, and its cleanup is what makes typing fast and safe. The package file pins the exact versions: React 19.3.1, Vite 8.3.5, TypeScript 7.0.2.

Proof it works: build, run, look

We built it with npm install and npm run build (TypeScript check plus Vite bundle; the final page is 221.68 kB, 69.48 kB gzipped). Then we ran the real API with uvicorn and the built page with vite preview on port 5173, and rendered both with headless Chrome. We stopped both servers right after.

terminal: build the frontend
$ cd frontend && npm install && npm run build
> tsc -b && vite build
dist/index.html                   0.46 kB │ gzip:  0.30 kB
dist/assets/index-C1K-B02y.css    1.04 kB │ gzip:  0.49 kB
dist/assets/index-Cy1AYesN.js   221.68 kB │ gzip: 69.48 kB
✓ built in 223ms

What Chrome showed. Opening /?q=prod Postgres cluster throwing 500s and timing out rendered the page title, the filled search box, the "Suggest a reply" button and five cards: "I locked myself out after changing my phone number" (Account, 0.18), "Requesting GDPR data export and account deletion" (Account, 0.15), "Requests time out when uploading files larger than 50 MB" (Technical, 0.15), "Please update our SSO domain and billing address" (Account, 0.15) and "Our invoice shows the wrong company name and tax number" (Billing, 0.13).

The same wrong TF-IDF answers as before, now visible. The page works; the model behind it is the weak part, which is exactly what SEARCH_BACKEND=minilm fixes.

In a second render the page was opened with the query "money taken twice from my card" and the suggest button was clicked automatically (a scratch copy of the page, not the code above). The capture caught the stream mid-flight: the reply box held "Hi," and the button was greyed out (disabled), while four Billing cards (0.32, 0.13, 0.11, 0.09) filled the list. That is chunk 6 working: the streamed text grows while the search results stay put.

Chunk order
static list, fetch on click, states, debounce, stream reader, streamed reply.
State list
query, hits, status, reply, streaming. The screen is a function of these.
Controlled input
The input's value comes from state; each keystroke updates state.
Where the network call lives
Inside the effect for search (debounced, cancellable); inside suggest() for the stream.
Build check
npm run build = type check + bundle. Run it after every chunk.
Env value
VITE_API_URL overrides the API address at build time.

07 · Ship itNext.js, the Thin Proxy, and the Stack Table

Next.js is a React framework that also runs a small server. It lets one project hold the page, a server-side proxy to your API and a single deployment. We use it as the "ship the demo" variant, not as a replacement for what you built.

The Vite page works and Maya can click it on your laptop. Northwind will click it on theirs, over the internet, on Thursday. That raises two practical problems: the API address and any keys should not live in browser code, and you want one thing to deploy. Next.js solves both, and the forward-deployed engineering track expects you to know it.

Which Next.js, and what is new

As of October 2026 the current major version is Next.js 16 (the npm package was at 16.4.3 when we built this demo), requiring Node.js 20.9 or later. Its bundler, Turbopack, is the default. We pinned next@16.4.3, react@19.3.1 and typescript@5.9.3 in nextjs-demo/package.json and ran next build to prove it compiles.

The App Router (the folder app/) is the current way to write Next.js. A folder with a page.tsx is a page. A folder with a route.ts is an HTTP endpoint. Files are server components by default. A file that starts with 'use client' is a client component.

One honest page: what runs where

The best way to learn the server/client split is one page that needs both. Our demo page pre-fetches three similar tickets on the server (no secrets in the browser, no loading spinner for them) and holds a client component for the box that streams the reply.

3 Browser Suggest.tsx 'use client' holds reply state Next.js server 1 page.tsx server component 2 route.ts streaming proxy FastAPI /search /suggest HTML + 3 hits POST /search server-side POST /api/suggest token stream POST /suggest SSE tokens the browser never sees the API address; page and route.ts share one origin, so no CORS
Fig. 5b.15 — Where each Next.js file runs. The server component fetches on the server; the route handler forwards the stream; only the client component ships JavaScript to the browser.
  1. The server component. page.tsx runs only on the Next.js server. It calls /search directly and sends finished HTML, with the 3 hits already inside. Its code and its API_URL never reach the browser.
  2. The route handler. app/api/suggest/route.ts is a thin proxy (a backend for the frontend, or BFF). It receives the browser's POST and forwards it to FastAPI, then passes the response stream back untouched. It is the place to add an API key or a rate limit later.
  3. The client component. Suggest.tsx starts with 'use client'. It is the only part that gets JavaScript in the browser, because only it needs state and a click handler. It talks to /api/suggest on its own origin, so no CORS is needed.
Step-by-step: what the three Next.js files do, in plain English
  1. page.tsx (server): export const dynamic = 'force-dynamic' asks Next.js to run it on every request, not once at build time.
  2. similar() POSTs a fixed query ("customer was charged twice") to FastAPI with caching turned off, and returns an empty list if the API is down so the page still renders.
  3. The page is an async function: server components may await data. It lists the 3 hits and renders <Suggest />.
  4. Suggest.tsx (client): holds the typed ticket and the reply; its go() POSTs to /api/suggest and reads the stream with the same buffer-and-split loop as sse.ts, appending each token.
  5. route.ts: POST forwards the request body to FastAPI's /suggest.
  6. It returns new Response(upstream.body, ...): the body is a stream, handed through without reading it, with text/event-stream and no-cache headers.
nextjs-demo/app/page.tsxbuilds offline (calls the API at run time)
// SERVER component (the default in the App Router): runs on the server only.
// The backend URL and any secrets never reach the browser.
import Suggest from './Suggest'

export const dynamic = 'force-dynamic' // ask the API on every request, not at build time

const API = process.env.API_URL ?? 'http://localhost:8000'

type Hit = { id: number; category: string; text: string; score: number }

async function similar(query: string): Promise<Hit[]> {
  try {
    const res = await fetch(`${API}/search`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ query, k: 3 }),
      cache: 'no-store',
    })
    return (await res.json()).hits
  } catch {
    return [] // the demo page must still render if the API is down
  }
}

export default async function Page() {
  const hits = await similar('customer was charged twice')
  return (
    <main>
      <h1>HelpDeskAI: suggested replies</h1>
      <h2>Pre-fetched on the server</h2>
      <ul>
        {hits.map((h) => (
          <li key={h.id}>[{h.category}] {h.text} ({h.score.toFixed(2)})</li>
        ))}
      </ul>
      <Suggest />
    </main>
  )
}
nextjs-demo/app/Suggest.tsxbuilds offline
'use client' // CLIENT component: ships JavaScript to the browser, may use state and events

import { useState } from 'react'

export default function Suggest() {
  const [ticket, setTicket] = useState('')
  const [reply, setReply] = useState('')

  async function go() {
    setReply('')
    const res = await fetch('/api/suggest', { // same origin: no CORS needed
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ ticket }),
    })
    const reader = res.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 blocks = buffer.split('\n\n')
      buffer = blocks.pop() ?? ''
      for (const b of blocks) {
        if (b.startsWith('event: token')) {
          const line = b.split('\n').find((l) => l.startsWith('data: '))!
          setReply((r) => r + JSON.parse(line.slice(6)).text)
        }
      }
    }
  }

  return (
    <section>
      <h2>Suggest a reply (streamed through the BFF)</h2>
      <input value={ticket} onChange={(e) => setTicket(e.target.value)}
             style={{ width: '100%' }} placeholder="Paste the ticket..." />
      <button onClick={go}>Suggest</button>
      <p style={{ whiteSpace: 'pre-wrap' }}>{reply}</p>
    </section>
  )
}
nextjs-demo/app/api/suggest/route.tsbuilds offline
// Route handler = a tiny server endpoint inside Next.js. Here it is a thin
// proxy (a "backend for frontend"): the browser talks only to Next.js.
const API = process.env.API_URL ?? 'http://localhost:8000'

export async function POST(req: Request) {
  const upstream = await fetch(`${API}/suggest`, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: await req.text(),
  })
  // Pass the stream through untouched; do not buffer it with .text().
  return new Response(upstream.body, {
    status: upstream.status,
    headers: { 'Content-Type': 'text/event-stream', 'Cache-Control': 'no-cache' },
  })
}

We ran next build, then next start on port 3000 with the FastAPI server on 8000, called the proxy with curl and stopped both. These are the real results.

terminal: next build, then curl through the proxy
$ npm run build
Route (app)
┌ ƒ /
├ ○ /_not-found
└ ƒ /api/suggest
ƒ  (Dynamic)  server-rendered on demand

$ curl -s localhost:3000 | grep "Pre-fetched"        # HTML already holds the hits
...Pre-fetched on the server</h2><ul><li>[Billing] I was double charged on invoice 4471, need this reversed (0.31)</li>...

$ curl -sN -X POST localhost:3000/api/suggest -H 'Content-Type: application/json' \
       -d '{"ticket":"container keeps restarting OOM"}'
event: context
data: {"ids": [112]}

event: token
data: {"text": "Hi, "}

event: token
data: {"text": "thanks "}

Read the output. The route table marks / and /api/suggest as dynamic (ƒ): they run per request. The page's HTML already contains the first Billing hit, scored 0.31 against the fixed query "customer was charged twice", so the server component worked. The proxy call returns the very same event stream as FastAPI did directly: ticket 112 for the memory-killed container, then tokens.

"Now I have two servers, Next.js and FastAPI, for one search box. Isn't that more moving parts, not fewer?"

— anyone who has done an on-call rotation

Yes, it is. Next.js earns its place only when a server-side layer helps: secrets that must not reach the browser, one deployable for the client's IT team, server-rendered HTML for fast first paint, or auth cookies. For a demo run from your laptop, the Vite page plus FastAPI is fewer parts and fewer surprises.

The honest downside: the proxy adds a hop, and any buffering in it will ruin streaming. If tokens appear in one lump at the end, suspect the proxy, not the model. Our route passes upstream.body untouched for exactly that reason.

The stack, and why

The one question that decides it: who will click this, and who must be able to keep running it after the demo?

What this module uses, what else you could use, and when to switch (as of October 2026)
LayerWe useAlternativesWhy this oneSwitch when
API frameworkFastAPI 0.141 + Pydantic 2Flask; Django Ninja; Litestar; Express/NodeType hints become validation and OpenAPI docs; async; native SSE since 0.141; same language as the model code. Weaker: no admin, ORM or auth built in.Django Ninja when the app already lives in a Django monolith with its admin and ORM. Express or Next.js route handlers when the whole team writes only TypeScript and the "model" is an HTTP call.
FrontendReact 19 + Vite 8 (a single-page app)Next.js 16; SvelteKit; Streamlit or Gradio; Angular (see the Angular primer)Largest ecosystem and hiring pool; builds to static files any host serves. Weaker: you add routing, server rendering and secrets handling yourself.Next.js when secrets must stay server-side, you want one deployable, or you need server-rendered pages. Streamlit or Gradio for an internal tool under about 20 users with no branding. Angular when the client's team already works in Angular.
Streaming transportServer-Sent Events over fetchWebSockets; long pollingPlain HTTP, one direction, passes through proxies and load balancers. Weaker: text only, server-to-browser only, and some proxies buffer unless told not to.WebSockets for two-way live data such as voice or shared editing. Long polling only behind a proxy that cannot stream.
LanguageTypeScript 7 for the pagePlain JavaScriptThe page's Hit type mirrors the API's Pydantic model, so a renamed field fails the build rather than a customer. Weaker: a build step and config.Plain JavaScript for a throwaway single-file page you will delete after the demo.
AI UI helpersPlain fetch plus our 25-line sse.tsVercel AI SDK (the ai package, version 7 on npm)Zero dependencies, and you see every byte of the protocol once. Weaker: you write chat state, retries and tool-call rendering yourself.The AI SDK when you need chat history state, tool-call UI or more than one model vendor, or the project is already on Next.js.
Search backendIn-memory NumPy matrix, TF-IDF or MiniLMChroma; pgvector (see Module 08)25 tickets need no database; the index is rebuilt in memory each time the server starts. Weaker: lost on restart, rebuilt each time, no filtering.Chroma when you need persistence or updates without a restart. pgvector when tickets already live in Postgres and you have under about 10 million vectors. A 100,000-ticket matrix of 384 floats is about 154 MB of RAM, so move before then.

For a 48-hour client demo, FastAPI plus a Vite React page is the shortest path; add Next.js only when a server-side layer or a single deployable earns it.

Next.js 16
Current major as of October 2026; needs Node 20.9+; Turbopack is the default bundler.
Server component
Default in app/; runs on the server, may await data, ships no JS.
Client component
File starts with 'use client'; has state and events; ships JS.
Route handler
app/.../route.ts; exports POST etc. Use it as a thin streaming proxy (BFF).
Streaming through a proxy
Return upstream.body unread; never .text() it; keep no-cache.
force-dynamic
Run on every request instead of at build time, so the page can ask a live API.

08 · The 48-hour playbookPrototype in 48 Hours: What to Fake, What Must Be Real

A 48-hour prototype is a promise about one thing, kept completely, with everything else honestly faked. The skill is choosing which thing is real, and saying out loud which parts are not.

We now own every piece Maya asked for. What remains is the part no tutorial covers: how to spend 48 hours so the demo on Thursday goes well. The hardest decisions are not technical. They are what to leave fake, and when to stop adding.

1 2 3 Frame Real backend UI + streaming Fake the rest, polish Rehearse x3 Buffer 0 h 4 12 24 36 44 48 h hour 4: the API contract (the JSON shapes) is frozen, so screen and backend work in parallel hour 12: /search returns real hits on the client's sample tickets hour 36: feature freeze; only fixes after this point hour 44: no code changes at all; the last 4 hours are for sleep and one more dry run
Fig. 5b.16 — A 48-hour budget. The widest bar is the UI and streaming; the two highlighted bars are the ones teams skip.
  1. Real backend, hours 4 to 12 (8 h). The search must be real on the client's own sample data, because that is the claim the demo makes. A fake search that returns canned hits fails the first time the client types their own ticket.
  2. Rehearse three times, hours 36 to 44 (8 h). Run the demo script end to end on the machine you will present from, with the network you will use. Every rehearsal finds one thing; the third finds none. Stop adding features at hour 36.
  3. Buffer, hours 44 to 48 (4 h). It exists because something will break. If nothing does, it is sleep, which is worth more than a feature.
Table 5b.3. The fake/real table: choose one claim to keep real, and say the rest out loud
PieceReal or fakeWhyWhat you say in the demo
Similar-ticket searchReal, on the client's sample ticketsIt is the product claim. Canned hits break on the first live query."This is searching 2,000 of your own tickets, by meaning."
Reply textReal LLM if a key and budget exist; else the fake streamer built from real resolutionsStreaming looks the same either way. Never present a template as AI."Today the draft is assembled from past fixes; the model plugs in here."
Login and usersFake: one hard-coded userSSO is a project of its own (see Module 16b)."Real login comes in week two."
Data storeFake: in memory, rebuilt at start-upNobody can tell in a 10-minute demo, and it removes a database from the critical path."Persistence is a Postgres table away."
Loading, error and empty statesRealDemos fail at the edges: a slow network, a typo query. Chunk 3 of the lab is the cheapest insurance.Nothing; they should simply not show up as blank screens.
DeploymentReal: one public URL"Works on my laptop" does not survive a client call. Deploy by hour 24."Open this link yourself."
Numbers on slidesReal: measuredOne invented number discredits all the true ones."Search took 22 ms on this laptop; the model reply starts in 4 ms."

The demo script

Write the demo as a numbered script and rehearse it. Ten minutes is plenty. The point is that you never improvise a click.

  1. Minute 0 to 1: the problem in the client's words. One ticket from their own data, on screen.
  2. Minute 1 to 3: search. Paste the ticket. Show the three similar past tickets and the resolution of the best one.
  3. Minute 3 to 5: the suggested reply. Click the button, let it type. Say aloud where it came from.
  4. Minute 5 to 7: a hard case. A ticket worded very differently from the old ones, to show meaning-search working.
  5. Minute 7 to 8: the failure you chose. Show one miss and say what you would do about it. It builds trust.
  6. Minute 8 to 10: the next step. What a pilot looks like, in weeks, with one number to track.

Keep a fallback ready: a recorded screen capture of the happy path, so a network failure costs you the live demo but not the meeting.

Decision table: which shape for which demo
SituationChooseAvoid whenTypical cost
Internal tool, under 20 users, Python-only teamStreamlit or Gradio (Python only)The customer will see it, or you need custom streaming layoutHours, not days; low polish
Client-facing demo you run yourselfFastAPI + React/Vite (this module's main path)Secrets must stay server-side and IT wants one deployableAbout 2 days for a team of one
Client-facing, one deployable, keys on the serverNext.js with a route handler proxy to FastAPIYou need no server layer at all and want the fewest partsAdds a second runtime and a hop
The client's front-end team uses AngularAngular + the same FastAPI (primer)You must show something in under a dayDepends on their conventions
Mobile app planned laterKeep the API as is; any client can call itNever: this is why the API is its own boxAlmost free if the API is clean
Boardroom translation

"A model in a notebook helps four people. A search box helps every agent on every ticket. Take Maya's numbers: 8,000 tickets a day at six minutes of hunting each is 48,000 minutes, or 800 agent-hours, a day. If search halves the hunt on only a quarter of tickets, that returns 8,000 × 25% × 3 minutes = 6,000 minutes, or 100 agent-hours, every day. The pilot's job is to measure the real figure, not to assume it."

One sentence for the executive: "We turn your old tickets into an assistant that tells an agent how you solved it last time, and types the first draft."

There are no dumb questions

Where does the 48-hour prototype end and the real product begin?
At the first thing you faked on purpose: login, persistence, evaluation of search quality and safety review. The prototype proves value; the product needs those. Writing the fake list down in the README is what keeps it from shipping by accident.
Is it dishonest to fake the reply with a template?
Only if you say it is a model. Say what it is. The streaming UI, the retrieval and the prompt-building are real and carry over unchanged when the real model plugs in, which is the point of having the same interface behind fake_stream and claude_stream.
Why not just test the search in the notebook?
A notebook hides the integration bugs: CORS, a 422 from a too-short query, a buffered stream, a slow first paint. They only show up when a browser is the client. The earlier you meet them, the cheaper they are.
How do I know the search is "good enough" to demo?
Do not guess: try 20 real tickets, note whether the top-3 contains a useful past ticket, and write the count down. Module 07 turns that into proper evaluation. For example, "14 of 20 tickets had a useful hit in the top 3" plus an honest list of the 6 misses beats a polished claim.
One real claim
Pick the one thing the demo promises and make it real; fake the rest openly.
Freeze points
Contract at hour 4; features at hour 36; code at hour 44.
Always real
The search, the error and empty states, a public URL, the numbers on slides.
Often faked
Login, persistence, the reply text (if no key), feedback.
Script
Problem, search, reply, hard case, one admitted miss, next step; plus a screen-recorded fallback.

09 · Interview radarHow This Shows Up in Interviews

Interview radar

Full-stack AI questions test whether you can connect the boxes: what runs where, what breaks in a browser, and what you cut under time pressure.

"Design a web app that shows AI-suggested replies to support agents as they work a ticket."

The real test Can you draw the three boxes, name the two streets and say what streams?

Strong answer A React page talks to one API. The API has a search endpoint that returns the top similar past tickets using embeddings, and a suggest endpoint that builds a prompt from those tickets and streams the reply over Server-Sent Events. The browser debounces the search box by about 300 ms and appends tokens to state. Secrets stay in the API. I would log the ticket, the hits shown and whether the agent used the draft, because that log is the evaluation data.

Land it The model sits behind the API and the reply streams, so the agent sees the first word in milliseconds, and every answer is logged so quality can be measured.

"How do you stream an LLM response to a browser, and what can go wrong?"

Strong answer Server-Sent Events: an HTTP response with content type text/event-stream, one event per token, a blank line between events. In FastAPI that is an async generator returning ServerSentEvent objects. On the browser I use fetch and read the body stream because I need POST. Things that go wrong:

  • A proxy or load balancer buffers the response, so tokens arrive in one lump.
  • A network chunk cuts an event in half, so the reader must keep a buffer.
  • The user navigates away, so the server must stop generating, or you pay for tokens nobody reads.

Land it Streaming is plain HTTP plus a parsing discipline: split at blank lines, keep the tail, and make every hop pass bytes through unbuffered.

"Why does my API work in curl but the browser says it was blocked by CORS?"

The real test Do you know that CORS is enforced by the browser and fixed by a server header?

Strong answer The page and the API are on different origins, for example ports 5173 and 8000. The browser sends a preflight OPTIONS request and only lets the page read the reply if the server answers with an access-control-allow-origin header naming that origin. Curl does not enforce this, so the server logs look healthy. The fix is CORS middleware with an explicit origin list, never a wildcard together with credentials.

Land it The server succeeded; the browser discarded the reply, so fix it with headers on the server, and check the Network tab first.

"When would you choose WebSockets over Server-Sent Events?"

The real test Vendor-agnostic judgment, not "WebSockets are more powerful".

Strong answer When the client must send a continuous stream too, such as voice or a shared document, or when latency in both directions matters. For a model writing a reply the traffic is one-way, so SSE is simpler: it is ordinary HTTP, it passes through proxies, and an aborted fetch cancels the stream. I would still check that the proxy does not buffer.

Land it Pick the lighter tool that matches the data direction, and move up only when you need two-way traffic.

"You have 48 hours to demo an AI prototype to a client. What is real and what is fake?"

Strong answer I pick the one claim the client cares about and make that real on their own data, say, search over their sample tickets. I keep loading and error states and a public URL real, because demos fail at the edges. I fake login, persistence and anything the client will not click, and I say so aloud. I freeze the API contract by hour 4, features by hour 36, and rehearse three times.

Land it Honesty about what is faked is what makes the real part believable.

"What is the difference between a server component and a client component in Next.js?"

Strong answer Server components run only on the server: they can await data and read secrets, and they ship no JavaScript to the browser. Client components start with 'use client', run in the browser and can hold state and handle clicks. I keep as much as possible on the server and push 'use client' down to small interactive pieces, like the box that streams the reply.

Land it Default to the server, and use client components only where the user interacts.

10 · RecapWhat You Can Do Now

  • You can draw a full-stack AI app as three boxes and two streets, and place any bug on one of them.
  • You can build a FastAPI backend with Pydantic models, a semantic-search endpoint and a Server-Sent Events streaming endpoint, and test it with TestClient.
  • You can explain CORS, and fix the "works in curl, blocked in the browser" failure.
  • You can explain why TF-IDF missed the outage ticket while MiniLM found Technical tickets, and why scores cannot be compared across models.
  • You can write a React search page with TypeScript, state, a debounced effect with cancel, and loading, error and empty states.
  • You can read a POST event stream in the browser with fetch and a buffer.
  • You can split a page into server and client components in Next.js 16, and use a route handler as a streaming proxy.
  • You can run a 48-hour prototype: what to fake, what must be real, freeze points and a demo script.
🧠 Flex your memory

From this module: without looking back, sketch the three boxes and write on each arrow what moves. Then list the five pieces of state in SearchPage.tsx.

From Module 05: that module's TF-IDF baseline scored 1.00 on its held-out test set yet misread an outage ticket as an Account ticket. Which two words made TF-IDF choose Account tickets for our outage query here, and what would you change in the search endpoint so a weak match shows "No similar tickets" instead?

Check yourself

The shared words were "out" (ticket 122) and "and" (ticket 121). The endpoint already drops zero-score hits; a stronger fix is a minimum score cut-off per backend, measured on your own tickets, because 0.175 means different things in TF-IDF and MiniLM.