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."
01 · The hookA Model in a Notebook Cannot Win a Client
"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."
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 know (backend) | It becomes (this module) |
|---|---|
| A REST endpoint with a request DTO | A FastAPI endpoint with a Pydantic model. The model is the DTO and the validator and the OpenAPI schema. |
| A DB query ordered by an index | A search that orders past tickets by a similarity score. |
| Chunked HTTP response, long polling | Server-Sent Events: one open response, many small messages. |
| A template engine rendering HTML | A React component: a function from data to a piece of screen. |
| Same-origin policy, CORS headers on a gateway | The 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.
- 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).
- The API. It is the only box allowed to touch the model. It has 2 endpoints,
/searchand/suggest, and 7 automated tests guard them. Everything the browser may ask for is listed here and nowhere else. - 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.
| Stage | The file you open | The call that runs | What flows out |
|---|---|---|---|
| Browser | frontend/src/SearchPage.tsx | fetch(API + '/search', {method: 'POST', ...}) | A JSON body such as {"query": "...", "k": 5} |
| Wire | (browser dev tools, Network tab) | An OPTIONS preflight, then the real POST | Headers; the CORS answer decides whether the page may read the reply |
| API | backend/app.py | @app.post("/search") then top_hits() | A SearchResponse: query, backend name, list of hits |
| Model + index | build_index() in app.py | MATRIX @ ENCODE([query])[0] | One score per past ticket, highest first |
| API, streaming | backend/app.py | @app.post("/suggest", response_class=EventSourceResponse) | event: token lines, one per word |
| Browser, streaming | frontend/src/sse.ts | readSse(res), an async generator | React state reply growing one word at a time |
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.
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
- Import
numpy, the library for lists of numbers. - Make the query arrow Q as a two-number array, (0.6, 0.8).
- Make a dictionary of three tickets, each with its own two-number arrow.
- Loop over the tickets. For each,
np.linalg.normgives the arrow's length (should be 1.00). query @ vecis the dot product: multiply matching numbers and add. That is the score.- Print the ticket name, its length and its score, to three decimal places.
# 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}")
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
- Q, the new ticket. Its arrow is (0.6, 0.8): a little money, mostly machines. Every other arrow is compared against this one.
- 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.
- 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
- Build a TF-IDF vectoriser over the 25 past ticket texts (words and two-word pairs; word counts are damped with
sublinear_tf). - Turn the outage query into an arrow and list which of its words the vocabulary knows at all.
- For tickets 122, 121 and 109, turn the ticket into an arrow too.
- Multiply the query and ticket arrows axis by axis. Any axis that survives is a shared word; print it with its contribution.
- Add the contributions. That sum is the cosine score the search used.
"""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}")
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
- Set
HF_HUB_OFFLINE=1so the library uses the cached model and never reaches for the network. - Import
build_indexfrom the API rung that supports both backends, and the ticket list. - Define three queries: the outage one, a locked-out-after-new-phone one, and a "money taken twice" one.
- For each backend,
tfidfthenminilm, build the index (this loads the model once). - 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.
"""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}")
--- 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)
- 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.
- 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.
- 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.
Questions you might be asking now
Four questions that come up right after the scores appear. They all reuse the three arrows from Fig. 5b.2: Q = (0.6, 0.8), A = (0.96, 0.28), B = (0.28, 0.96), C = (0.80, 0.60).
Is a score like 0.960 a percentage? Does it mean 96% sure?
No. It is a measure of how closely two arrows point the same way, from −1 (opposite) through 0 (unrelated) to 1 (identical direction). It is not a probability and it is not "96% correct".
The score is only good for ordering. Look at what happens to the numbers when we change the story:
- Same direction. If a ticket were exactly Q, (0.6, 0.8), the score is 0.6 × 0.6 + 0.8 × 0.8 = 0.36 + 0.64 = 1.000.
- Unrelated. A ticket at (0.8, −0.6) scores 0.8 × 0.6 + (−0.6) × 0.8 = 0.48 − 0.48 = 0.000. It is a right angle to Q.
- Real data. In our run, MiniLM's best hit for the outage query scored only 0.331 and was still the right kind of ticket. Real sentence arrows rarely line up perfectly.
A score ranks hits against each other; it is not a probability, and its scale changes when you change the model.
Why did TF-IDF put a locked-out-phone ticket first for a database outage?
Because the only word the two sentences share is "out". TF-IDF can only compare words it has seen in the 25 tickets, and it had never seen "Postgres", "cluster", "throwing" or "timing".
- Count the query's words. "prod Postgres cluster throwing 500s and timing out" has 8 words.
- Keep the known ones. Only "and" and "out" appear in the ticket vocabulary. Six of eight words are invisible to the search.
- Find overlaps. Ticket 122 ("I locked myself out after changing my phone number") contains "out": contribution 0.1752. Ticket 121 contains "and": 0.1550. Ticket 109 contains neither: 0.0000.
- Sort. 0.1752 > 0.1550 > 0.0000, so 122 wins.
This is why marker 1 in Fig. 5b.3 shows two Account tickets. The ranking is mathematically correct and useless.
Word-counting search only sees words it has already met; meaning-search does not need the same word.
What are the 384 numbers MiniLM gives each ticket?
They are the coordinates of an arrow, exactly like our (0.6, 0.8), but with 384 coordinates instead of 2. Nobody labelled the axes. The model learned them so that sentences with similar meanings end up with similar coordinates.
The scoring step does not change. For 384 numbers it is the same recipe as in the pencil exercise: multiply matching positions, add all 384 products. In the program that is one line, MATRIX @ ENCODE([query])[0].
Here is the honest limit: you cannot read the axes. Coordinate 17 does not mean "money". You can only trust the arrows by testing them, and that is what the evaluation module is for.
An embedding is an arrow with many coordinates; scoring it is the same multiply-and-add you did by hand.
So is semantic search just keyword search plus a synonym list?
No, though from outside it can look that way. A synonym list is written by a person and covers the pairs they thought of. An embedding model has learned from huge amounts of text which phrases appear in similar situations, so it also links pairs nobody listed ("timing out" and "connection pool exhausted").
The cost is control. With a synonym list you can add one line and see the fix. With an embedding model you cannot patch one pair; you change the model or add a keyword layer beside it.
Synonym lists are hand-made and patchable; embeddings are learned and broader but cannot be fixed one word at a time.
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.
- The wire. Every message is an
event:line plus adata: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. - 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.
- State. The page keeps a string called
reply. Each token event appends itstext. 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.
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.
- The preflight question. Because our request has a JSON body and a custom
Content-Type, the browser first sendsOPTIONS, naming the page's origin. No data moves yet. - 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 fromhttp://evil.examplegot400 Bad Requestand no allow-origin header. - 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: 600seconds. - 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.
-
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
- Import the
FastAPIclass. - Create the app object. Everything else attaches to it.
@app.get("/health")registers the function below it for GET requests to/health.- 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.pyprintsrung 1 /health -> {'status': 'ok'}. To see it live:uvicorn app_1_hello:app --port 8000, thencurl localhost:8000/health. - Import the
-
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
SearchRequestsays a request needsquery(2 to 300 characters) and may carryk(1 to 10, default 3).Hitis one search result: id, category, text, resolution, score.SearchResponsewraps the query, the backend's name and a list of hits.- The
/searchendpoint takes aSearchRequest. FastAPI parses the JSON body for us and answers422if it does not fit. - The stub builds hits from the first
ktickets 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 offlinefrom 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)BaseModelandField(...)— a Pydantic class whose type hints are enforced, with limits such asmin_lengthandge(greater or equal).python rung_checks.pyprintsrung 2 /search -> 200 [101, 102] stub, thenrung 2 bad input -> 422 String should have at least 2 characters. -
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
build_index()collects the 25 ticket texts and fits a TF-IDF vectoriser on them.- It returns two things: an
encodefunction (text to arrows) and the matrix of all 25 ticket arrows. ENCODE, MATRIX = build_index()runs once at import time, not per request, so a request does not re-train anything.top_hits()encodes the query, multiplies the matrix by it (25 scores), sorts, keeps the best k and drops zero scores.- The
/searchendpoint now callstop_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 offlinedef 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.argsortreturns positions in score order.python rung_checks.pyprintsrung 3 /search -> tfidf [(122, 0.1752), (121, 0.155)]for the outage query, thenrung 3 no overlap -> []for "zzzz qqqq". The first line is the wrong answer from Fig. 5b.3; chunk 4 fixes it. -
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
- Read
SEARCH_BACKENDfrom the environment, defaulting to "tfidf". build_index(backend)now takes the name. If it is "minilm", it importssentence_transformerslate, loadsall-MiniLM-L6-v2and encodes text withnormalize_embeddings=Trueso every arrow has length 1.- Otherwise it builds the same TF-IDF encoder as chunk 3.
- 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.pyprints the two blocks you saw in the output above: for the outage query,tfidfgives#122 (0.175), #121 (0.155)andminilmgives#112 (0.331), #109 (0.295).python rung_checks.pyprintsrung 4 default backend -> tfidf. - Read
-
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
- Two new imports:
asyncioforsleep, andEventSourceResponseplusServerSentEventfromfastapi.sse. SuggestRequestneeds atickettext of 2 to 2,000 characters.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.fake_stream()is an async generator: it yields the reply one word at a time and waits 20 ms between words.suggest()finds the top 3 similar tickets and yields acontextevent with their ids.- It then yields one
tokenevent per word, counting them, and finishes with adoneevent holding the count.
app_5_stream.py (added lines; plus two new imports at the top)runs offlineimport 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 defwithyield— an async generator.response_class=EventSourceResponsetells FastAPI (0.141 and later) to send each yieldedServerSentEventas one SSE message, with keep-alive pings.python rung_checks.pyprintsrung 5 /suggest -> 47 events; first 3 and last:then the linesevent: context/data: {"ids": [101, 108, 105]}, twotokenevents ("Hi, ","thanks ") and finallyevent: done/data: {"tokens": 45}. 47 events = 1 context + 45 tokens + 1 done. - Two new imports:
-
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
claude_stream()importsAsyncAnthropiclate, so offline runs do not need the SDK installed.- 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. client.messages.stream(...)opens a streaming call; the model id comes fromANTHROPIC_MODEL, defaulting toclaude-sonnet-5. Check the current model list before relying on that default.async for text in stream.text_streamyields each piece of text as it arrives.- In
suggest(),LLM=claudepicksclaude_stream; otherwise the fake streamer runs. The rest of the endpoint is unchanged.
app_6_claude.py (added lines)needs API keyasync 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()andstream.text_stream— the Messages API's streaming helper. Module 06 teaches the SDK itself; here it is a plug.python rung_checks.pyprintsrung 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:appstreams real text with the identical event format. Not run here: no API key in this environment. -
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
- Import
CORSMiddleware. - Read
CORS_ORIGINSfrom the environment (comma-separated), defaulting to the Vite dev address. app.add_middlewarewraps every response: it answers preflightOPTIONSrequests and addsaccess-control-allow-originfor listed origins only.- Only GET and POST, and only the
Content-Typeheader, are allowed: the smallest list that works.
app_7_cors.py (added lines)runs offlinefrom 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.pyprintsrung 7 preflight -> 200 http://localhost:5173. The same OPTIONS request fromhttp://evil.examplegets no allow-origin header. - Import
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.
# 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.
/search request through the finished app.py, with the real values from the outage query.- The body. The browser sends the query text and
k. Nothing has been checked yet. - The check. Pydantic compares the body with
SearchRequest. A 1-character query orkof 99 stops here with a 422 and a plain message, and the search code never runs. - 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.
- 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.
- Pick. The best 2 scores become
Hitobjects: 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.
- 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.
- 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.
- 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
- Create one
TestClientaround the realapp. parse_sse()splits a stream body at blank lines and turns each block into an (event name, JSON data) pair.- The health test checks the JSON.
- The search test posts the database query and checks that ticket 109 is first and the scores are sorted.
- The no-overlap test checks that gibberish returns an empty list, not an error.
- The bad-input test posts a 1-character query and a
kof 99, and expects422both times. - 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.
- The CORS test sends a preflight from the Vite origin (must be allowed) and from
evil.example(must not).
# 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
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.
$ 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.
- 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.
- 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. - 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.
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.
@app.post("/suggest",1 response_class=EventSourceResponse)2
async def suggest(req: SuggestRequest):3
yield4 ServerSentEvent(event="token",5 data={"text": piece})6
- POST, not GET. The ticket text goes in the body, not the URL. People pick GET here because the browser's built-in
EventSourceonly does GET, then find tickets too long for a URL. - The response class. It sets
Content-Type: text/event-streamand turns each yielded value into SSE text. Forget it and FastAPI returns one JSON list when the generator ends, with no streaming at all. - The function is async. While it waits for the model, the server can serve other requests. A plain
defthat sleeps would hold a worker thread per open stream. yield, notreturn. Eachyieldsends one event and keeps the function alive. Areturnends the response. This is the single easiest word to get wrong.- 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 tomessage. - 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.
Tonight's talk: the browser and the API argue over the question, "Who is the real product?"
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.poston a function; type hints are the contract.- Pydantic
BaseModel - The request/response shape; violations return
422automatically. - Build once
- Fit the index at start-up (
ENCODE, MATRIX = build_index()), never per request. - SSE endpoint
response_class=EventSourceResponse, anasync defthatyieldsServerSentEvent.- Event order
- One
context, Ntoken, onedonein 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
TestClientis 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
type Hit = {...}names a shape: id and score are numbers, text is a string, andnote?may be missing.type Status = 'idle' | 'loading' | 'error' | 'done'says a value is exactly one of these four words. Anything else is a compile error.label(h: Hit): stringtakes a Hit and returns a string. Pass it the wrong shape and the checker complains.describecheckss === 'done'and the list length. After a check, TypeScript knows more: this is called narrowing.- Build a one-item list typed as
Hit[]and print four results. The last comment shows an error the checker would catch.
// 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
#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.
Hit model and the page's Hit type describe the same six pieces of data in two languages.- The Pydantic side. The shape lives in
app.py. Pydantic enforces it at run time on every response. - The TypeScript side. A hand-copied type of the same shape. Python
intandfloatboth become TypeScriptnumber;strbecomesstring;list[Hit]becomesHit[]. - 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
- Import
useState, React's tool for remembered values. - The component is an exported function; React calls it to get the screen.
useState(0)returns a pair: the current value (count) and a function to change it (setCount). The first time,countis 0.- It returns a button. Clicking calls
setCount(count + 1). - React sees the state changed, calls the function again with the new count and updates the button text. Nothing else touches the screen.
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.
- The first render. React calls
Counter()once.useState(0)givescount = 0, so the button says "clicked 0 times". - After a click. The click handler runs
setCount(0 + 1). React stores 1 and callsCounter()again, anduseStatenow returns 1 instead of 0, so the button says "clicked 1 times". - 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
secondsis remembered state that starts at 0.useEffectruns after the first screen is drawn. It starts a timer that adds 1 tosecondsevery 1,000 ms.setSeconds((s) => s + 1)uses the previous value, so quick updates do not lose counts.- The returned function clears the timer. React calls it when the component goes away, so timers never leak.
- The empty list
[]means "no dependencies": run once, at the start. - The component returns a paragraph showing the current count.
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.
- 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.
- 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.
- 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
- Type the text "database pool" at one key every 120 ms: build a list of key times (0, 120, 240, … 1440).
- Print the key count (13) and the last key time. Without debounce, every key is one call.
- 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.
- Each key replaces the pending timer (
pendingSince = t). - After the loop, the last timer survives and fires: count one more call, and print its time (last key + 300).
// 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`)
keys typed: 13, last key at 1440 ms
no debounce: 13 API calls
debounce 300 ms: 1 API call, at 1740 ms
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.
| Option | What it promises | Choose it when |
|---|---|---|
EventSource | Built 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 + ReadableStream | Any 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:
- URL length. A long ticket may exceed limits (many servers cap a URL at about 8,000 characters), and logs record every URL.
- Secrets. A token in the URL ends up in server logs and browser history.
- The upside you give up.
EventSourcereconnects 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:
- Add the new chunk to the end of
buffer. - Split the buffer at every blank line (
\n\n). - 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()). - Every remaining piece is a complete event: read its
event:anddata:lines and yield it.
- The chunk. Chunk 1 ends in the middle of the word "token"; chunk 2 starts with "en". The network does not respect event boundaries.
- The events. Chunk 1 yields one whole event (
context). Chunk 2 yieldstoken "Hi, "because its tail from chunk 1 plus its own start made a complete block. Chunk 3 yields two events,token "thanks "anddone. - 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:
- Key "d" at 0 ms.
querybecomes "d" (fewer than 2 characters), so the effect sets status to idle and returns without a timer. - Key "b" at 100 ms.
querybecomes "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. - Quiet until 400 ms. The timer fires and calls
/search. - 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.
- The keys. "d" at 0 ms, "b" at 100 ms and "o" at 250 ms. Each change of
queryre-runs the effect, so there are three effect runs. - 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.
- 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
/searchcall, 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.
- 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.
- 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.
- With abort. The cleanup calls
controller.abort()on the first request. Itsfetchthrows anAbortError, 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.
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 buildpasses (TypeScript and Vite) at every one of the six chunks.- Typing 13 characters sends one
/searchrequest, 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.pywith 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.
-
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
type Hitcopies the API'sHitmodel: id, category, text, resolution, score.SAMPLEis a fixed list of two hits written by hand, using real tickets 109 and 112.SearchPageis the component. It returns a page title and a list.SAMPLE.map(...)turns each hit into one<li>. Thekey(the ticket id) lets React track each item when the list changes.- Each card shows the category badge, the text, the score to two decimals and the resolution.
ladder/SearchPage.1-static.tsxbuilds offlinetype 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. Thekeymust be a stable unique value, never the array position.npm run buildends withdist/assets/index-Cj2fi5VK.js 220.29 kB │ gzip: 68.94 kBand✓ built. Opened in a browser it shows two cards: tickets 109 and 112, scores 0.43 and 0.31. -
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
- Import
useState. APIis the server address: theVITE_API_URLenvironment value if set, elsehttp://localhost:8000.queryremembers what is typed;hitsremembers the last results (starting empty).runSearchPOSTs{query, k: 5}as JSON to/searchand waits for the reply.res.json()parses the body;setHits(data.hits)stores it, and React redraws the list.- The input is controlled: its value comes from state and every keystroke updates state. The button calls
runSearch. The list now maps overhitsinstead ofSAMPLE.
ladder/SearchPage.2-fetch.tsx (changed and added lines)builds offlineimport { 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;awaitpauses until the reply arrives.npm run buildends withindex-DrtFZGfS.js 220.31 kB │ gzip: 68.95 kB. Withuvicorn app:apprunning, 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. - Import
-
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
type Statussays the page is exactly one of: idle, loading, error, done.- A
statusstate starts as idle. runSearchsets loading first, then wraps the call intry/catch.- If the server answers with a non-OK status,
throwjumps tocatch, which sets error. A stopped server also lands incatch. - On success it stores the hits and sets done.
- 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 offlinetype 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 { ... }andcond && <element>— handle failure, and draw something only when a condition holds.npm run buildends withindex-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." -
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
- Import
useEffect. The starting value ofqueryreads?q=from the page address, so a link can pre-fill the box (handy for screenshots and demos). - The effect depends on
[query]: it runs after every change of the text. - If the text has fewer than 2 characters (the API's minimum), reset to idle with no hits and stop.
- Otherwise create an
AbortControllerand start a 300 ms timer. - When the timer fires it sets loading, calls
/searchwithsignalattached, then stores the hits and sets done. - An
AbortErroris expected when we cancel, so it must not show the error message. - 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 offlineimport { 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, andAbortControllerwithsignal— debounce plus cancellation.npm run buildends withindex-BFWL-EQ-.js 220.88 kB │ gzip: 69.18 kB. Type "database pool" at normal speed and watch the Network tab: one/searchrequest.node debounce_sim.tsprinteddebounce 300 ms: 1 API call, at 1740 msfor the same text. - Import
-
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
SseEventis the shape handed back: an event name and its decoded data.readSseis an async generator (async function*): it canyieldmany values over time.- Get a reader for the response body and a decoder that turns bytes into text.
bufferstarts empty. - Loop: ask the reader for the next chunk; when it says done, stop.
- Decode the chunk and append it to
buffer(stream: truekeeps a half-finished character for next time). - Split the buffer at blank lines. The last piece may be half an event, so
pop()removes it and it becomes the new buffer. - For each whole block, read its
event:anddata:lines, parse the data as JSON andyieldthe 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*andfor await— produce and consume values that arrive over time.TextDecoderturns bytes into text.node sse_demo.ts(infrontend/examples) feeds three torn chunks and printsnetwork chunks: 3, thencontext {"ids":[102,107]},token {"text":"Hi, "},token {"text":"thanks "}anddone {"tokens":2}. Four whole events from three torn chunks. The component is unchanged, sonpm run buildstill gives220.88 kB, because nothing importssse.tsyet. -
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
- Import
readSsefrom the new file. - Two new pieces of state:
reply(the text so far) andstreaming(are we mid-reply). suggest()clears the reply, sets streaming, then POSTs the typed text to/suggest.for await (const ev of readSse(res))loops once per event as they arrive.- On a
tokenevent,setReply((r) => r + text)appends the new word to the previous value. finallysets streaming back to false even if the call fails.- 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 offlineimport { 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 buildends withindex-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. - Import
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.
// ── 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.
- idle. Nothing typed, or under 2 characters. The page shows only the box. A 300 ms pause with enough text moves it to loading.
- loading. The call is in flight. The page shows "Searching..." and the earlier hits are still visible, so the list does not flash empty.
- 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.
- 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.
$ 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_URLoverrides 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.
- The server component.
page.tsxruns only on the Next.js server. It calls/searchdirectly and sends finished HTML, with the 3 hits already inside. Its code and itsAPI_URLnever reach the browser. - The route handler.
app/api/suggest/route.tsis 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. - The client component.
Suggest.tsxstarts 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/suggeston its own origin, so no CORS is needed.
Step-by-step: what the three Next.js files do, in plain English
page.tsx(server):export const dynamic = 'force-dynamic'asks Next.js to run it on every request, not once at build time.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.- The page is an
asyncfunction: server components mayawaitdata. It lists the 3 hits and renders<Suggest />. Suggest.tsx(client): holds the typed ticket and the reply; itsgo()POSTs to/api/suggestand reads the stream with the same buffer-and-split loop assse.ts, appending each token.route.ts:POSTforwards the request body to FastAPI's/suggest.- It returns
new Response(upstream.body, ...): the body is a stream, handed through without reading it, withtext/event-streamandno-cacheheaders.
// 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>
)
}
'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>
)
}
// 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.
$ 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?
| Layer | We use | Alternatives | Why this one | Switch when |
|---|---|---|---|---|
| API framework | FastAPI 0.141 + Pydantic 2 | Flask; Django Ninja; Litestar; Express/Node | Type 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. |
| Frontend | React 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 transport | Server-Sent Events over fetch | WebSockets; long polling | Plain 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. |
| Language | TypeScript 7 for the page | Plain JavaScript | The 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 helpers | Plain fetch plus our 25-line sse.ts | Vercel 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 backend | In-memory NumPy matrix, TF-IDF or MiniLM | Chroma; 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, mayawaitdata, ships no JS. - Client component
- File starts with
'use client'; has state and events; ships JS. - Route handler
app/.../route.ts; exportsPOSTetc. Use it as a thin streaming proxy (BFF).- Streaming through a proxy
- Return
upstream.bodyunread; never.text()it; keepno-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.
- 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.
- 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.
- 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.
| Piece | Real or fake | Why | What you say in the demo |
|---|---|---|---|
| Similar-ticket search | Real, on the client's sample tickets | It is the product claim. Canned hits break on the first live query. | "This is searching 2,000 of your own tickets, by meaning." |
| Reply text | Real LLM if a key and budget exist; else the fake streamer built from real resolutions | Streaming 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 users | Fake: one hard-coded user | SSO is a project of its own (see Module 16b). | "Real login comes in week two." |
| Data store | Fake: in memory, rebuilt at start-up | Nobody 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 states | Real | Demos 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. |
| Deployment | Real: one public URL | "Works on my laptop" does not survive a client call. Deploy by hour 24. | "Open this link yourself." |
| Numbers on slides | Real: measured | One 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.
- Minute 0 to 1: the problem in the client's words. One ticket from their own data, on screen.
- Minute 1 to 3: search. Paste the ticket. Show the three similar past tickets and the resolution of the best one.
- Minute 3 to 5: the suggested reply. Click the button, let it type. Say aloud where it came from.
- Minute 5 to 7: a hard case. A ticket worded very differently from the old ones, to show meaning-search working.
- Minute 7 to 8: the failure you chose. Show one miss and say what you would do about it. It builds trust.
- 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.
| Situation | Choose | Avoid when | Typical cost |
|---|---|---|---|
| Internal tool, under 20 users, Python-only team | Streamlit or Gradio (Python only) | The customer will see it, or you need custom streaming layout | Hours, not days; low polish |
| Client-facing demo you run yourself | FastAPI + React/Vite (this module's main path) | Secrets must stay server-side and IT wants one deployable | About 2 days for a team of one |
| Client-facing, one deployable, keys on the server | Next.js with a route handler proxy to FastAPI | You need no server layer at all and want the fewest parts | Adds a second runtime and a hop |
| The client's front-end team uses Angular | Angular + the same FastAPI (primer) | You must show something in under a day | Depends on their conventions |
| Mobile app planned later | Keep the API as is; any client can call it | Never: this is why the API is its own box | Almost free if the API is clean |
"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_streamandclaude_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
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
fetchand 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.
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.