Principle:AI QL Tuui Chat Completion Streaming
| Knowledge Sources | |
|---|---|
| Domains | LLM, Streaming, SSE |
| Last Updated | 2026-10-24 00:00 GMT |
Overview
A streaming pattern that reads LLM chat completion responses incrementally via Server-Sent Events, parsing SSE data lines into structured deltas for real-time display.
Description
Chat Completion Streaming addresses the latency problem of waiting for a full LLM response before displaying it to the user. By reading the HTTP response body as a ReadableStream, splitting SSE data: lines, and parsing each JSON delta incrementally, the pattern enables token-by-token rendering. It handles both streaming (SSE line-split mode) and non-streaming (single JSON) responses. The pattern also separates reasoning content (think tags) from regular content during parsing.
Usage
Use this principle when building chat interfaces that need real-time token streaming from OpenAI-compatible LLM APIs, where the response arrives as a stream of incremental JSON deltas.
Theoretical Basis
The streaming flow operates as a recursive reader:
1. fetch(url, { signal: abortController.signal }) → Response
2. response.body.getReader() → ReadableStreamDefaultReader
3. read(reader) recursively:
a. reader.read() → { done, value: Uint8Array }
b. TextDecoder.decode(value) → string
c. If streaming mode:
- Split by '\n', buffer incomplete last line
- For each line: extract "data:" prefix content
- Skip "[DONE]" sentinel
- parseJson(content) → parseChoices → parseChoice
d. If non-streaming: parseJson(chunks)
e. Recurse until done
The delta accumulation pattern merges incremental content into a single AssistantMessage: