Streaming responses and cancellation
Build LLM-backed product features end to end against a deterministic local mock: form well-formed chat requests, structure prompts and validated JSON outputs, stream and retry safely, ground answers in retrieved sources, call tools inside bounded agent loops, defend against prompt injection, and evaluate quality with reproducible checks instead of one-off demos. No API keys and no network calls are used anywhere in the course.
What you will be able to do
#- Assemble streamed deltas into the complete reply and explain why chunks are fragments rather than standalone values.
- Detect and fix the overwrite bug that silently drops all but the last chunk.
- Implement early termination over a mock stream and state precisely what cancellation does and does not undo.
Overview
#Why streaming exists
A non-streaming request blocks until the whole reply is generated. For a 500-token answer that can be many seconds of nothing on screen. Streaming sends the reply as it is generated: a sequence of small pieces, usually called deltas, each carrying a fragment of text. The full reply is identical; only the delivery timing changes. The product value is time-to-first-token: the user sees progress immediately instead of a spinner.
Deltas are fragments, not messages
The classic streaming bug is treating each chunk as a complete value. A chunk is a fragment to append:
function* mockStream(chunks) {
yield* chunks;
}
function collectStream(chunks) {
let text = "";
for (const delta of mockStream(chunks)) {
text += delta;
}
return text;
}
// collectStream(["Hel", "lo wo", "rld!"]) -> "Hello world!"
The mock generator yields fixed fragments, so the assembled result is deterministic and hand-traceable. Real streams wrap the same idea in server-sent events or similar frames, with per-chunk metadata and a final signal that the stream is complete. Two things arrive at the end of a real stream, not the beginning: the finish reason and the token usage. Cost accounting and truncation checks (lessons 3 and 4) therefore belong in the stream-completion handler, not the chunk handler.
The overwrite bug
function brokenCollect(chunks) {
let text = "";
for (const delta of mockStream(chunks)) {
text = delta; // defect: assignment instead of accumulation
}
return text;
}
// brokenCollect(["Hel", "lo wo", "rld!"]) -> "rld!"
The function returns only the last fragment. It looks like a rendering glitch ("text flickers and loses the beginning") and the fix is one character. The general lesson: write a tiny deterministic test for stream assembly before wiring a real stream, because the failure mode is silent.
Cancellation: stop consuming, state what actually stops
Users navigate away and hit stop. The client-side contract is an abort signal: stop consuming, release UI state, and mark the request cancelled.
function consumeUntil(chunks, shouldStop) {
let text = "";
let cancelled = false;
for (const delta of mockStream(chunks)) {
text += delta;
if (shouldStop(text)) {
cancelled = true;
break;
}
}
return { text, cancelled };
}
// consumeUntil(["Hel", "lo wo", "rld!"], t => t.length >= 8)
// -> { text: "Hello wo", cancelled: true }
Be precise about what cancellation means. Aborting stops the client from reading and, when the provider supports it, requests upstream termination. But a request that already finished server-side cannot be un-finished: its tokens may still be generated and billed. Cancellation is a UX and cost-control mechanism, not a transaction rollback. If the side effects of a generation matter (for example, the reply triggers an email), the cancellation policy must be explicit in your design, which foreshadows the approval gates of lesson 11.
Where validation fits in a stream
You cannot validate a JSON payload you have only half of. The standard patterns:
- Buffer silently, validate on completion. Simplest and correct for machine-to-machine outputs.
- Render progressively for prose, validate on completion. Correct for chat UIs.
- Incremental parsing for special cases such as auto-completing brackets. Genuinely harder; adopt only with a reason.
Pattern 2 is the default for user-facing chat: show text as it arrives, and run structured-output validation (lesson 5) only when the stream signals completion. Attempting to validate mid-stream is a common source of false-negative errors that blame the model for a bug in your assembler.
Continue with ai-engineering-errors-retries-and-timeouts to handle the failures a stream can raise mid-flight.
Exercises
#Reference answers and expected output are authored, not executed in this browser. Nothing you type is run, and there is no Run or Pass control on this page.
Exercise 1Implement
Implement collectStream(chunks) that iterates the mockStream generator and concatenates every delta into the full text.
starter.javascriptfunction* mockStream(chunks) { yield* chunks; } function collectStream(chunks) { // Iterate mockStream(chunks) and concatenate every delta. }Reveal the reference answer
reference.javascriptfunction* mockStream(chunks) { yield* chunks; } function collectStream(chunks) { let text = ""; for (const delta of mockStream(chunks)) { text += delta; } return text; } console.log(collectStream(["Hel", "lo wo", "rld!"]));Authored expected output: Hello world!
Each yielded value is a fragment. Accumulation with += is the entire contract; the mock generator keeps the exercise deterministic and traceable.
Exercise 2Debug
brokenCollect returns only the last fragment. Identify the defect, fix it, and state the symptom a user would have seen.
starter.javascriptfunction* mockStream(chunks) { yield* chunks; } function brokenCollect(chunks) { let text = ""; for (const delta of mockStream(chunks)) { text = delta; } return text; } console.log(brokenCollect(["Hel", "lo wo", "rld!"]));Reveal the reference answer
reference.javascriptfunction* mockStream(chunks) { yield* chunks; } function fixedCollect(chunks) { let text = ""; for (const delta of mockStream(chunks)) { text += delta; } return text; } console.log(fixedCollect(["Hel", "lo wo", "rld!"]));Authored expected output: Hello world!
text = delta replaces the accumulator on every chunk, so earlier fragments are lost and the user sees flickering text that ends up truncated to the last chunk. The fix is text += delta.
Exercise 3Implement
Implement consumeUntil(chunks, shouldStop): append each delta, and after each append call shouldStop(text); when it returns true, stop iterating and return { text, cancelled: true }. If the stream completes without shouldStop firing, return { text, cancelled: false }.
starter.javascriptfunction* mockStream(chunks) { yield* chunks; } function consumeUntil(chunks, shouldStop) { // Append each delta, then call shouldStop(text). On true, stop and // return { text, cancelled: true }. On natural completion return // { text, cancelled: false }. } const result = consumeUntil(["Hel", "lo wo", "rld!"], (t) => t.length >= 8); console.log(JSON.stringify(result));Reveal the reference answer
reference.javascriptfunction* mockStream(chunks) { yield* chunks; } function consumeUntil(chunks, shouldStop) { let text = ""; let cancelled = false; for (const delta of mockStream(chunks)) { text += delta; if (shouldStop(text)) { cancelled = true; break; } } return { text, cancelled }; } const result = consumeUntil(["Hel", "lo wo", "rld!"], (t) => t.length >= 8); console.log(JSON.stringify(result));Authored expected output: {"text":"Hello wo","cancelled":true}
With chunks Hel, lo wo, rld! and shouldStop t => t.length >= 8, the accumulated text reaches length 8 after the second chunk, so the loop breaks with Hello wo and cancelled true.
Exercise 4Predict
The transcript consumer pushes every delta into an array and finally logs the array joined with | followed by the collected text. Predict both logged lines for chunks Hel, lo wo, rld!.
starter.javascriptfunction* mockStream(chunks) { yield* chunks; } const chunks = ["Hel", "lo wo", "rld!"]; const transcript = []; let text = ""; for (const delta of mockStream(chunks)) { transcript.push(delta); text += delta; } console.log(transcript.join("|")); console.log(text);Reveal the reference answer
reference.javascript// Predicted output: // // Hel|lo wo|rld! // Hello world! // // Trace: three deltas arrive in order and are pushed verbatim, so the // transcript joins as Hel|lo wo|rld!. The accumulator concatenates the // same fragments into Hello world!.Authored expected output: Hel|lo wo|rld! Hello world!
Three deltas are logged verbatim in arrival order, then the accumulator shows they concatenate into one string. This is the mental model for rendering a stream in a UI.
Exercise 5Explain
Knowledge check: what does streaming change about a model reply?
starter.text// Choose the correct option.Reveal the reference answer
reference.textOnly delivery timing. The assembled text is the same generation; streaming improves perceived latency via time-to-first-token, while finish reason and usage still arrive at completion.Authored expected output: Delivery timing only, not the final content
Treating chunks as fragments and completion as the validation point keeps streaming and correctness independent.
Common misconceptions
#- Myth: streaming changes the final text. Fact: the assembled reply is the same generation delivered earlier; only timing differs.
- Myth: aborting a request undoes generation. Fact: it stops consumption and may stop upstream generation; work already completed can still be billed and cannot be rolled back.
- Myth: usage and finish reason arrive with the first chunk. Fact: they arrive at stream completion, so accounting belongs in the completion handler.
Follow-up practice
#- ai-engineering-errors-retries-and-timeouts
Your progress
#Answers, drafts and completion marks are stored only in this browser. Nothing is sent to a server and no account is used.
Verification: authored. Answers and outputs on this page are authored reference material, not executed results.