Velamuvi AIAcademy

Lesson 8 of 11 · Generation

Stop Sequences and Max Tokens

How LLM output ends: end-of-turn tokens, max tokens, stop sequences and finish reasons. Detect truncated answers and control length and cost, in Python.

  • 6 min read
  • Intermediate
  • Reviewed
In this lesson you will learn
  • The three ways a model's output can end
  • What max tokens does, and what it does not do
  • How stop sequences work and when to use them
  • Why you should always check the finish reason

How does a model know when to stop?

A model writes token after token. Something has to end the loop. There are three possibilities:

  1. The model decides it is finished. It produces a special end-of-turn token, which it learned during fine-tuning.
  2. It hits the length limit you set, called max tokens.
  3. It writes a stop sequence, a piece of text you told the API to stop at.

Every API response tells you which one happened.

Seeing all three

The program below simulates a model producing a list, token by token, and applies different limits.

Try it yourselfPython
# The tokens a model would produce, one by one, if nothing stopped it
stream = ["Item", " 1", ":", " apples", "\n", "Item", " 2", ":", " pears", "\n",
          "Item", " 3", ":", " plums", "\n", "\n", "Note", ":", " prices", " vary"]

def generate(max_tokens, stop_sequences):
    output = ""
    for count, token in enumerate(stream):
        if count == max_tokens:
            return output, "max_tokens"           # ran out of room
        output += token
        for stop in stop_sequences:
            if stop in output:
                return output[:output.index(stop)], "stop_sequence"
    return output, "end_turn"                      # the model finished by itself

for max_tokens, stops in [(100, []), (7, []), (100, ["\n\n"]), (100, ["Item 3"])]:
    text, reason = generate(max_tokens, stops)
    print(f"max_tokens={max_tokens:<3} stops={stops!r:<12} -> {reason}")
    print("   " + repr(text))
  • With no limits, the model finished by itself (end of turn), including a note we may not want.
  • With max_tokens = 7, the output was cut off mid-list: "Item 2" with nothing after it.
  • With the stop sequence "\n\n" (a blank line), generation stopped cleanly after the list, dropping the note.
  • With the stop sequence "Item 3", it stopped after two items. The stop sequence itself is not included in the output.

Max tokens

Max tokens is a safety limit, not a length instruction:

  • It protects you from runaway responses and unexpected costs.
  • It does not make the model plan a shorter answer. The model does not know the limit exists; it just gets cut off.
  • To get a short answer, ask for one ("under 100 words") and set max tokens with some headroom above that.
  • For reasoning models, thinking tokens usually count toward the limit too, so set it high enough for thinking plus answer.

Stop sequences

Stop sequences are handy when output has a predictable shape:

  • Stop at a closing tag such as </answer> to get exactly the answer and nothing after it.
  • Stop at a blank line to get a single paragraph or list.
  • In few-shot formats like "Q: ... A: ...", stop at the next "Q:" so the model doesn't invent extra questions.

Always check the finish reason

Common mistakes

Practice exercise

Check the finish reason of each response, so truncated answers are never shown as if they were complete.

Your solutionPython
responses = [
    ("Paris is the capital of France.", "end_turn"),
    ("The three main causes were: first, the", "max_tokens"),
    ("Here is your summary in 3 bullet points.", "end_turn"),
    ("Step 1: open the", "max_tokens"),
]

# For every response that stopped because of max_tokens, print:
# Cut off: <the text>
# Then print a final line like: 2 of 4 responses need a retry
Knowledge check

A response's finish reason says the maximum token limit was reached. What does that tell you?

Summary

  • Output ends when the model emits end of turn, reaches max tokens, or produces a stop sequence.
  • Max tokens is a ceiling for safety and cost, not a way to make answers shorter.
  • Stop sequences end output cleanly at a predictable point, such as a closing tag.
  • Always check the finish reason, and handle cut-off responses.

Next: open and closed models, and how to choose between them.

Finished reading? Tick it off to track your progress.