790. Parse a server-sent event stream that arrives in random chunks
Streaming LLM APIs send tokens as server-sent events over HTTP. The network hands your client arbitrary chunks, so one event, or even one line, can be split across chunks.
Write parse_stream(chunks) that takes a list of string chunks and returns the list of event payloads in order.
Format: lines end with '\n' (a '\r' right before it should be removed). A line 'data: X' adds X to the current event (remove exactly one space after the colon if present). Several data lines in one event are joined with '\n'. A line that starts with ':' is a comment. Other field lines such as 'event: x' are ignored. A blank line ends the event; an event with no data lines produces nothing. If an event's payload is '[DONE]', stop and do not return it. A partial event left at the end without a blank line is dropped.
def parse_stream(chunks)Example 1
Input: chunks = ['data: He', 'llo\n\nda', 'ta: world\n\n']
Output: ['Hello', 'world']
Constraints
- At most 10,000 chunks.
- Standard library only.
Hint 1
Never assume a chunk ends at a line break.
Hint 2
An event is complete only at a blank line.
Hint 3
Strip only one leading space after the colon.
Common mistakes
- Splitting each chunk on newlines on its own, which breaks lines that span chunks.
- Using strip(), which also removes meaningful spaces inside the token text.
- Emitting the [DONE] sentinel as a token.
Understand the idea
Server-sent events are a plain text protocol: each event is a few 'field: value' lines followed by a blank line. The catch is that TCP gives you bytes in whatever pieces it likes, so a chunk boundary can fall in the middle of a word. The fix is a buffer: add each chunk, process only full lines, keep the remainder. For example 'data: He' then 'llo\n\n' only becomes the event 'Hello' after the blank line arrives. Every streaming chat client, and every proxy that relays tokens, needs this exact loop.