#440Stop-Sequence Detection (Streaming)EasyLLMsML System DesignAsked atOpenAI · Anthropic · Cohere
Stop-Sequence Detection (Streaming)
Background
LLM streaming generation needs to detect when a stop sequence appears so it can cut off mid-token-batch. The complication: a stop sequence like "</answer>" may straddle two streamed chunks. The streaming buffer keeps the last characters from the previous chunk so cross-chunk matches are caught.
Problem statement
Implement detect_stop(streamed_chunks, stop). Walk the chunks in order, return the index of the chunk in which the stop sequence first completes, OR -1 if it never appears.
Input
streamed_chunks-list[str], concatenation-order text chunks.stop-str, the stop sequence.
Output
int, the chunk index wherestopcompletes (the last char ofstoplies in this chunk), or-1.
Examples
Input: chunks=["The ans", "wer is ", "42</an", "swer>"], stop="</answer>"
Output: 3 # completes in the last chunk; straddles chunks 2-3
Constraints
- Empty
stopraisesValueError. - Length 1 string (or matching only within one chunk) returns the chunk it appears in.
Notes
- Why buffer. Concatenating all of history is wasteful; keeping just the last chars from the running buffer is sufficient.
Python
Loading...
▶ Run executes the 3 visible sample tests below in your browser. Submit runs the full suite — including hidden tests — on the server for an official verdict.
- •Reference example straddling two chunks
- •Sample fully inside one chunk
- •Reference completion inside the second chunk