Streaming
Streaming means you get the answer piece by piece, as the AI writes it, instead of waiting for all of it. It is how chat screens show words appearing one after another.
client.chat.stream() gives you an AsyncGenerator<string>: a list of text pieces (called deltas) that you can loop over as they arrive. Use it for live screens where the answer should appear word by word.
Basic streaming
const stream = client.chat.stream({
model: 'auto',
messages: [{ role: 'user', content: 'Write a haiku about the sea.' }],
});
for await (const chunk of stream) {
process.stdout.write(chunk); // or append to UI
}
for await waits for each piece, one at a time, and runs your code on it.
Collecting the full text
Want the whole answer at the end as well? Add the pieces together:
let fullText = '';
for await (const chunk of client.chat.stream({
model: 'auto',
messages: [{ role: 'user', content: 'Tell me a story.' }],
})) {
fullText += chunk;
}
console.log(fullText);
React example
This keeps adding pieces to what is already on screen:
async function streamToState(
messages: ChatMessage[],
setText: (t: string) => void,
) {
let accumulated = '';
for await (const chunk of client.chat.stream({ model: 'auto', messages })) {
accumulated += chunk;
setText(accumulated);
}
}
Parameters
stream() accepts the same parameters as complete(). See Chat completions.
The generator gives you text only, so the SDK does not expose the gateway's X-Router-* response headers. To find out whether Artemis or the fallback router decided a streamed request, and why, look it up with client.requests.list() (see Which router decided).
How it works inside
NuRoute uses server-sent events (SSE), a standard way for a server to push small messages to you over one open connection.
The generator reads the data: … lines from the response and gives you the choices[0].delta.content field of each one. The special [DONE] message ends the stream automatically.