BLOGLLM Logo
Go Pro
Guest
Not signed in
All BlogsCoursesPracticeInterview prepSeriesTagsBookmarksPricing
Log in
All BlogsCoursesPracticeTagsBookmarksPricing
My PrepProblemsStudy PlansResearch PapersRoadmapInterviewContestsLeaderboardGames
Articles
Practice / LLM inference and serving31 of 36 in topic

790. Parse a server-sent event stream that arrives in random chunks

MediumLLM inference and serving Pro

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.

Functiondef 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.

Topics
LLM inference and serving
Similar questions
  • Generate one token at a time with a KV cacheMedium
  • Allocate KV cache memory in pages, like vLLMMedium
  • Verify a draft model's guesses in speculative decodingMedium
  • Is decoding memory-bound? A roofline estimateMedium
All LLM inference and serving problems
Report
790 / 903
Python 3solution.pyPython idle
1
2
3
4
def parse_stream(chunks):
# return the list of event payloads
pass
​

Run checks these cases in your browser, no sign-in needed. Submit checks the full hidden test set with Pro.

Ctrl/Cmd + Enter to run
© BlogLLM, Bengaluru, IndiaAboutTermsPrivacyRefundsDMCAContactRSS