You’ve typed a question into an AI chat window and watched the answer appear a few words at a time. A community language exchange club wants that for the practice partner on its page, where members practice Spanish between meetups. When a member orders a coffee in Spanish, the reply should start showing while the model is still generating it, so the member isn’t left waiting in silence.
Over this course, you’ll build that partner, from a terminal script to a chat panel with a Stop button. In this lesson, you’ll ask your provider for a stream and watch its pieces arrive in a loop. Start with the project the course builds on.
Set Up the Club’s Project
The text lessons build one project as you type along, with calls to your own provider that cost a fraction of a cent each. The videos show that project at work, the exercises run in your browser against a stand-in model with no key, and the final project puts the pieces together.
The course assumes you can send requests with fetch(), write async functions with await, cancel a request with an AbortSignal, and run Node.js scripts that use npm packages. If you’re coming from Python and the async part is new, then Async JavaScript for Pythonistas covers it.
You also need an API key for OpenAI or Anthropic. You don’t need to know any server code, because the course teaches the parts of the Express server framework it uses.
Get the starting project from the sample code download linked in the course’s first lesson, the Overview video. Unzip it and open a terminal in its folder. It holds:
model/, the module your code calls the model through. Itsask()sends instructions and an input to your provider and returns the reply’stext,stopReason, andusage. It also holds one file per provider, the model IDs inconfig.js, andsettings.js, which reads.env.prompts/partner.md, the partner’s instructions: reply in Spanish, stay in the café scene, and end with one tip in English about a mistake in the member’s message.data/sessions.json, practice sessions by club members, each containing a list of the messages a member sent.cost.js, withcostInCents(), which turns a call’susageinto cents at your model’s prices.public/index.htmlandserver.js, the club’s page and a small server for it, used in the course’s last part.
Install the packages, then create .env from the template, or copy in a .env you already have from earlier work with ask():
Open .env, set MODEL_PROVIDER to openai or anthropic, and paste your key into the matching key line. Set MAX_OUTPUT_TOKENS=400 and MODEL_TIMEOUT_SECONDS=30.
The first session is Amara’s. She orders a coffee and a pastry, then asks for the total:
{
"member": "Amara",
"messages": [
"Hola, quiero una café con leche y un cruasán, por favor.",
"¿Cuánto cuesta todo?"
]
}
Her first message has the kind of slip the partner’s tip is for: café is masculine, so it’s un café, not una café. That’s the message you’ll send in this lesson.
Ask for the Answer as It’s Written
A normal model call makes the member wait for the whole reply. With ask(), the provider answers only once the model has generated everything, as one JSON body. For a reply of a few paragraphs, that’s several seconds of an empty chat panel.
Both providers can send the reply while it’s being generated instead. You ask for that with one more field in the request body, stream: true. The provider then sends the status and headers right away, keeps the connection open, and writes each new piece of the reply into the body as the model generates it. This is a streamed response.
To see a streamed response firsthand, you’ll make the request yourself in a new file, model/raw-stream.js, which goes in model/ because it names a provider’s endpoint and fields. Its openStream() sends the partner’s instructions and a member’s message and returns the response with its body still unread.
This file is only a look behind the scenes. Later in the course, a streamAnswer() function in the module takes over, and no feature code sees a raw stream. That’s all you need about streamAnswer() for now.
Open the version for your provider. Both send the request you know from ask() with stream: true added, using the cheaper model config.js lists for the fast role:
OpenAI’s Responses API takes the same instructions and input as a normal call:
model/raw-stream.js
import { settings } from "./settings.js";
import { MODELS } from "./config.js";
import { httpError } from "./http-error.js";
const ENDPOINT = "https://api.openai.com/v1/responses";
export async function openStream(instructions, input) {
const response = await fetch(ENDPOINT, {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${settings.apiKey}`,
},
body: JSON.stringify({
model: MODELS.openai.fast,
instructions,
input,
max_output_tokens: settings.maxOutputTokens,
stream: true,
}),
signal: AbortSignal.timeout(settings.timeoutMs),
});
if (!response.ok) {
const body = await response.json().catch(() => null);
throw httpError(response, body);
}
return response;
}
The model field reads gpt-6.1-terra from MODELS.openai.fast. The only new line in the body is stream: true.
Anthropic’s Messages API takes the same system and messages as a normal call:
model/raw-stream.js
import { settings } from "./settings.js";
import { MODELS } from "./config.js";
import { httpError } from "./http-error.js";
const ENDPOINT = "https://api.anthropic.com/v1/messages";
export async function openStream(instructions, input) {
const response = await fetch(ENDPOINT, {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${settings.apiKey}`,
"anthropic-version": "2026-10-21",
},
body: JSON.stringify({
model: MODELS.anthropic.fast,
system: instructions,
messages: [{ role: "user", content: input }],
max_tokens: settings.maxOutputTokens,
stream: true,
}),
signal: AbortSignal.timeout(settings.timeoutMs),
});
if (!response.ok) {
const body = await response.json().catch(() => null);
throw httpError(response, body);
}
return response;
}
The model field reads claude-haiku-5-5 from MODELS.anthropic.fast. The only new line in the body is stream: true.
The end of openStream() is the same for both providers. AbortSignal.timeout() stops the request after the number of seconds set by MODEL_TIMEOUT_SECONDS, as in ask(), and with a stream it also covers reading the body, so it limits the whole answer. If the response status indicates failure, openStream() throws an error created by httpError(). For example, a wrong key triggers the same 401 error that ask() would.
Once the 200 has arrived, though, an error part way through arrives inside the stream or is thrown from the loop that reads it, not from openStream(). A later lesson handles that.
The function returns response without calling .json(). That method waits for the whole body, then parses it as one JSON document. A streamed body is a series of events, not one JSON value, so .json() would throw a SyntaxError. Reading the body piece by piece is the job of the script you write next.
If it’s unclear why openStream() can return before the reply exists, then this button opens a mentor chat with the question ready to send:
Read the Body Chunk by Chunk
To show a reply as it arrives, your code needs each piece of the body the moment it comes off the network. A plain loop can’t do that, because the pieces don’t exist yet when it starts.
You know for...of, which runs its body once for each item of an array, a string, or another iterable. Its asynchronous version is for await...of. Each pass waits for the next item to arrive, then runs the body with it, and the loop ends when the stream does.
A response’s body works with for await...of. Each item it gives you is a chunk: one piece of the body as it arrived, in raw bytes. Create watch-chunks.js in the project folder, next to server.js. It names no provider, so it’s the same for everyone. It starts by reading the partner’s instructions and Amara’s first message:
watch-chunks.js
import { readFile } from "node:fs/promises";
import { openStream } from "./model/raw-stream.js";
const prompt = await readFile("prompts/partner.md", "utf8");
const text = await readFile("data/sessions.json", "utf8");
const sessions = JSON.parse(text);
const amara = sessions.find(
(session) => session.member === "Amara"
);
const message = amara.messages[0];
The rest opens the stream and loops over its body, recording the start time so it can log how much time has elapsed:
watch-chunks.js
const start = Date.now();
const response = await openStream(prompt, message);
console.log("Headers after", Date.now() - start, "ms");
console.log(response.headers.get("content-type"));
const decoder = new TextDecoder();
let count = 0;
for await (const chunk of response.body) {
count += 1;
const label = `chunk ${count}: ${chunk.length} bytes`;
console.log(`--- ${label} at ${Date.now() - start} ms`);
console.log(decoder.decode(chunk, { stream: true }));
}
console.log(count, "chunks in", Date.now() - start, "ms");
Before the loop, the script logs how long it took for the headers to arrive and the response’s content type. Inside it, each chunk is a Uint8Array, an array of bytes. The loop logs its number, size, and arrival time, then turns the bytes into text with a TextDecoder.
The decoder’s { stream: true } option, unrelated to the request’s stream: true, tells the decoder more bytes are coming. A letter like é takes two bytes, and a chunk can end between them, so the decoder holds the first byte until the next chunk brings the second.
If the difference between for...of and for await...of still feels hazy, then the button below opens a mentor chat with this question ready to send:
Run the script with node --env-file=.env watch-chunks.js. Open the version for your provider to see one run’s output. Long lines are cut with ..., and your chunks, times, and reply will differ:
This run used gpt-6.1-terra and sent 21 chunks:
Headers after 606 ms
text/event-stream
--- chunk 1: 3270 bytes at 608 ms
event: response.created
data: {"type":"response.created","sequence_number":0,...
event: response.in_progress
data: {"type":"response.in_progress","sequence_number":1,...
--- chunk 2: 27 bytes at 2900 ms
event: response.output_item
--- chunk 3: 1360 bytes at 2900 ms
.added
data: {"type":"response.output_item.added",...
...
--- chunk 5: 26 bytes at 2901 ms
event: response.output_ite
--- chunk 6: 4098 bytes at 2901 ms
m.done
data: {"type":"response.output_item.done",...
...
event: response.output_text.delta
data: {"type":"response.output_text.delta","se
--- chunk 7: 179 bytes at 2902 ms
quence_number":6,...,"delta":"Claro",...}
...
--- chunk 18: 4098 bytes at 3591 ms
event: response.completed
data: {"type":"response.completed",...,"status":"completed",...
...
--- chunk 20: 1360 bytes at 3592 ms
...,"usage":{"input_tokens":108,...,"output_tokens":102,
"output_tokens_details":{"reasoning_tokens":58},...
...
21 chunks in 3607 ms
Chunk 1 holds two whole events, while chunks 2 and 3 cut one event’s name, response.output_item.added, in two. During the pause between chunk 1 and chunk 2, the model generates reasoning tokens before the reply’s text. The stream doesn’t carry those tokens as text you can read.
The partner’s words come in response.output_text.delta events, one small delta string each: "Claro", then ",", " un", " café", and so on. The reply took about 0.7 seconds from first word to last and ended with the tip: “Say “un café,” not “una café,” because “café” is masculine.”
The response.completed event at the end carries the status and token usage, and response.incomplete takes its place when the output limit cuts the reply off. The 102 output tokens include 58 hidden reasoning tokens, which are billed and count against MAX_OUTPUT_TOKENS too. At the fast model’s prices, this call cost about 0.06 cents. Streamed runs of Amara’s message took between 3.6 and 5.1 seconds, and one without stream: true took 4.9 seconds.
This run used claude-haiku-5-5 and sent 16 chunks:
Headers after 182 ms
text/event-stream
--- chunk 1: 858 bytes at 484 ms
event: message_start
data: {"type":"message_start","message":{"id":"msg_01...",...
event: content_block_start
data: {"type":"content_block_start","index":0,"content_block":{"type":"text",...}}
event: content_block_delta
data: {...,"delta":{"type":"text_delta","text":"¡H"}}
--- chunk 2: 119 bytes at 602 ms
event: content_block_delta
data: {...,"delta":{"type":"text_delta","text":"ola!"}}
--- chunk 3: 125 bytes at 610 ms
event: content_block_delta
data: {...,"delta":{"type":"text_delta","text":" Claro, un"}}
...
--- chunk 14: 356 bytes at 933 ms
event: content_block_delta
data: {...,"delta":{"type":"text_delta","text":" \"un café con leche,\""}}
event: content_block_delta
data: {...,"delta":{"type":"text_delta","text":" not \"una café con leche.\""}}
event: content_block_stop
data: {"type":"content_block_stop","index":0}
--- chunk 15: 650 bytes at 935 ms
event: message_delta
data: {"type":"message_delta","delta":{...,"stop_reason":"end_turn",...},
"usage":{...,"output_tokens":91,...}}
--- chunk 16: 51 bytes at 936 ms
event: message_stop
data: {"type":"message_stop"}
16 chunks in 937 ms
The stream opens with message_start and a content_block_start for the text. The partner’s words come in content_block_delta events whose delta is a text_delta: "¡H", then "ola!", and so on, ending with the tip: ““café” is masculine, so it should be “un café con leche,” not “una café con leche.”” After content_block_stop, the message_delta event carries the stop reason and token usage, and message_stop ends the stream.
Chunk 1 holds three whole events, and chunk 14 holds three more. Chunk boundaries and arrival times vary from run to run, and a chunk can also end in the middle of an event. Streamed runs of Amara’s message took between 0.9 and 1.1 seconds, and runs without stream: true took 0.9 to 1.0 seconds.
The output_tokens value in message_delta determines your output charge and counts against MAX_OUTPUT_TOKENS. At the fast model’s prices, this call cost about 0.006 cents.
The headers arrived in under a second, long before the reply. Their content type, text/event-stream, indicates that the body contains server-sent events: plain text made of events, with a blank line after each one. In both providers’ streams, each event is an event: line naming it and a data: line holding JSON.
The chunks came in after that, each pass of the loop waiting for its chunk. Watch out, though, because a chunk isn’t one event. It can hold several events or only part of one, as your provider’s run shows.
Streaming only shortens the wait for the first words. It doesn’t change how fast the model generates or what each token costs. Total times vary so much from run to run that a streamed reply can even finish later, as your provider’s timings show.
On a short reply like Amara’s, the gain is small. On a reply of several paragraphs, the member reads from the first sentence instead of staring at an empty panel.
Check Your Understanding
These questions use this lesson’s model/raw-stream.js and watch-chunks.js. Work through them before you open the answers:
- What two changes turn a normal model call into one that reads the reply as it’s written?
- A teammate deletes
stream: truefrom the request body and runswatch-chunks.jsagain. What changes in the output? - In your provider’s stream, which event tells you why the reply stopped and how many tokens it used, and where in the stream does it come?
- Does a streamed reply cost less or finish sooner than the same reply without streaming?
- The request body adds
stream: true, and the code readsresponse.bodywithfor await...ofinstead of calling.json(). - The content type becomes
application/json, and nothing arrives, not even the headers, until the model has generated the whole reply. The body is then one JSON document, which the loop may still receive in one chunk or several. - A closing event near the end of the stream, after the text, carries the reason the reply stopped and the token usage. Its name depends on your provider, as your provider’s sample output shows.
- Neither. Streaming changes neither how fast the model generates nor what each token costs, and total times vary from run to run either way. It only lets the first words reach the member sooner.
Your script now logs the raw stream, and you’ve seen that its chunks don’t follow event boundaries. In the next lesson, Split the Stream Into Events, you’ll gather those chunks into whole events and print only the partner’s words as they arrive.