Lesson 6.3 · 3 of 5 · 4 min read · Reviewed 24 Nov 2026
Stop sequences and max_tokens
By the end, you can
- Use stop sequences and max_tokens.
- Control where output ends.
max_tokens
A required cap on output tokensOutput tokens: The tokens the model generates in its reply, including any tool calls and thinking. per response. If reached, the response stops and stop_reason is max_tokens (3.4).
| Too low | Too high |
|---|---|
| Answers cut off mid-thought | Little harm in itself; you pay for tokens actually generated |
Set it comfortably above the longest answer you expect, and control length with instructions.
Stop sequences
Strings that end generation as soon as they’re produced:
{
"stop_sequences": ["</answer>", "\n\nHuman:"],
"messages": [...]
}
The response has stop_reason: "stop_sequence" and stop_sequence set to the one that matched. The stop string itself isn’t included in the output.
Uses
- End after a closing tag when you prefillPrefilling: Writing the first part of the assistant’s reply yourself so the model continues from there. an opening tag, on models that still accept prefill (13.3)
- Stop list generation after a set marker
- Prevent the model continuing into a second, unwanted section
Don’t over-rely on them
For structured outputStructured outputs: Making a model return data that matches a defined schema, such as JSON with required fields and types., tool use or structured outputs are more reliable than stop sequencesStop sequence: A string that makes the model stop generating as soon as it produces it. (chapter 14). Use stop sequences as a simple, cheap control where they fit.
Key points
- max_tokens caps how many tokens the model may generate in one response.
- Stop sequences end generation as soon as a given string appears; the response says which one matched.
- Use them for structure (stop after a closing tag) and for cost and length control.
Cut a token stream at stop sequences
Implement max_tokens and stop sequences the way an API does, including a stop string split across two tokens.
You will have: A generate() function that returns the text, the stop_reason and the matched stop sequence for three test streams.
Steps
- Run the starter: it joins every token and always reports end_turn.
- Stop when the output reaches max_tokens and report max_tokens.
- Stop as soon as the text so far contains a stop sequence; cut it out of the output and report which one matched.
- Make sure '</answer>' is caught even when it arrives as '</ans' and 'wer>'.
- Run all three streams and compare with the expected results.
Done when
- Stream A stops at '</answer>' with the stop string removed.
- Stream B reports max_tokens after 5 tokens.
- Stream C catches a stop sequence split across tokens.
Open in the Playground No API key needed.
Starter code (Python)
STREAMS = {
"A": ["<answer>", "30", " days", "</answer>", " Also", " shipping"],
"B": ["The", " refund", " window", " is", " 30", " days", " from", " delivery"],
"C": ["<answer>", "Yes", "</ans", "wer>", " extra"],
}
def generate(tokens, stop_sequences, max_tokens):
text = "".join(tokens) # TODO: build text one token at a time instead
# TODO: stop at max_tokens -> ("max_tokens", None)
# TODO: stop when any stop sequence appears in text -> cut it, ("stop_sequence", seq)
return text, "end_turn", None
for name, toks in STREAMS.items():
print(name, generate(toks, ["</answer>"], max_tokens=5))
Show a solution
STREAMS = {
"A": ["<answer>", "30", " days", "</answer>", " Also", " shipping"],
"B": ["The", " refund", " window", " is", " 30", " days", " from", " delivery"],
"C": ["<answer>", "Yes", "</ans", "wer>", " extra"],
}
def generate(tokens, stop_sequences, max_tokens):
text = ""
for count, tok in enumerate(tokens, start=1):
text += tok
for seq in stop_sequences:
at = text.find(seq)
if at >= 0:
return text[:at], "stop_sequence", seq
if count >= max_tokens:
return text, "max_tokens", None
return text, "end_turn", None
for name, toks in STREAMS.items():
print(name, generate(toks, ["</answer>"], max_tokens=5))