Reading a streamed reply

Take your time, follow the code and check your understanding.

The codeLLM API basics
// The server streams lines such as:
// data: {"choices":[{"delta":{"content":"Hel"}}]}
// data: [DONE]
for (const line of text.split("\n")) {
  const chunk = JSON.parse(line);
  output += chunk.choices[0].delta.content;
}
Your answer4 min · no timer
What needs fixing?

Show solution and explanation

Server-sent events prefix each payload with "data: " and finish with a literal [DONE] marker. Remove the prefix, stop at [DONE], skip blank lines, then parse the JSON.

JSON.parse fails because each line starts with "data: " and the last one is [DONE].