Parse a Streaming Chat Completions Response from Raw Bytes

Last updated: November 29, 2026

Quick Overview

Given the raw byte chunks of a server-sent events response from an OpenAI-compatible chat completions endpoint, reassemble the generated text, the finish reason and the usage block, handling events split across chunk boundaries.

Together AI
Coding & Algorithms
Software Engineer
Together AI
November 29, 2026
Software Engineer
Technical Screen
Coding & Algorithms
Easy

0

0

0 solved


Given the raw byte chunks of a server-sent events response from an OpenAI-compatible chat completions endpoint, reassemble the generated text, the finish reason and the usage block, handling events split across chunk boundaries.

Together AI exposes an OpenAI-compatible API with `stream=true`, and its SDKs and gateway have to parse server-sent events correctly. This screen checks careful buffering and protocol handling more than algorithms: chunk boundaries that split lines or UTF-8 characters, keep-alive comments, the `[DONE]` sentinel, and error events.

What the Interviewer Expects
  • Buffers bytes and only splits on complete lines
  • Decodes UTF-8 per complete line so multibyte characters split across chunks survive
  • Treats a blank line as the end of an event and joins multi-line data fields
  • Ignores comment lines used as keep-alives
  • Stops on the [DONE] sentinel and surfaces error events
Key Topics to Cover
server-sent events
streaming parsing
UTF-8 boundaries
buffering
API clients
How to Approach This
  1. Clarify input constraints and edge cases before writing code.
  2. Walk through your approach verbally and confirm with the interviewer before coding.
  3. Start with a brute force solution, then optimize. Mention time and space complexity.
  4. Test your solution with examples, including edge cases like empty input or duplicates.
  5. Consider common patterns: sliding window, two pointers, hash map, BFS/DFS, dynamic programming.
Possible Follow-up Questions
  • How would you expose this as a generator that yields deltas as soon as they arrive?
  • What should the client do if the connection drops before [DONE]?
  • How would you handle multiple choices (n greater than 1) in one stream?
  • Where would you measure time to first token in this loop?
Sharpen Your Skills on Codemia

Practice similar problems with our interactive workspace, get AI feedback, and track your progress.

Practice DSA Problems
Sample Answer
Requirements

Input is an iterable of byte chunks exactly as the socket delivers them, so a chunk can end mid-line or mid-character. Events are lines prefixed data:, terminated by a blank line. Lines starting wit...

High-Level Design

Keep a byte buffer. Append each chunk, then repeatedly cut off complete lines at \n. Decode only complete lines, which avoids breaking a multibyte character such as an accented letter or CJK text th...


Submit Your Answer
Markdown supported

Related Questions