Code Lab / Challenge 13

Streaming SSE Parser + Tool-Call Assembler

HardSSE parser, incremental tool-call argument assembly

The problem, as an interviewer would set it

LLM APIs stream responses as Server-Sent Events over HTTP. The network hands
you raw byte chunks split at ARBITRARY boundaries - mid-line, even mid-way
through a multi-byte UTF-8 character. Implement:

1. SSEParser - incremental push parser.

       feed(chunk: bytes) -> list[SSEEvent]   # complete events only

   Requirements:
   - byte chunks may split anywhere; buffer partial lines AND partial UTF-8
     sequences (an emoji is 4 bytes and can straddle chunks)
   - `data:` field lines; multiple data lines in one event join with "\n"
   - `event:` field sets the event type (default "message")
   - comment lines starting with ":" are ignored (keep-alive pings)
   - events are dispatched on a blank line; `data: [DONE]` marks the sentinel
     (SSEEvent.done == True)
   - handles both "\n" and "\r\n" line endings
   - feeding the same byte stream in different chunkings must yield the
     IDENTICAL sequence of events.

2. ToolCallAssembler - reassembles streamed tool calls. Providers stream a
   tool call as deltas: the name/id arrive first, then the JSON `arguments`
   string arrives in fragments (which are NOT individually valid JSON).

       add_delta(index, *, id=None, name=None, arguments=None) -> None
       is_complete(index) -> bool     # accumulated args parse as JSON?
       finish() -> list[ToolCall]     # all calls, ordered by index
What interviewers look for

Handling chunks split mid-event/mid-JSON, buffering discipline, partial-parse recovery

A strong solution demonstrates:
- Two distinct buffering layers: bytes -> text (incremental UTF-8 decoder)
  and text -> lines (find "\n" in a buffer). Decoding each chunk with
  bytes.decode() crashes on a split code point, the most common bug here and
  one that only shows up on non-ASCII output in production.
- Push-parser design: feed() returns only COMPLETE events and keeps partial
  state; no assumption that one chunk == one event (or even one line).
- Knowing the SSE grammar details: value may have one optional leading space
  ("data: x" and "data:x" are both "x"); a lone "data" line means empty data;
  comments keep connections alive through proxies.
- For tool calls: argument fragments are meaningless until concatenated.
  "Accumulated string parses as JSON" is a useful readiness check, but the
  authoritative end of a call is the provider's own signal (a finish reason,
  or a content-block or output-item done event). Dispatch on that, then
  validate the parsed arguments against the tool's schema.
- Wire formats differ: [DONE] is an OpenAI Chat Completions convention.
  Other APIs end with a typed event (e.g. message_stop, response.completed)
  and name every event via `event:`, so the parser must not depend on [DONE].
Common mistakes: bytes.decode() per chunk (UnicodeDecodeError on split
emoji); str(chunk) instead of decoding; discarding "data:" lines that follow
another (multi-line data is legal); treating [DONE] as JSON; json.loads on
each argument fragment; letting `event:` leak into the next event instead of
resetting it on dispatch.
Follow-ups: support the `id:` field and Last-Event-ID reconnection; lone-\r
line endings and a leading UTF-8 BOM, both in the SSE spec; backpressure via a
generator API; parallel tool calls interleaved by index (already supported
here - discuss why the index, not order of arrival, keys the accumulator).

Write your own version first. The reference solution and its tests are one click away when you are ready.

Next challenge