Split the Stream Into Events

Your watch-chunks.js script showed the raw stream as it came off the network: event lines, JSON, and chunks that cut an event in two. A member practicing with the partner needs none of that on screen. They need the partner’s Spanish, word by word, the moment each piece arrives.

In this lesson, you’ll turn the raw body into whole events, pick the partner’s words out of them, and print the reply as the model generates it. You’ll also read the reply’s stop reason and final token usage, which arrive at the end. First, fix the problem the last run showed you: one event arrives in two pieces.

Hold the Unfinished Event in a Buffer

Your code can read an event only once all of it has arrived, and the network doesn’t wait for event boundaries. In the server-sent events format, a blank line ends each event, so splitting the text on "\n\n" looks like the way to cut it into events.

That isn’t enough on its own. This toy stream has two short events, delivered in two chunks that break the second event’s name. Save it as try-buffer.js and run it with node try-buffer.js:

Language: JavaScript Filename: try-buffer.js
const chunks = [
  'event: delta\ndata: {"text":"Claro"}\n\nevent: del',
  'ta\ndata: {"text":", un café"}\n\n',
];
for (const chunk of chunks) {
  console.log(chunk.split("\n\n"));
}

Splitting each chunk on its own gives a piece containing event: del and another starting ta:

Language: Program Output
[ 'event: delta\ndata: {"text":"Claro"}', 'event: del' ]
[ 'ta\ndata: {"text":", un café"}', '' ]

Neither piece is an event, and a real chunk can also end in the middle of a data: line, where JSON.parse() would throw.

The fix is a buffer: a string that collects the decoded text and holds on to any unfinished event until the rest of it arrives. Replace the whole of try-buffer.js with this version, which keeps the same chunks and adds a buffer:

Language: JavaScript Filename: try-buffer.js
const chunks = [
  'event: delta\ndata: {"text":"Claro"}\n\nevent: del',
  'ta\ndata: {"text":", un café"}\n\n',
];
let buffer = "";
for (const chunk of chunks) {
  buffer += chunk;
  const blocks = buffer.split("\n\n");
  buffer = blocks.pop();
  console.log("Whole:", blocks);
  console.log("Kept:", JSON.stringify(buffer));
}

The loop adds each chunk to the end of buffer and then splits the text. Run the script again, and each event comes out whole:

Language: Program Output
Whole: [ 'event: delta\ndata: {"text":"Claro"}' ]
Kept: "event: del"
Whole: [ 'event: delta\ndata: {"text":", un café"}' ]
Kept: ""

The key line is buffer = blocks.pop(). The last piece of a split is the text after the final blank line, or all the text if none has arrived. That’s either the start of an event that isn’t finished, like event: del, or an empty string when the chunk ended exactly on a blank line. Either way, it goes back into the buffer, and every piece before it is a whole event.

A real stream gets cut the same way. The widget below runs the same loop on four events from one recorded run of Amara’s message, with long data: lines shortened to ... as in the last lesson. Pick your provider, then drag the two sliders to change where chunk 1 and chunk 2 end, and watch the output change:

Interactive diagram — enable JavaScript to view.

Each character in the output keeps the color of the chunk it arrived in, and Node.js prints each long event as two quoted lines joined with +. With the starting cuts, chunk 1 ends inside the first event’s name, so Kept: holds that piece.

Chunk 2 finishes the first event and ends inside the second event’s data: line. Chunk 3 finishes the second event and carries two whole events of its own, so its Whole: lists three.

Wherever you put the cuts, the same four events come out in the same order. Which of them carry the partner’s words depends on your provider. Picking those out is the next step.

If the .pop() step still feels slippery, then this button opens a mentor chat with the question ready to send:

Read Each Event’s Name and Data

A whole event is still text. Your code needs the event’s name to identify its kind, and its data as an object. Each event your provider sends is an event: line and a data: line holding JSON, so a short function can pull them apart:

Language: JavaScript
function parseEvent(block) {
  let name = "";
  let data = "";
  for (const line of block.split("\n")) {
    if (line.startsWith(":")) continue;
    if (line.startsWith("event: ")) name = line.slice(7);
    if (line.startsWith("data: ")) data = line.slice(6);
  }
  if (data === "") return { name: "", data: null };
  return { name, data: JSON.parse(data) };
}

The .slice() calls drop the event: and data: labels, seven and six characters long.

The format allows comment lines, which start with a colon, and providers send them to keep a connection open, sometimes as a block of their own, like : keep-alive. That’s why parseEvent() skips lines starting with : and returns an empty name and null data for a block with no data: line. readEvent(), below, ignores that block like any other event it doesn’t need.

The server-sent events format allows more, such as several data: lines in one event or lines that end in \r\n. Both providers send one data: line with a space after the colon and end their lines with \n, so this short version and the split on "\n\n" are enough here.

The events that matter and the location of their text differ by provider. That’s provider code, so it goes in model/raw-stream.js, next to openStream(). Add a readEvent() function that takes an event’s name and data and returns one of three things: { text } for a piece of the reply, { stopReason, usage } for the closing event, or null for every other event. Open the version for your provider:

The partner’s words come in response.output_text.delta events, and the closing event is response.completed, or response.incomplete when the output limit cuts the reply off:

Language: JavaScript Filename: model/raw-stream.js
export function readEvent(name, data) {
  switch (name) {
    case "response.output_text.delta":
      return { text: data.delta };
    case "response.completed":
    case "response.incomplete":
      return readEnd(data.response);
    default:
      return null;
  }
}

Both closing events carry the whole response object, with the same fields ask() reads. A helper below readEvent() turns it into the module’s usual shape:

Language: JavaScript Filename: model/raw-stream.js
function readEnd(response) {
  return {
    stopReason:
      response.incomplete_details?.reason ?? response.status,
    usage: {
      inputTokens: response.usage.input_tokens,
      outputTokens: response.usage.output_tokens,
    },
  };
}

readEvent() returns null for every other event, from response.created to response.output_item.done. It also returns null for error and response.failed, the events OpenAI sends when generation fails partway. For now, this version ignores failure events.

The input token count comes first, in message_start. The partner’s words come in content_block_delta events whose delta is a text_delta, and the stop reason and output token count come in message_delta:

Language: JavaScript Filename: model/raw-stream.js
let inputTokens = 0;

export function readEvent(name, data) {
  switch (name) {
    case "message_start":
      inputTokens = data.message.usage.input_tokens;
      return null;
    case "content_block_delta":
      if (data.delta.type !== "text_delta") return null;
      return { text: data.delta.text };
    case "message_delta":
      return {
        stopReason: data.delta.stop_reason,
        usage: {
          inputTokens,
          outputTokens: data.usage.output_tokens,
        },
      };
    default:
      return null;
  }
}

The inputTokens variable outside readEvent() keeps the count from message_start until message_delta needs it. One variable for the whole module works here because the script reads one stream. In the next lesson, streamAnswer() keeps the count inside each call, so two streams at once can’t overwrite each other’s.

The check on data.delta.type skips any delta that isn’t text. readEvent() returns null for every other event, from content_block_start to message_stop. It also returns null for error, the event Anthropic sends when generation fails partway, such as an overloaded_error. For now, this version ignores failure events.

Whichever provider you use, the switch compares the event’s name with each case and returns as soon as one matches. The stopReason and usage it returns have the same shape as the ones ask() returns, so code outside model/ never needs to know the provider’s field names. If switch is new to you, then the course Decisions in JavaScript covers it.

With whole events and a way to read them, you can show the member the reply while it’s being generated. Create print-events.js next to watch-chunks.js. It names no provider, and it starts with the same lines that load the partner’s instructions and Amara’s first message:

Language: JavaScript Filename: print-events.js
import { readFile } from "node:fs/promises";
import {
  openStream,
  readEvent,
} 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];

Below those lines, add parseEvent() from the previous section, an answer string, and a handleEvent() function that decides what to do with each whole event:

Language: JavaScript Filename: print-events.js
let answer = "";

function handleEvent(block) {
  const { name, data } = parseEvent(block);
  const result = readEvent(name, data);
  if (result === null) return;
  if (result.text !== undefined) {
    answer += result.text;
    process.stdout.write(result.text);
  } else {
    console.log("\n\nStop reason:", result.stopReason);
    console.log("Usage:", result.usage);
  }
}

Each piece of text does two jobs. It goes to process.stdout.write(), which prints a string without adding a linebreak, so the member sees the pieces join up on screen. It’s also added to answer, because printed text is gone as far as your code is concerned. Only answer holds the whole reply as a value, ready to save or send on. handleEvent() prints the stop reason and usage below the reply when it receives the closing event.

The last part opens the stream and runs the buffer loop from try-buffer.js, with the real body and the decoder from watch-chunks.js:

Language: JavaScript Filename: print-events.js
const response = await openStream(prompt, message);
const decoder = new TextDecoder();
let buffer = "";
for await (const chunk of response.body) {
  buffer += decoder.decode(chunk, { stream: true });
  const blocks = buffer.split("\n\n");
  buffer = blocks.pop();
  for (const block of blocks) {
    handleEvent(block);
  }
}
console.log("Saved reply:", answer.length, "characters");

The last line uses answer once the loop has ended, without printing the reply a second time. Run it with node --env-file=.env print-events.js, and watch the reply grow in your terminal a few words at a time. Open the version for your provider to see where one run ended up. Your wording will differ, and long lines are wrapped for display:

This run used gpt-6.1-terra:

Language: Program Output
¡Claro! Un café con leche y un cruasán, enseguida.

Tip: Say “un café,” not “una café,” because “café” is
masculine.

Stop reason: completed
Usage: { inputTokens: 108, outputTokens: 99 }
Saved reply: 116 characters

The stop reason completed comes from the response’s status, and the 99 output tokens include the hidden reasoning tokens from the last lesson. At $1 per million input tokens and $5 per million output tokens, this run cost about 0.06 cents.

To see the other stop reason, set MAX_OUTPUT_TOKENS=30 in .env and run the script again. In two runs, the model used all 30 tokens for reasoning before producing any text, so nothing printed above the stop reason. The response.incomplete event supplied max_output_tokens. Set the limit back to 400 when you’re done.

This run used claude-haiku-5-5:

Language: Program Output
¡Hola! Claro, un café con leche y un cruasán. ¿Lo quiere
tomar aquí o para llevar? ¿Algo más para beber?

Tip: "un café" is masculine, so it should be "un café con
leche" (not "una"). Everything else was perfect!

Stop reason: end_turn
Usage: { inputTokens: 151, outputTokens: 96 }
Saved reply: 212 characters

The stop reason end_turn means the model finished its reply. At $0.10 per million input tokens and $0.50 per million output tokens, this run cost about 0.006 cents.

To see another stop reason, set MAX_OUTPUT_TOKENS=30 in .env and run the script again. In one run, the reply stopped mid-sentence at ¡Claro que sí! Un café con leche y un cruasán, enseguida. ¿, and the stop reason read max_tokens. Set the limit back to 400 when you’re done.

The stop reason and usage print after the reply because they arrive last. The provider can’t know the reply’s final output token count, or why it ended, until the model has stopped generating. So a streamed reply shows its first words early, but code that logs its full cost, like the cents above, has to wait for the closing event.

When a stream finishes normally, the loop ends with an empty buffer because the last event ends with a blank line like every other one. If the body breaks off partway, this script silently drops the unfinished event left in the buffer, and it never checks that a closing event arrived. The script also drops any error event the provider sends partway through. A later lesson handles a stream that fails.

To explore what your script does in that case now, this button opens a mentor chat with the question ready to send:

Check Your Understanding

These questions use try-buffer.js, print-events.js, and your provider’s readEvent(). Work through them before you open the answers:

  1. A chunk ends in the middle of an event’s data: line. What happens to that partial line in print-events.js, and when is it used?
  2. A teammate moves buffer = blocks.pop() so that it runs after the inner for loop instead of before it. What goes wrong?
  3. Why does readEvent() live in model/raw-stream.js while the buffer loop lives in print-events.js?
  4. Your script must log the reply’s output token count before it shows anything to the member. What does that cost the member when the reply is streamed?
  5. The club wants to save each reply to the member’s practice session. Which value in print-events.js do you save, and at what point is it complete?
  1. Splitting the buffer puts the partial line in the last piece, and buffer = blocks.pop() keeps it in the buffer. The loop appends the next chunk, then splits off and handles the whole event once a blank line arrives.
  2. The last piece is still in blocks when the inner loop runs, so handleEvent() also receives the unfinished event. When the chunk ended inside that event’s data: line, JSON.parse() throws a SyntaxError.
  3. The buffer loop only knows the server-sent events format, which both providers share. The event names and the fields that hold the text are different for each provider, so that code stays in model/ with the rest of the provider code.
  4. The final output token count arrives in the closing event, after all the text, because the provider can count it only once the model has stopped generating. The script would have to hold the whole reply until then, so the member waits as long as they would without streaming and misses out on seeing the first words early.
  5. Save answer, because the text printed on screen can’t be read back by your code. But the loop ending doesn’t make it complete. It’s complete only once the closing event arrives with your provider’s stop reason for a finished reply—the one your first run printed. This script doesn’t check that, so answer is incomplete if the body breaks off, an error event is dropped, or the reply hits the output limit. A later lesson handles a stream that fails.

Your script now prints the partner’s reply as it’s written, plus the stop reason and usage, but it still handles raw events itself, and so would every feature that copied it. In the next lesson, Add streamAnswer() to the Model Module, you’ll move this work into the module so features get the reply’s text and nothing else.

Become a Member to join the conversation.