Streaming Output
🎯 Introduction
The first three articles covered text generation and multi-turn conversations. Those calls share one limitation: the program must wait for the entire answer before receiving the result. Long answers leave the user waiting.
Chat applications typically display text as it is generated. This is streaming output. Using AIHubMix and the OpenAI SDK, you will receive text chunks in Node.js, assemble the answer, check whether generation finished, and cancel requests. For now, we cover the model API → Node.js program flow. Building an AI Service API will explain how to forward the stream to a browser through Express.
⚖️ Non-Streaming and Streaming Responses
Suppose you ask the model to introduce Vue 3. Both approaches may ultimately return the same text, but the program receives it at different times.
| Non-streaming response | Streaming response |
|---|---|
| Wait for generation to finish, then receive all the text at once | Receive chunks during generation and display them immediately |
| Suitable when only the final result matters | Suitable for chats and long-form generation where content should appear early |
For example, "Vue 3 supports the Composition API for more flexible code organization" might appear progressively as:
First display: Vue 3
Next display: Vue 3 supports the Composition API
Final display: Vue 3 supports the Composition API for more flexible code organization.
This is only an illustration of the display behavior. The SDK does not necessarily split text at these positions. A chunk may contain a few characters or a longer passage; one chunk is neither one character nor one token.
Chat Completions streaming responses usually arrive from the server over SSE (Server-Sent Events). The OpenAI SDK parses the stream into iterable objects, so you do not need to parse SSE manually here. Streaming primarily lets you see the first content sooner; it does not guarantee faster overall generation.
🛠 Receive Streaming Text with the SDK
Continue with ai-sdk-course, using Node.js 24.x and openai@7.62.0 and the AIHubMix configuration in .env. No dependency installation is needed.
Create 04.streaming.mjs in the project root:
import OpenAI from "openai";
const client = new OpenAI({
apiKey: process.env.AI_API_KEY,
baseURL: process.env.AI_BASE_URL
});
const stream = await client.chat.completions.create({
model: process.env.AI_MODEL,
messages: [
{
role: "user",
content: "Introduce the core features of Vue 3 in three sentences."
}
],
stream: true
});
let text = "";
let finishReason = null;
for await (const chunk of stream) {
const choice = chunk.choices[0];
if (!choice) continue;
const content = choice.delta?.content;
if (content) {
text += content;
process.stdout.write(content);
}
if (choice.finish_reason != null) {
finishReason = choice.finish_reason;
}
}
console.log("\nFinish reason:", finishReason ?? "not received");
console.log("Characters received:", text.length);
if (finishReason !== "stop") {
console.warn("The answer may be incomplete; check the finish reason");
}
Run this from the project root:
node --env-file=.env 04.streaming.mjs
If you need a local HTTP proxy to access AIHubMix, use the command verified in Introduction to AI SDKs and Environment Setup:
HTTPS_PROXY=http://127.0.0.1:7890 NODE_USE_ENV_PROXY=1 node --env-file=.env 04.streaming.mjs
Text will appear incrementally in the terminal instead of being printed only after the request ends. The final terminal contents might look like this illustrative output:
Vue 3's Composition API helps organize code by feature.
Its reactivity system updates the interface when data changes.
Single-file components combine templates, logic, and styles in one file.
Finish reason: stop
Characters received: 2449
The actual text, chunk count, and character count vary. The sample text above has a JavaScript string length of 2449; the code prints the length of the text actually received in your run.
What Changed in the Code?
Compared with the chat.completions.create() calls in the previous two articles, adding stream: true changes how you read the result:
- A non-streaming request returns a complete response; read its text through
response.choices[0].message.content. - A streaming request returns an asynchronously iterable stream; read newly added text through each
chunkobject'schoices[0].delta.content.
The program appends each content fragment to text while displaying it with process.stdout.write(). Unlike console.log(), this does not automatically add a newline, so the text keeps growing in place.
🧱 A Streaming Response Contains More Than Text
Stream chunks may carry role information or a finish reason as well as text. Do not assume every iteration provides delta.content.
The following is a simplified structure with other fields omitted, not a complete API response:
// A text chunk arrives
{
choices: [
{ delta: { content: "Vue 3" }, finish_reason: null }
]
}
// Another text chunk
{
choices: [
{ delta: { content: " supports the Composition API" }, finish_reason: null }
]
}
// Generation ends; there may be no text
{
choices: [
{ delta: {}, finish_reason: "stop" }
]
}
Because the final chunk may contain no text, the complete example handles delta.content and finish_reason separately.
How Do You Check Whether Generation Completed?
Text Generation and Model Parameters introduced finish_reason. A non-streaming response exposes it directly; with a stream, you must record it while iterating.
| Finish reason | Meaning | How to handle it |
|---|---|---|
stop | Normal completion | Treat the text as fully generated |
length | Output length limit reached | Text may be truncated; do not treat it as a complete answer |
content_filter | Generation restricted by content filtering | Handle it as a filtered result |
| No finish reason received | Completion cannot be confirmed | Do not infer success from the text alone |
For example, the stream might return "Vue 3's Composition API can" before the connection fails. Receiving some text does not mean generation succeeded. The SDK may throw if transmission fails. If the stream ends without a normal finish_reason, do not display "Generation complete".
This article checks only whether text generation ended normally. Your application must still verify accuracy and compliance with its requirements.
🪤 Stop an Answer During Generation
A streaming chat also needs a way for users to stop an answer that is heading in the wrong direction. In a Node.js terminal, use Ctrl + C to simulate clicking Stop.
Create 04.cancel.mjs:
import OpenAI from "openai";
const client = new OpenAI({
apiKey: process.env.AI_API_KEY,
baseURL: process.env.AI_BASE_URL
});
const controller = new AbortController();
process.once("SIGINT", () => {
controller.abort();
});
let finishReason = null;
try {
const stream = await client.chat.completions.create({
model: process.env.AI_MODEL,
messages: [
{
role: "user",
content: "Describe the history of JavaScript in detail."
}
],
stream: true
}, { signal: controller.signal });
for await (const chunk of stream) {
const choice = chunk.choices[0];
if (choice?.delta?.content) {
process.stdout.write(choice.delta.content);
}
if (choice?.finish_reason != null) {
finishReason = choice.finish_reason;
}
}
} catch (error) {
if (!controller.signal.aborted) throw error;
}
if (controller.signal.aborted) {
console.log("\nStopped by the user; the text received so far may be incomplete");
} else if (finishReason === "stop") {
console.log("\nGeneration complete");
} else {
console.log("\nGeneration did not complete normally:", finishReason ?? "no finish reason received");
}
Run:
HTTPS_PROXY=http://127.0.0.1:7890 NODE_USE_ENV_PROXY=1 node --env-file=.env 04.cancel.mjs
Press Ctrl + C while text is still being generated. AbortController sends a cancellation signal, and the SDK stops receiving data for that request. If generation has already finished, the program ends normally and the shortcut cannot demonstrate cancellation. Retry with a question requiring a longer answer.
Distinguish these three outcomes:
| Situation | Status to display |
|---|---|
stop received without cancellation | Generation complete |
| User cancels | Stopped; keep the partial text already received |
| Request error or no normal finish reason | Failed or incomplete |
Cancelling a request does not guarantee the model server stops computing at exactly the same moment. Billing and cancellation behavior depend on AIHubMix and the selected model.
❓ Knowledge Check
Q1: Does streaming require WebSocket?
No. Chat Completions can stream content over HTTP using SSE, with the SDK parsing the stream. WebSocket is another option for bidirectional communication, but is not required to display streamed model replies.
Q2: Why check finish_reason after receiving text?
The text may be only a partial result. A length finish reason or a disconnected request means nonempty text alone cannot prove normal completion.
🧪 Exercise
- Change the prompt in
04.streaming.mjsto "List five advantages of TypeScript, each on its own line". Observe how text appears incrementally and check whetherstoparrives at the end. - Press Ctrl + C while
04.cancel.mjsgenerates a long answer and observe the stopped message. Run it again without pressing the shortcut and compare the ending states.
Success criteria: Assemble text from delta.content, explain why finish_reason must be read, and distinguish normal completion, user cancellation, and unexpected interruption.
🎉 You can now receive and control streaming model replies in Node.js. Next, you will generate structured data that is easier for programs to process.
