Overview

A stop sequence is a string sent with the request; generation halts as soon as the model produces it, and the string is not included in the output. Pass several and the first match wins. Use one when the output has a known end marker and anything after it is waste or risk, such as a closing tag, a delimiter, or a simulated next speaker turn.

Stop sequences give a semantic boundary and max_tokens gives a hard length ceiling; use both. They are not a reliable way to make answers shorter, so ask for brevity in the prompt. In the Claude API the parameter is stop_sequences (a list). When one fires, stop_reason is "stop_sequence" and the stop_sequence field holds the matched string.

Example

response = client.messages.create(
    model="claude-sonnet-5-5",
    max_tokens=512,
    stop_sequences=["</answer>"],
    messages=[{"role": "user", "content": "What is 2+2? Wrap the result in <answer>...</answer> tags."}],
)
print(response.stop_reason)  # "stop_sequence"