Wiring Up Streaming Output: From the First Text Chunk to the Complete Answer
Understand how streaming responses differ from ordinary JSON, and get a handle on SSE framing, incremental assembly, request cancellation, and clean failure handling, so waiting in a chat interface feels natural.

Making users wait for the complete answer before showing anything often feels sluggish. Streaming output lets an application reveal text progressively while it is generated. It improves perceived wait time, but it does not guarantee the total generation time is shorter.
First Confirm the Model Supports Streaming Requests#
For models that support the chat completions protocol, you can usually request a streaming response with stream: true. Event structures differ across protocols, so read the model's documentation before integrating, and use a minimal request to confirm the Content-Type and data format actually returned.
Do not carry over the handling you wrote for plain responses: a streaming response is not one complete object you JSON-parse after it ends — it is a series of events delivered according to the protocol.
A Network Chunk Is Not a Complete Event#
One network read may yield half an event, or it may contain several events. UTF-8 characters can also straddle chunk boundaries, so keep feeding the same streaming decoder and keep the text that has not finished parsing.
A robust processing order:
- Hand the received bytes to a streaming text decoder.
- Append the decoded result to a buffer.
- Extract complete events at SSE blank-line boundaries, tolerating the line endings the protocol specifies.
- Join the
data:lines inside an event and ignore comments or heartbeats. - Parse the event according to the current protocol, and leave any incomplete tail for the next read.
Do not run JSON parsing directly on each read's result, and do not assume every chunk carries exactly one data: line. Production applications should prefer a well-maintained SSE parser.
Assemble the Text — and Recognize the End Signal#
In chat-completions-compatible protocols, the text increment usually sits in choices[].delta.content. Some events only carry the role, the finish reason, or other information; an empty text field is not necessarily an error.
The following is a protocol sketch; not every model returns exactly these fields:
data: {"choices":[{"delta":{"content":"Hello"}}]}
data: {"choices":[{"delta":{"content":", nice to meet you."}}]}
data: [DONE][DONE] is an end marker used by some compatible protocols and does not generalize to every endpoint. Tool call arguments can also arrive in fragments; merge and validate them completely per the protocol instead of executing the moment you see a partial argument.
The UI Needs at Least Four States#
| State | UI suggestion |
|---|---|
| Waiting for the first chunk | Show “connecting” or “waiting for a response”, and keep a cancel affordance |
| Streaming | Append text, and avoid triggering expensive re-renders on every character |
| Finished cleanly | Stop the loading state and enable follow-up actions such as copy |
| Interrupted or failed | Keep the content already received and clearly mark it as incomplete |
Before the first text arrives, check the HTTP status. Once the transfer has started, error events and disconnections can still happen; an initial 200 alone does not make the task a success.
Handle Cancellation and Mid-Stream Drops#
When the user switches sessions, closes the page, or clicks stop, the client should stop reading and cancel the request. If your own server sits in between, forward the cancellation signal to the upstream handling logic so it does not keep working for nothing.
After partial content has already been shown, do not silently resend and splice the new answer onto the old one. The cleaner approach: mark this output as interrupted, let the user choose to regenerate, and present the new attempt as a separate answer.
Finally, check whether the reverse proxy buffers responses, whether idle connections time out at a reasonable point, and whether Markdown rendering keeps jumping because of unclosed code fences. For related debugging steps, see the API error troubleshooting guide.

