What you'll learn: By the end of this lesson you will be able to say what makes a screen that calls a language model different from an ordinary data screen, draw the browser, server and provider split and say why the key stays on the server, choose between waiting for a whole reply and streaming it, model a reply as a small state machine with a partial result, plan for errors that arrive after a 200 status and for connections that drop silently, treat model output as untrusted input, and name the other lessons of this module that each deepen one part.
Think of ordering at a restaurant where the chef cooks everything to order. The kitchen is slow, so the waiter brings the bread first and then each course as it is ready. Sometimes the kitchen runs out halfway through your meal. Sometimes a dish arrives that looks right and is wrong. You can cancel, but the kitchen may already have started. A good restaurant designs for all of that: it shows progress, it lets you stop, it says plainly when something went wrong, and it never serves a dish without a check. An AI feature in a front end is that restaurant. The model is the kitchen, and the front end is the waiter.
The running example is a help assistant panel on an online store's dashboard: a text box, a growing answer, a Stop button and a Retry button. The numbers in this lesson that are not from a documentation page are illustrative.
The core idea
- A model call is an unusual network call. It is slow compared with a normal API call, the answer is produced piece by piece, it can fail after it has already started to answer, and its content can be wrong. Each of those four properties changes the front end.
- The browser should call your server, and your server should call the model provider. The key, the limits, the logging and the shape of the stream belong on your side of the line.
- Every reply is a small state machine with a partial result. A reply can be waiting, streaming, complete, stopped, failed or cut short, and the screen must say which, while keeping whatever text arrived.
Three illustrations run through the lesson: a minimal example (a one-shot "summarize" button), a realistic example (the help panel with streaming, Stop and Retry) and a failure example (a connection that drops and leaves a half-answer that looks finished).
What is different about a model call
A normal screen asks for data that exists, gets it in one response, and either succeeds or fails. A model call differs in ways that matter to architecture.
| Property | Ordinary API call | Model call | What the front end must do |
|---|---|---|---|
| Time | Usually short and predictable | OpenAI's production guide says latency is mostly set by the model and by the number of tokens generated | Show progress; never leave a blank screen |
| Shape of the answer | One complete response | Many small pieces, if streaming is on | Keep a growing text and apply pieces in order |
| Failure | Fails before any data, or succeeds | Can fail after a 200 status and after part of the answer arrived | Keep the partial answer and say it is partial |
| Content | Deterministic for the same input | Free text that may be wrong or unsafe | Treat it as untrusted input; offer feedback |
| Cost and limits | Often invisible to the page | Anthropic's stream reports cumulative token usage, and requests can be rate limited or overloaded | Let the server enforce limits and report them as a clear state |
Streaming does not make the model faster. The OpenAI guide says that setting stream: true makes the model start returning tokens as soon as they are available, which shortens the wait for the first token but not the time to produce all of them. That is why a streamed answer feels quicker: the user starts reading earlier.
Three parts, three trust levels
Figure 1. The browser, your server and the provider
How to read this: the page never talks to the provider. Its request goes to your endpoint, which adds the secret, applies limits and records what happened. The reply travels back along the same path as a stream, drawn in Figure 2.
Why the key stays on the server: Anthropic's own example sends the API key in an x-api-key request header, and OpenAI's production guide says to avoid exposing keys in your code and to store them in a secure location, using environment variables or a secret manager. Anything shipped in page JavaScript can be read by every visitor, so a browser that held the key would let anyone spend your quota. This is reasoning from those two statements, not a quote.
Your endpoint is also where the stream is shaped. The provider's event format is the provider's, and its documentation says new event types may be added. If the page consumed it directly, every provider change would reach every browser. An adapter on your server turns the provider's events into your own small format (text pieces, a terminal event, an error event), and the page depends only on that. The lab of the next lesson, Streaming LLM Responses in the Browser, uses such a format. This is a design choice, not a rule from any provider.
One reply, step by step
Figure 2. A streamed reply, with a Stop
How to read this: the answer is built on the page from many small messages. Stop acts on the page at once, and the server then stops reading. What the provider does with a request that was closed early, and whether it still counts the tokens, is something to check in its documentation.
On the page this is a fetch with a streamed body. MDN describes Response.body as a ReadableStream, and its read() resolves with { value, done } chunks until the stream closes or errors. The browser's EventSource is built for server-sent events, but MDN documents only a URL and a withCredentials option for its constructor, with no documented place for a request body or custom headers. A prompt is usually sent as a POST body with an auth header, which is why many AI clients read a fetch body and parse the event stream themselves. Server-Sent Events in Depth teaches the format, and Polling, Server-Sent Events and WebSockets compares the transports.
To stop, the page calls abort() on an AbortController whose signal it passed to fetch. MDN says the fetch() promise then rejects with an AbortError, and that if the abort happens after fetch() has resolved but before the body is read, reading the body rejects with an AbortError. A Stop is therefore an error you caused: handle it as a user action, not as a failure.
A reply is a state machine
Figure 3. The states of one reply
How to read this: only the streaming state accepts text pieces. Every other state is final for that reply, and each keeps the text received so far. A new Send starts a new reply.
Two of these states are easy to miss. Failed and interrupted are different. A provider can signal an error inside the stream: Anthropic's documentation says that after a stream starts the API has already returned a 200, so it sends an error as an error event, for example overloaded_error during high usage. A connection can also drop with no event at all. The same documentation says that on a mid-stream connection drop no error event arrives. If the page treats "the stream ended" as "the reply is complete", a dropped connection leaves a half-answer on screen that looks finished. The rule is simple: a reply is complete only when a terminal event said so.
The state also decides what the screen shows. The partial text stays visible in every ending. The status line says what happened: writing, complete, stopped, failed or cut short. Retry appears for the last three. Error, Loading and Empty States teaches the same discipline for ordinary data, and the idea carries over with one addition: here "error" can arrive with half a screen of useful content already drawn.
What to do with partial results
Both major providers document partial output. Anthropic's streaming guide describes recovering an interrupted request by capturing the partial response and sending a continuation request, and says tool-use and thinking blocks cannot be partially recovered: you can resume from the most recent text block. OpenAI's guide notes that streaming makes it harder to moderate content, because partial completions are harder to evaluate, and that moderation scores come only after the full output is available.
For the front end this means three questions. Do you keep the partial text? Almost always yes: the user can read it, copy it or ask for more. Can the user continue it? Only if your server can build a continuation request, and the second part is a new request. Is it safe to show before it is checked? If a check needs the full text, a stream is shown before the check, so decide whether that is acceptable or whether the feature should wait.
Stream or wait?
Figure 4. Choosing how to deliver a reply
user doing
with the answer?"} -->|"reads long text"| R{"Must the whole
text be checked
first?"} Q -->|"needs all of it
to act, short"| W["Wait for the
whole response"] Q -->|"structured data
for a component"| J{"Can the UI use
half a structure?"} R -->|"yes"| W R -->|"no"| S["Stream: status, partial text,
Stop, Retry"] J -->|"yes"| S J -->|"no"| W
How to read this: streaming is for long text read from the top. Short or structured answers, and answers that must be checked as a whole, usually wait. A half-built JSON object is rarely useful to a component.
The structured-data branch has a documented reason. Anthropic's streaming guide says that for tool use the deltas are partial JSON strings, and that you can accumulate them and parse the JSON once the block ends. A page that needs an object waits for the end of the block, and a page that only shows text can draw as it goes.
Showing a stream without hurting the page
A stream can deliver many small pieces, and drawing the whole answer again for each one makes the page slow. The cheaper pattern has two parts. First, apply pieces once per frame: collect the pieces that arrive between two frames and update the screen once. MDN describes requestAnimationFrame as calling your function before the next repaint, at a rate that generally matches the display refresh rate, and paused in most browsers in background tabs. Second, redraw only the end: finished paragraphs do not change, so only the paragraph being written needs to be redrawn. The next lesson builds and tests both.
Assistive technology needs a different approach. MDN says aria-live="polite" is for updates that matter but are not so rapid as to be annoying, and that a screen reader speaks changes when the user is idle. A region that changes with every piece would be unusable. The usual design announces only the status ("Writing the reply", "Reply complete", "Stopped") in a live region and leaves the growing text as ordinary content that the user can read when they choose. Accessible Forms and Dynamic Content covers live regions in more detail.
Where the state lives
Most of the state of a reply lives in the page and dies with it: the status, the text so far, the abort controller. The conversation as a whole is different. It is what the user will expect to see tomorrow, on another device, and what your server needs for context in the next request. That belongs on the server, and the page keeps a copy it can show quickly. Local vs Global State in the Front End is the starting point for deciding which is which. How a conversation is modelled as messages is the subject of a later lesson in this module, Chat Interface State and the Message Model.
| Piece of state | Lives in | Why |
|---|---|---|
| Status and partial text of the current reply | The page (a reducer or similar) | Changes many times a second and is useless after the reply ends |
| Abort controller of the current request | The page | Only the page can cancel its own request |
| The conversation (messages, feedback) | Your server, with a copy in the page | Must survive reload, and the server needs it for context |
| API key and provider limits | Your server | A secret and a shared resource |
| Provider-specific event details | Your server's adapter | So provider changes stay out of the browser |
Illustrations
Illustration 1: the minimal example. A "Summarize this order" button sends the order id to your endpoint and waits. The summary is short and the user needs all of it, so no stream is needed: a loading state, an error state and a result. It is still a model call, so the server holds the key and applies a limit, and the page draws the text as untrusted.
Illustration 2: the realistic example. The help panel streams. Send shows "Writing the reply" at once, text appears once per frame, and Stop is enabled while streaming. If the provider sends an error event, the partial text stays and the status says it failed. Retry sends the same prompt again as a new reply, and the server saves the finished conversation, not the half-drawn state.
Illustration 3: a failure. The connection drops after two paragraphs and the byte stream just ends. A page that marks the reply complete at that point shows two paragraphs as the whole answer, and the user acts on a half-finished step. The fix is the rule from the state machine: complete means a terminal event arrived.
Trust and safety, briefly
The model's text is data from outside your system, shaped in part by whatever is in the prompt and the documents it was given. Draw it as text or as sanitized markup, never as raw HTML, and never let it choose a URL or an action without the checks you would apply to a form field. Prompt injection, output safety and the patterns for trust and citations are separate lessons in this module, Prompt Injection and Output Safety in the UI and AI UX: Trust, Citations and Feedback. The architectural point here is that output crosses a trust boundary on its way into the page.
Trade-offs
| Choice | Gain | Cost |
|---|---|---|
| Stream the reply | Reading starts earlier; the user can stop | Partial states, more code, harder to check before showing |
| Wait for the whole reply | One state change; easy to validate | A long wait with no progress |
| Browser calls the provider | Fewer hops | Exposes keys; no central limits or logging |
| Browser calls your server | Keys, limits and logs in one place | One more hop to build and run |
| Your own event format | Provider changes stay on the server | An adapter to write and test |
| Draw every piece at once | Simplest | Many redraws; heavy on the main thread |
| Draw once per frame, redraw only the tail | Smooth, cheap | A scheduler and a block splitter to maintain |
Build it
This lesson has no lab. The next lesson, Streaming LLM Responses in the Browser, has one: a deterministic fake token stream (a model, with no real model and no network) and the pure TypeScript core that decodes it, tracks the six states above, batches pieces per frame and handles Stop.
In practice: a help assistant that looked finished and was not
This is a realistic scenario, not a case history. It is a composite built from common production patterns. It describes no specific company or product, and every number in it is an illustrative assumption.
The situation
A store adds a help assistant to its seller dashboard. The first version was built quickly: the page sends the prompt straight to the model provider with a key from a build-time environment variable, reads the stream with fetch, appends each piece to a string, and shows the string. The reply is marked complete when the stream ends.
Starting architecture
Figure 5. Starting point: the page talks to the provider
How to read this: nothing of yours sits between the page and the provider, so there is no place for limits, logs, a changed event format or a hidden key.
Options considered
| Option | What it fixes | What it costs | Risk |
|---|---|---|---|
| Keep the direct call, restrict the key | Nothing structural | A restriction that may not exist for this provider | The key is still in the bundle |
| Add a thin server endpoint that forwards the stream | Key out of the page; one place for limits and logs | A server hop to run and monitor | Forwarding raw events keeps provider details in the page |
| Endpoint plus adapter to your own event format, and a reply state machine in the page | Key, limits and logs on the server; provider changes stay out of the page; partial endings are explicit | An adapter and a reducer to build and test | More code than the first version |
The decision
| Field | Decision record |
|---|---|
| Context | The first version holds a secret in the page, trusts the end of the stream as "complete" and has no limits. |
| Decision | Add an endpoint that holds the key, applies a per-user limit, and converts the provider's events into three of its own (text piece, done, error). The page keeps a reply state machine with six states and marks a reply complete only on a done event. |
| Consequences, good | Secrets are off the page; a cut stream is shown as cut; the page survives provider event changes. |
| Consequences, bad | A new service to operate, and an adapter to keep in step with the provider's documentation. |
| Revisit when | The product needs tool calls or citations (the event format grows), or on-device inference changes where the model runs. |
Rollout and verification
- Ship the endpoint first, behind a flag, and compare its output with the direct call for a small group.
- Record the ending of every reply: done, error, stopped or interrupted. A share of interrupted replies that rises is an early warning about the network path.
- Test the endings without a provider: feed the page a scripted stream that ends each way.
- Remove the key from the bundle and revoke it, after confirming nothing else uses it.
The 2 a.m. failure
Support reports that some answers "stop in the middle of a sentence" for users behind a corporate network. The page shows them as complete (illustrative). The cause is a proxy that closes long responses early, so the byte stream ends without a done event, and the old code treated the end as success.
First three checks: (1) look for replies recorded without a terminal event; (2) reproduce with a scripted stream that ends after two pieces; (3) check whether the page marks complete on the end of the stream. Mitigation: mark such replies as interrupted and show Retry. Follow-up: add an interrupted ending to the test suite, count endings in monitoring, and send a periodic comment or ping line from the server so idle connections are less likely to be closed. The SSE standard suggests a comment line every 15 seconds or so for that reason.
Architect's notes
- Put a server between the page and the model. It is the only place that can hold a secret, enforce a limit and change the event format.
- Model the reply as a state machine, and make "complete" mean a terminal event arrived. The end of a byte stream proves nothing.
- Keep the partial text in every ending, and treat the output as untrusted input.
- Version the event format you own. The provider's format will change.
Common mistakes
- Putting a key in the bundle, or in a header the page sets.
- Treating the end of the stream as the end of the reply.
- Dropping the partial text on error, so a long reply is lost to a late failure.
- Redrawing the whole answer on every piece, or announcing every piece to a screen reader.
- Inserting model output as HTML.
- Consuming the provider's raw events in the page, which ties the page to one provider's format.
- Starting a second reply while the first is still running, so old pieces arrive in the new answer.
Key takeaways
- A model call is slow, arrives in pieces, can fail after it has started, and can be wrong. The front end design follows from those four facts.
- The browser calls your server. Your server holds the key, applies limits, logs usage and shapes the stream.
- Streaming shortens the wait for the first token, not the whole generation, and it costs partial states.
- A reply has six states; only
streamingaccepts text, and every ending keeps the text received. - An error can arrive after a 200 status as an event, and a connection can drop with no event. Only a terminal event means complete.
- Cancel with an AbortController; a Stop is an
AbortErroryou caused. - Draw once per frame, redraw only the tail, and announce only the status.
- Output is untrusted input.
Practice exercises
Exercise 1 — Starter (45 min): Draw the state machine for your own AI feature on paper. For each of the six endings, write what the screen shows, whether the partial text stays and which button appears.
Exercise 2 — Intermediate (2 hours): Write the list of events your server would send the page for a text-only reply: names, fields and the rule for each terminal event. Then list three provider changes that your list should survive unchanged.
Exercise 3 — Advanced (half day): Write a decision record for "stream or wait" for one real feature, using Figure 4. State what is checked before display, what the user does with the answer, and what you will measure after release.
Related reading
In this course:
- Server-Sent Events in Depth, the wire format that most provider streams use.
- Reconnection and Message Ordering, what to do when a stream drops and resumes.
- Real-Time Data in React State and Query Caches, putting a stream of messages into component state.
- Local vs Global State in the Front End, deciding where each piece of state lives.
- Polling, Server-Sent Events and WebSockets, choosing a transport.
Official documentation
- Claude API: Streaming messages, the event flow,
pinganderrorevents, partial JSON for tool use and error recovery. - Claude API: Handle errors, errors that arrive inside a stream and connection drops.
- OpenAI: Streaming API responses, typed events and the moderation caveat, and production best practices, keys and latency.
- MDN: Using readable streams and Using Fetch, reading a response body and aborting.
- MDN: ARIA live regions and requestAnimationFrame.