Streaming Chat in Practice: the stream Flag, Rendering Tokens, Usage and What Happens When You Disconnect

CQTAI

10/28/2026

#Streaming#Chat API#SSE#Developers
Streaming Chat in Practice: the stream Flag, Rendering Tokens, Usage and What Happens When You Disconnect

A long answer can take ten seconds or more to finish. If your interface shows nothing until the last token arrives, that feels broken, even though nothing is wrong. Streaming fixes the feeling: the server sends the answer in small pieces as it is produced, so your user starts reading almost at once.

The chat endpoint streams the same way the OpenAI API does, so the code you already know works.

Turn it on

Add "stream": true to the request:

curl -N https://api.novapi.ai/v1/chat/completions \
  -H "Authorization: Bearer $API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "MODEL_ID",
    "stream": true,
    "messages": [{ "role": "user", "content": "Write a four-line poem about debugging." }]
  }'

-N tells curl not to buffer, so you see pieces as they arrive. The response is a stream of server-sent events. Each event is a line starting with data: that carries a JSON chunk, and the stream ends with data: [DONE].

data: {"choices":[{"delta":{"content":"Bugs"},"index":0}]}

data: {"choices":[{"delta":{"content":" hide"},"index":0}]}

data: [DONE]

The text lives in choices[0].delta.content. Some chunks carry no text (the first one often holds only the role), so treat a missing content as an empty string.

Python

import os
from openai import OpenAI

client = OpenAI(base_url="https://api.novapi.ai/v1", api_key=os.environ["API_KEY"])

stream = client.chat.completions.create(
    model="MODEL_ID",
    messages=[{"role": "user", "content": "Write a four-line poem about debugging."}],
    stream=True,
)

for chunk in stream:
    if chunk.choices and chunk.choices[0].delta.content:
        print(chunk.choices[0].delta.content, end="", flush=True)
print()

The flush=True matters in a terminal. Without it, Python buffers the output and the stream looks like a single block.

In a browser

Never call the API directly from browser code, because that would put your key in the page. Call your own server, and let it forward the stream. On the page, read it with fetch:

const res = await fetch("/api/chat", {
  method: "POST",
  headers: { "Content-Type": "application/json" },
  body: JSON.stringify({ prompt: "Write a four-line poem about debugging." }),
});

const reader = res.body!.getReader();
const decoder = new TextDecoder();
let buffer = "";

while (true) {
  const { value, done } = await reader.read();
  if (done) break;
  buffer += decoder.decode(value, { stream: true });

  const lines = buffer.split("\n");
  buffer = lines.pop() ?? ""; // keep the last, possibly partial, line

  for (const line of lines) {
    if (!line.startsWith("data:")) continue;
    const data = line.slice(5).trim();
    if (data === "[DONE]") return;
    const text = JSON.parse(data).choices?.[0]?.delta?.content;
    if (text) appendToScreen(text);
  }
}

The buffer is the part people forget. A network packet can end in the middle of a line, so keep the incomplete tail and finish it with the next read.

Usage and billing

Chat is billed by tokens, from the usage the model reports. For a stream, that report arrives at the end. You do not have to do anything for billing to work: the gateway asks the upstream for usage on every streamed request and bills from it.

If you want to see the numbers yourself, ask for them in the usual way:

{ "stream": true, "stream_options": { "include_usage": true } }

The last chunk before [DONE] then has an empty choices list and a usage object with prompt and completion tokens. Make sure your reader copes with a chunk that has no choices, as the code above does. If you do not ask for usage, you will not receive that chunk.

If the client disconnects

Closing the connection stops you from receiving more, but the model may already have produced tokens that you did not read. When a stream ends early, or the upstream never reports usage, and some text has already been sent to you, the gateway bills an estimate of the tokens produced. You are charged for what was generated and delivered, not for the full length you asked for, and not nothing.

That suggests three habits:

  • Let users stop a generation (a Stop button), because it saves points when the answer is going the wrong way.
  • Set max_tokens so a runaway answer has a ceiling.
  • Do not open streams you do not read.

A short checklist

  • Use curl -N or flush=True while testing, so you can see the stream.
  • Buffer incomplete lines and parse only complete data: lines.
  • Handle chunks without choices and a final [DONE].
  • Keep your key on the server.
  • Add a Stop button and a max_tokens limit.

To choose which model to stream from, see comparing models with one script.

    Streaming Chat in Practice: the stream Flag, Rendering Tokens, Usage and What Happens When You Disconnect