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:
\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".: are comments and are ignored, as are other fields.[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.