Sub topic 3
Rendering Partial Output in Streaming LLM Interfaces
Assume basic HTTP, JSON, JavaScript promises, and LLM API requests. A streamed response arrives as small text deltas. The UI should append each delta immediately instead of waiting for the complete message.
Render and relay the stream
A browser can read the response body and update an element as data arrives:
async function showResponse(url, prompt, output, stopButton) {
const controller = new AbortController();
stopButton.onclick = () => controller.abort();
const response = await fetch(url, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ prompt }),
signal: controller.signal
});
if (!response.ok || !response.body) {
throw new Error(`Request failed: ${response.status}`);
}
const reader = response.body
.pipeThrough(new TextDecoderStream())
.getReader();
let buffer = "";
try {
while (true) {
const { value, done } = await reader.read();
if (done) break;
buffer += value;
const events = buffer.split("\n\n");
buffer = events.pop();
for (const event of events) {
for (const line of event.split("\n")) {
if (line.startsWith("data: ")) {
const data = line.slice(6);
if (data !== "[DONE]") {
output.textContent += JSON.parse(data).delta;
}
}
}
}
}
} catch (error) {
if (error.name !== "AbortError") {
output.textContent += "\n[Generation failed]";
}
}
}Your backend should keep the provider connection open and relay events as they arrive. Return text/event-stream, disable caching, and disable buffering in the proxy when supported.
Tool calls, buffering, and flow control
Tool-call arguments often arrive as fragments such as {"city":"Pa and ris"}. Append fragments by tool-call ID, then parse JSON only after the provider signals that the tool call is complete. Never execute partial JSON.
Reverse proxies and serverless platforms may buffer output until a threshold. Test the complete production path, not only the local server. Slow browsers also create backpressure: bound queues, avoid unbounded buffering, and apply cancellation or timeouts.
SSE is usually simpler for one-way model output. Use WebSockets when the connection needs frequent two-way messages, such as collaborative state or interactive tool negotiation. WebSockets add connection-management and scaling complexity.
| Transport | Best fit |
|---|---|
| SSE | Server-to-browser token updates |
| WebSockets | Continuous two-way interaction |
Exercise
Why should a streamed tool-call fragment not be parsed immediately?
Show answer
The fragment may contain incomplete JSON. Accumulate all fragments for that call, then parse and validate the complete argument object.