LearnQuestion bank

Model output arrives as arbitrary text chunks. Write a parser that emits each complete tool call (in a given XML or JSON format) as soon as it closes, while passing plain text straight through. Variant: write the server side that streams words incrementally like an LLM endpoint.

Applied LLMCodingHard

Answer it yourself first, out loud or on paper, then compare.

Answer

Model answer, written in a candidate's voice

In short

  • Use an incremental state machine over a small buffer, not a regex over the whole stream.
  • Emit plain text immediately; buffer only a partial tag, brace, string, or escape until the call closes.
  • Track nesting depth and string/escape state so JSON braces and XML tags split across chunks still parse correctly.
  • Process each byte once for linear time; define EOF behaviour for unterminated or malformed calls as an explicit error/flush, never silent loss.
  • For the server variant, stream words through bounded queues with backpressure, cancel on client disconnect, and flush partial output on close.
  • Validate with property-style tests over random chunk boundaries, escapes, nesting, and malformed tails, comparing against a batch parser.

In full

I would treat the stream as a sequence of bytes feeding a small finite-state machine, not as text to re-parse after every chunk. Plain text is passed through as soon as it is safe, while only a partial tag, brace, string, or escape is held in a bounded buffer; when the matching close is seen, the complete tool call is emitted and the buffer resets. For JSON I track string state, escapes, and brace depth; for XML I track tag state and nesting, so a call split across chunks still closes exactly once. At end of stream, an unterminated or malformed call is reported as an explicit error or flushed as partial output according to a documented policy, never silently dropped. On the server side I would stream words incrementally through bounded queues, apply backpressure when the client is slow, cancel work on disconnect, and flush on close or timeout. I would test with property-style random chunk boundaries, random escapes and nesting, and malformed tails, checking that the incremental result matches a batch parser and that slow clients and disconnects do not lose or duplicate output.

Corrected by an independent AI reviewer.

What a strong answer covers

  • State machine with a buffer; handles tags or braces split across chunk boundaries; escapes and nested structures
  • Linear-time processing (no re-parsing the whole buffer per chunk)
  • Defined behaviour for malformed or unterminated input at end of stream
  • Property-style tests with randomised chunk boundaries; server variant handles backpressure, client disconnects and flushing

Common mistakes

  • Assuming tags never span chunks
  • quadratic re-parsing