Stream text safely when stop sequences can span chunks

Why it matters Every streaming chat API implements stop-sequence handling, and leaking half a stop token like "<|e" to users is a common production bug.

When streaming, the server must never send part of a stop sequence to the client. If the text so far ends with "<|e" and the stop string is "<|end|>", those characters have to be held back until the next chunk shows whether the stop really arrived.

Write stream_with_stops(chunks, stops). chunks is a list of text pieces in arrival order; stops is a list of non-empty stop strings. Keep a buffer of held text. For each chunk, set buf = held + chunk.
- If any stop string occurs in buf, cut at the earliest occurrence (smallest start index), emit buf before it, and stop processing: return (emits, True).
- Otherwise find the largest k such that the last k characters of buf are a proper prefix (shorter than the full string) of some stop. Emit buf without those k characters and hold them.
emits gets one string per processed chunk (possibly empty). If the stream ends with no stop, append one final string with the held text and return (emits, False).

Signaturedef stream_with_stops(chunks, stops)

Example

chunks ["Hi <", "|e", "nd|> bye"], stops ["<|end|>"] gives (["Hi ", "", ""], True).

Understand the idea

Holdback is like a news anchor reading a live feed with a few seconds of delay. If a sentence might turn into something that must not go on air, the delay gives time to cut it. For streaming, the risky part is the tail of the text that matches the beginning of a stop string. Worked example: stop is "<|end|>". After chunk "Hi <", the tail "<" could start the stop, so only "Hi " is sent and "<" is held. After "|e", the buffer "<|e" still could, so nothing is sent. The next chunk completes "<|end|>", so streaming ends and the held text is dropped. Rule: if a stop occurs, emit text before its earliest start and end; else hold the longest suffix that is a proper prefix of a stop. Chat servers do this for chat template end markers and user-provided stop words.

solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

Run checks the first 2 tests. Submit checks the hidden tests with Pro.

  • Sample 1: examplestream_with_stops(['Hi <', '|e', 'nd|> bye'], ['<|end|>'])
  • Sample 2: false alarmstream_with_stops(['a <', '|x', 'yz'], ['<|end|>'])