Parse a Streaming LLM Response (SSE)

medium
Unit 1 · LLMs0/3 to milestone

LLM APIs stream tokens as Server-Sent Events. The network delivers arbitrary chunks, so a line, or even the word data, can be split across two chunks.

The format:

  • Events are separated by a blank line. Lines end with \n or \r\n.
  • data: <text> lines carry the payload. Several data: lines in one event are joined with \n. Strip one optional space after the colon.
  • event: <name> sets the event type, which defaults to "message".
  • Lines starting with : are comments and are ignored, as are other fields.
  • An event whose data is exactly [DONE] ends the stream: set done = True and don't emit it.

Implement a class SSEParser with feed(chunk) -> list[dict], which returns the complete events in this chunk as {"event": name, "data": text}, buffering any partial event for later. It also has a done attribute. Events with no data lines are skipped.

#streaming#apis#parsing3 visible + 3 hidden tests
solution.py · Python 3.13
Loading editor…
Run your code to see results. ⌘↵ to run · ⌘⇧↵ to submit
Parse a Streaming LLM Response (SSE) · TechGradify