Handling Streaming Responses
When you set stream=True in your API request, the server sends back data in chunks as it becomes available. This is incredibly useful for applications like chatbots, where you want to display the response to the user word-by-word.
This guide provides more robust examples for handling streamed responses.
Python
When you iterate over the stream, you collect delta chunks. You should check if the content of the delta is available before appending it.
import os
from openai import OpenAI
client = OpenAI(
base_url="https://api.inceptron.io/v1",
api_key=os.environ["INCEPTRON_API_KEY"],
)
stream = client.chat.completions.create(
model="zai-org/GLM-5.3",
messages=[
{
"role": "user",
"content": "Write a short story about a robot who discovers music."
}
],
stream=True,
stream_options={"include_usage": True},
)
full_response = ""
usage = None
for chunk in stream:
if chunk.usage is not None:
usage = chunk.usage
if not chunk.choices:
continue
content = chunk.choices[0].delta.content
if content:
full_response += content
print(content, end="", flush=True)
print("\n--- Full Response ---")
print(full_response)
print("Token usage:", usage)JavaScript (Node.js)
Using an for await...of loop is the modern way to handle async iterators in JavaScript.
import { OpenAI } from "openai";
const client = new OpenAI({
baseURL: "https://api.inceptron.io/v1",
apiKey: process.env.INCEPTRON_API_KEY,
});
async function main() {
const stream = await client.chat.completions.create({
model: "zai-org/GLM-5.3",
messages: [
{
role: "user",
content: "Write a short story about a robot who discovers music.",
},
],
stream: true,
stream_options: { include_usage: true },
});
let fullResponse = "";
let usage = null;
for await (const chunk of stream) {
if (chunk.usage != null) {
usage = chunk.usage;
}
const content = chunk.choices[0]?.delta?.content || "";
fullResponse += content;
process.stdout.write(content);
}
process.stdout.write('\n--- Full Response ---\n');
process.stdout.write(fullResponse);
process.stdout.write('\n');
console.log("Token usage:", usage);
}
main();With include_usage: true, ordinary chunks have usage: null. One final chunk before [DONE] contains usage totals for the entire request and an empty choices array. Save this usage object once. A cancelled or interrupted stream may end before it arrives.
Completion usage includes reasoning and tool-call tokens as well as visible text. A short answer from a reasoning model can therefore have a much larger completion count than the text displayed by your application.