Add streamAnswer() to the Model Module

Your print-events.js script prints the partner’s reply as it’s written. The provider’s request and event names already live in model/raw-stream.js, but the script still buffers the body, splits it into events, and sorts the text from the closing event itself. Every other feature, the club’s page included, would have to copy that loop.

In this lesson, you’ll move that work behind the model/ module’s interface as a new function, streamAnswer(). Your scripts will loop over the reply’s text with for await and read the usage and stop reason once the loop ends, without knowing which provider answered. First, you need a way for a function to hand out values one at a time.

Hand Out the Reply One Piece at a Time

A function that returns the reply has to wait for all of it, which is the wait streaming avoids. streamAnswer() needs to give its caller each piece as soon as it has one, then carry on. JavaScript’s tool for this is an async generator function, written async function*, with an asterisk.

Inside it, the keyword yield hands one value to whoever is reading, and the function pauses there. Save this toy version of a reply as try-generator.js:

Language: JavaScript Filename: try-generator.js
async function* replyPieces() {
  console.log("generator: starts");
  yield "¡Claro!";
  console.log("generator: resumes");
  yield " Un café.";
  console.log("generator: finishes");
}

const pieces = replyPieces();
console.log("called replyPieces()");
for await (const piece of pieces) {
  console.log("loop got:", piece);
}
console.log("loop ended");

Before you run it with node try-generator.js, predict the order of the seven lines it prints. In particular, which comes first: called replyPieces() or generator: starts?

Language: Program Output
called replyPieces()
generator: starts
loop got: ¡Claro!
generator: resumes
loop got:  Un café.
generator: finishes
loop ended

Calling replyPieces() doesn’t run its body. It returns a generator, an object that runs the body only when a reader asks for a value. The for await loop asks, so the body runs up to the first yield and hands over "¡Claro!". The loop runs its body, then asks again, and the generator resumes after the yield. When the function’s body ends, so does the loop.

The two sides take turns. While the loop body works on one piece, the generator waits at its yield, so it never runs ahead of its reader. In model/, the module will read more of the stream only when the feature is ready for more text.

That pause is only on your side, though. The provider keeps generating the reply and billing for it while the unread pieces queue up in the connection. Only stopping the request stops the generation, which the club’s Stop button will do later.

That’s all you need about generators for now. You’ll type two more in this lesson, both following this pattern. For the full picture, JavaScript Iterators and Generators for Pythonistas covers generators in depth.

If the turn-taking between the loop and the generator still feels hazy, then this button opens a mentor chat with the question ready to send:

Turn Each Provider’s Events Into Items

The event reading in print-events.js belongs in model/, because the events differ by provider. Each provider file gets a generator, stream(), that opens the streamed request and yields the shapes readEvent() returned in the last lesson: { text } for each piece of the reply, then a last { stopReason, usage }.

So far, your scripts only called ask(). Now you’ll edit the files behind it, so here’s a short tour of the parts this lesson uses. In model/index.js:

  • ADAPTERS maps each MODEL_PROVIDER value to its provider file, and MODELS, from config.js, holds each role’s model ID.
  • ask() checks both, passes the request to sendWithRetries(), and sets cutOff when the stop reason equals the provider file’s CUT_OFF.
  • sendWithRetries() calls the provider’s send() up to MAX_ATTEMPTS times, giving each attempt settings.timeoutMs. It retries only errors marked retryable, after retryAfter seconds or a doubling delay, and gives up when the wait would pass MAX_WAIT_SECONDS. Its helper wait() does the waiting.

Each provider file, model/openai.js or model/anthropic.js, has these parts:

  • send() posts one request to the provider’s ENDPOINT and returns the reply in the module’s shape.
  • CUT_OFF is the provider’s stop reason for a reply that hit the output limit, and ROLE_SETTINGS holds each role’s extra request fields.
  • httpError(), from model/http-error.js, builds the error send() throws for a failed response, with status, retryable, and retryAfter. Billing failures, such as the error codes in OpenAI’s BILLING_CODES, are never retryable.

You’ll reuse these pieces rather than rewrite them.

The parseEvent() function from print-events.js only knows the server-sent events format, which both providers share. Copy it into a file of its own, model/parse-event.js, with export in front:

Language: JavaScript Filename: model/parse-event.js
export 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 new stream() sends the same request as send(), with stream: true added, then runs the buffer loop from print-events.js. Open your provider’s version and add it to your file. Then add the other version to the other file too, so both providers keep the same functions:

In model/openai.js, add import { parseEvent } from "./parse-event.js"; below the other imports. Then add stream() at the end of the file. Its first half sends the same request as send(). It reads signal from the request up front and adds stream: true to the body:

Language: JavaScript Filename: model/openai.js
export async function* stream(request) {
  const {
    model, instructions, input, maxOutputTokens, roleSettings,
    signal,
  } = request;
  const response = await fetch(ENDPOINT, {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
      Authorization: `Bearer ${settings.apiKey}`,
    },
    body: JSON.stringify({
      model,
      instructions,
      input,
      max_output_tokens: maxOutputTokens,
      ...roleSettings,
      stream: true,
    }),
    signal,
  });
  if (!response.ok) {
    const body = await response.json().catch(() => null);
    const billing = BILLING_CODES.includes(body?.error?.code);
    throw httpError(response, body, billing);
  }

The second half is the buffer loop from print-events.js. Where that script called handleEvent(), stream() yields each item:

Language: JavaScript Filename: model/openai.js
  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) {
      const { name, data } = parseEvent(block);
      const item = readEvent(name, data);
      if (item !== null) yield item;
    }
  }
}

Below stream(), add OpenAI’s readEvent() and readEnd() from the last lesson, without the export. Two new cases, error and response.failed, throw when OpenAI reports that generation failed partway, instead of ignoring them:

Language: JavaScript Filename: model/openai.js
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);
    case "error":
      throw new Error(`Stream error: ${data.message}`);
    case "response.failed":
      throw new Error(
        `Stream failed: ${data.response.error.message}`
      );
    default:
      return null;
  }
}

function readEnd(response) {
  return {
    stopReason:
      response.incomplete_details?.reason ?? response.status,
    usage: {
      inputTokens: response.usage.input_tokens,
      outputTokens: response.usage.output_tokens,
    },
  };
}

In model/anthropic.js, add import { parseEvent } from "./parse-event.js"; below the other imports. Then add stream() at the end of the file. Its first half sends the same request as send(). It reads signal from the request up front and adds stream: true to the body:

Language: JavaScript Filename: model/anthropic.js
export async function* stream(request) {
  const {
    model, instructions, input, maxOutputTokens, roleSettings,
    signal,
  } = request;
  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,
      system: instructions,
      messages: [{ role: "user", content: input }],
      max_tokens: maxOutputTokens,
      ...roleSettings,
      stream: true,
    }),
    signal,
  });
  if (!response.ok) {
    const body = await response.json().catch(() => null);
    const code = body?.error?.details?.error_code;
    const billing = code === "enforced_spend_limit_reached";
    throw httpError(response, body, billing);
  }

The second half is the buffer loop from print-events.js, with one addition. The input token count from message_start now goes into inputTokens, a variable inside stream():

Language: JavaScript Filename: model/anthropic.js
  const decoder = new TextDecoder();
  let buffer = "";
  let inputTokens = 0;
  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) {
      const { name, data } = parseEvent(block);
      if (name === "message_start") {
        inputTokens = data.message.usage.input_tokens;
      }
      const item = readEvent(name, data, inputTokens);
      if (item !== null) yield item;
    }
  }
}

In the last lesson, inputTokens was one variable for the whole file. Now each call to stream() gets its own, so two replies streaming at once can’t overwrite each other’s count.

readEvent() receives the count as its third parameter. Add it below stream(). It’s Anthropic’s readEvent() from the last lesson without the export, the module-level let inputTokens = 0; line, and the message_start case. Its new error case throws when Anthropic reports that generation failed partway, instead of ignoring it:

Language: JavaScript Filename: model/anthropic.js
function readEvent(name, data, inputTokens) {
  switch (name) {
    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,
        },
      };
    case "error":
      throw new Error(`Stream error: ${data.error.message}`);
    default:
      return null;
  }
}

Whichever provider you use, stream() yields the same item shapes, one each time a loop asks. If the response isn’t ok, it throws the same error as send(), with status, retryable, and retryAfter, so the module can retry both alike. A failure event from the provider throws a plain error, which is never retried, even when it arrives before any text. The next lesson looks at what such a failure leaves the member with.

Give Features streamAnswer()

Features shouldn’t choose a provider or see its items. They need the reply’s text, piece by piece, and after the loop, the usage, stopReason, and cutOff that ask() also returns. But a for await loop hands its body only the values a generator yields, and yielding the usage would mix it into the text.

So streamAnswer() returns an object. The loop reads the text from it, and the object fills in the other three as properties when the provider’s last item arrives.

streamAnswer() needs the same adapter and model ID as ask(), so first move those lookups into a helper in model/index.js, above ask():

Language: JavaScript Filename: model/index.js
function pickModel(role) {
  const { provider } = settings;
  if (!Object.hasOwn(ADAPTERS, provider)) {
    throw new Error(
      `model/ has no file for MODEL_PROVIDER "${provider}"`
    );
  }
  const adapter = ADAPTERS[provider];
  const models = MODELS[provider];
  const model = Object.hasOwn(models, role)
    ? models[role]
    : undefined;
  if (typeof model !== "string") {
    throw new Error(
      `model/config.js has no "${role}" model`
    );
  }
  return { adapter, model };
}

In ask(), replace the lines from const { provider, maxOutputTokens } = settings; to the end of the model ID check with these two:

Language: JavaScript Filename: model/index.js
  const { maxOutputTokens } = settings;
  const { adapter, model } = pickModel(role);

At the top of the file, add import { setTimeout as sleep } from "node:timers/promises";. Then add streamAnswer() at the end of the file. It takes the same arguments as ask(), plus a signal, and builds the same request:

Language: JavaScript Filename: model/index.js
export function streamAnswer({
  instructions,
  input,
  role = "capable",
  signal,
}) {
  const { adapter, model } = pickModel(role);
  const request = {
    model,
    instructions,
    input,
    maxOutputTokens: settings.maxOutputTokens,
    roleSettings: adapter.ROLE_SETTINGS[role],
  };

The rest of the function builds the object and returns it, in four steps. The object starts with the three properties a feature reads after its loop, set to null, null, and false until the reply ends, followed by the method that hands out the text:

Language: JavaScript Filename: model/index.js
  const answer = {
    usage: null,
    stopReason: null,
    cutOff: false,
    async *[Symbol.asyncIterator]() {
      for (let attempt = 1; attempt <= MAX_ATTEMPTS; attempt += 1) {

The method is the second of those two generators. A for await loop looks for a method stored under the key Symbol.asyncIterator and calls it to get its values, so writing async *[Symbol.asyncIterator]() makes the object something a feature can loop over. Its outer for loop runs once per attempt, as with the retries in ask().

Each attempt starts with its own signal. AbortSignal.timeout() gives the attempt a time limit, and AbortSignal.any() combines it with the caller’s signal into one signal that aborts when either does:

Language: JavaScript Filename: model/index.js
        const timeout = AbortSignal.timeout(settings.timeoutMs);
        const both = signal
          ? AbortSignal.any([signal, timeout])
          : timeout;
        let started = false;

With a stream, that timeout covers the whole reply, words included, so it must be long enough for the longest reply your output limit allows. A limit on the wait for the first words is the usual refinement, but 30 seconds is plenty for 400 tokens.

Next, the method loops over the provider’s stream() and sorts its items:

Language: JavaScript Filename: model/index.js
        try {
          const items = adapter.stream({ ...request, signal: both });
          for await (const item of items) {
            if (item.text === undefined) {
              answer.usage = item.usage;
              answer.stopReason = item.stopReason;
              answer.cutOff = item.stopReason === adapter.CUT_OFF;
            } else {
              started = true;
              yield item.text;
            }
          }
          break;

Follow one reply through it. The provider’s stream() yields { text: "¡Claro!" }, and this method yields only the string "¡Claro!", so the feature’s loop gets one pass with that string.

When the provider’s last item, { stopReason, usage }, arrives, the method sets the three properties instead, with cutOff worked out as in ask(), and yields nothing, so the feature’s loop gets no extra pass. The break ends the attempts once the stream finishes.

The last step repeats the retry logic that ask() uses in sendWithRetries(). The method makes up to MAX_ATTEMPTS attempts, retries only errors marked retryable, and waits retryAfter seconds or a doubling delay between them:

Language: JavaScript Filename: model/index.js
        } catch (error) {
          both.throwIfAborted();
          const last = attempt === MAX_ATTEMPTS;
          if (started || error.retryable !== true || last) {
            throw error;
          }
          const seconds = error.retryAfter ?? 2 ** (attempt - 1);
          if (seconds > MAX_WAIT_SECONDS) throw error;
          console.warn(
            `  Attempt ${attempt}: ${error.status}, waiting ${seconds} s`
          );
          await sleep(seconds * 1000, undefined, { signal });
        }
      }
    },
  };
  return answer;
}

If the caller stopped the request or the attempt timed out, both.throwIfAborted() throws that reason at once instead of retrying. Between attempts, sleep(), Node’s promise-based setTimeout(), replaces wait(). If timers in Node are new to you, then Timers and Files covers them. It takes the caller’s signal, so a stop during the wait ends it at once. No script passes a signal yet, but the club’s Stop button will, with no change to model/.

The new rule is that a retryable error is retried only before the first piece of text. Once started is true, the member has already seen words, and a second attempt would generate a different reply after them. So an error partway through is thrown to the feature instead.

If you’re unsure why a failure after the first words can’t be retried like the others, then this button opens a mentor chat with the question ready to send:

Now the partner script can be short. Create partner.js next to print-events.js. It loads Amara’s first message as before and loops over streamAnswer():

Language: JavaScript Filename: partner.js
import { readFile } from "node:fs/promises";
import { streamAnswer } from "./model/index.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 answer = streamAnswer({
  instructions: prompt,
  input: amara.messages[0],
  role: "fast",
});
let reply = "";
for await (const piece of answer) {
  reply += piece;
  process.stdout.write(piece);
}
console.log("\n\nStop reason:", answer.stopReason);
console.log("Cut off:", answer.cutOff);
console.log("Usage:", answer.usage);
console.log("Saved reply:", reply.length, "characters");

The script names no provider, no event, and no field from a provider’s stream. Run it with node --env-file=.env partner.js, and the reply grows a few words at a time, as before. Open the version for your provider to see one run. 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, ahora mismo.

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

Stop reason: completed
Cut off: false
Usage: { inputTokens: 108, outputTokens: 32 }
Saved reply: 89 characters

At $1 per million input tokens and $5 per million output tokens, this run cost about 0.03 cents. The hidden reasoning in the output tokens varies from run to run, and so does the cost. With a limit of 30 tokens, one run printed no reply text because reasoning used them all. It then printed Stop reason: max_output_tokens and Cut off: true.

This run used claude-haiku-5-5:

Language: Program Output
¡Hola! Muy bien, un café con leche y un cruasán. ¿Lo quiere
caliente o con hielo, y desea algo más para beber? Enseguida
le traigo su pedido.

Tip: "una café" should be "un café" because café is
masculine in Spanish, so it takes the article "un."

Stop reason: end_turn
Cut off: false
Usage: { inputTokens: 151, outputTokens: 104 }
Saved reply: 246 characters

At $0.10 per million input tokens and $0.50 per million output tokens, this run cost about 0.007 cents. With a limit of 30 tokens, one run stopped at ¡Hola! Claro, un café con leche y un cruasán. ¿Lo qui, then printed Stop reason: max_tokens and Cut off: true.

The script prints the properties after the loop, because the closing event arrives after the text. Try a cutoff yourself: set MAX_OUTPUT_TOKENS=30 in .env, run partner.js again, and watch Cut off: turn true. Set the limit back to 400 when you’re done.

Check Your Understanding

These questions use try-generator.js, partner.js, and the new streamAnswer(). Work through them before you open the answers:

  1. A teammate adds console.log(answer.usage) inside the for await loop in partner.js. What does it print on each pass, and why?
  2. In try-generator.js, the loop body takes a full second with each piece. When does generator: resumes print?
  3. Your provider answers the first attempt with a 503 before any text. A later call fails with an error after the first few words. What does streamAnswer() do in each case?
  4. Two members’ replies stream at the same time from the same model/ module. Why can’t one reply’s usage end up on the other’s answer?
  1. It prints null on every pass. The usage arrives in the provider’s last item, after all the text, so answer.usage is set only after the loop’s last pass. Read it once the loop has ended.
  2. It prints a second after loop got: ¡Claro!, once the loop body finishes and the loop asks for the next value. The generator waits at its yield until then, so it never runs ahead of the reader.
  3. The 503 is retryable and arrives before started is true, so streamAnswer() waits for the delay in Retry-After, or one second if it’s absent, and tries again. The member sees only the second attempt’s reply. The error after the first words is thrown to the feature’s loop, because the member has already seen part of a reply.
  4. Each call to streamAnswer() creates its own answer object, and each call to stream() has its own local variables. Nothing about a reply is stored at the top of a file, where another call could overwrite it.

Your partner script now gets the reply’s text entirely from streamAnswer(), whichever provider answers. A failure partway through throws from inside the loop, and a stream that ends without its closing event leaves stopReason at null. In the next lesson, Handle a Stream That Breaks Midway, you’ll learn what the member sees when a stream fails and how your code can tell.

Become a Member to join the conversation.