Read an SSE chat stream
With stream: true, the OpenAI-compatible chat API answers with Server-Sent Events. Join the text fragments and stop at [DONE].
An SSE stream arrives as text with one line per event: data: {json}. Each JSON carries the fragment in choices[0].delta.content, which may be missing (for example, the first event only carries role). Lines starting with : are comments (keep-alive) and empty lines separate events.
Write parseSSE(text) that returns the full text. Ignore comments, empty lines and any line that does not start with data:. When data: [DONE] arrives, stop: anything after it does not count. The space after data: is optional.
The variable SAMPLE holds an example stream.
One more check uses LIVE: real output from your own Ollama if you switch on "My Ollama", or a different sample if not. That check looks at structure, not exact words.
Challenges 0/5
- Joins the text of SAMPLE
- Skips events without content (no 'undefined')
- Stops at data: [DONE]
- Accepts data: without a space and ignores other lines
- Works on the real stream from your model (My Ollama) or another sample
function parseSSE(text) {
// 1. split into lines
// 2. keep only lines that start with 'data:'; stop at [DONE]
// 3. JSON.parse and append choices[0].delta.content when present
let out = '';
for (const line of text.split('\n')) {
if (line.startsWith('data: ')) {
const chunk = JSON.parse(line.slice(6));
out += chunk.choices[0].delta.content;
}
}
return out;
}
try { console.log(parseSSE(SAMPLE)); } catch (e) { console.error(e.message); }Tab indents, Ctrl+Z undoes. To leave the editor with the keyboard: Esc, then Tab.
Why this matters
With stream: true, Ollama, vLLM, LiteLLM and any OpenAI-compatible API answer like this. If you draw a chat on a page, this parser is your code: the first event carries no text, comments arrive to keep the connection alive, and [DONE] is not JSON. A parser that does not expect those three cases works in the demo and breaks with a proxy in between. Open WebUI does this same job for you; if you would rather not write it, see Open WebUI for a 10-person office.
Go deeper: the MDN reference →
This in production, with your data? Let's talk for 15 minutes →