Skip to content
Blog

Stop Sequences: Early Generation Termination in ADK

How stop sequences cut generation at exactly the right point — configuration, multi-sequence rules, structured-output interplay, and when a stop sequence beats prompt instructions.

Published on • November 25, 2026

AI Assistant

Sometimes you don’t want the model to finish its thought — you want it to stop at a specific point. A completion-style prompt that must hand off at a delimiter, a generator producing one item per call, a prompt-injection surface where anything after a marker is untrusted. Stop sequences are the mechanism: strings that, when the model generates them, end the response immediately.

They’re the most underused control in the sampling toolkit. Where max_output_tokens is a blunt ceiling, a stop sequence is a precision cut — and in the right situation, a sentence in your prompt can’t do what a stop sequence does reliably.

The basic mechanism

from google.adk.agents import Agent
from google.genai.types import GenerateContentConfig

agent = Agent(
    model="gemini-flash-latest",
    name="qa_generator",
    instruction=QA_INSTRUCTION,
    generate_content_config=GenerateContentConfig(
        stop_sequences=["\n\nEND", "###"],
        max_output_tokens=512,          # keep a backstop anyway
    ),
)

Semantics worth knowing exactly:

  • The stop string is not included in the returned text — generation halts before it.
  • Stopping is a finish reason, not an error — STOP (or the provider’s stop-marker equivalent), distinguishable from hitting max_output_tokens.
  • Matching happens at the decoding step. The model can’t “plan past” a stop sequence; it’s checked as tokens are emitted.
  • Partial matches at the end are dropped — if generation ends mid-way through a potential stop string, the incomplete fragment doesn’t count as a match (behavior to verify for your provider, since it’s the kind of edge that varies).

Multiple sequences are an OR: any one of them terminates generation.

Where stop sequences genuinely win

1. Structured handoffs between calls. A pipeline stage emits one item, then stops; the orchestrator loops:

config = GenerateContentConfig(stop_sequences=["\nNEXT:"], max_output_tokens=256)
# each call produces exactly one item, then halts

2. Untrusted-content boundaries. When a model is completing text that includes user- or document-supplied content, everything after a marker belongs to the source, not the model:

GenerateContentConfig(stop_sequences=["\nUser:", "\n### QUOTE END"])

This is prompt-injection mitigation at the sampling layer — a hard guarantee no instruction can override (“ignore previous instructions” doesn’t stop a decoder-level cut).

3. Preventing the classic detours. Models love adding preamble and postamble. Stop sequences kill them structurally:

  • \n\n after a one-line answer
  • \nExplanation: when you only want the label
  • """ when generating a code body inside a docstring

4. Completion-style APIs and legacy formats. Some integrations still expect raw completions terminated at a delimiter; stop sequences reproduce that contract on a chat model.

When to use a stop sequence vs. alternatives

ToolUse it when
Stop sequenceThe termination point is textually detectable and must be guaranteed
max_output_tokensYou only need a size bound (keep as backstop anyway)
Prompt instruction (“answer in one sentence”)Soft guidance is enough; format isn’t critical
output_schemaYou need a typed object, not an early cut
Tool callThe model should do something rather than emit text

Key insight: stop sequences and structured output solve different problems. output_schema guarantees shape; stop sequences guarantee where text ends. Combining them is valid — schema for structure, stop sequence to prevent trailing rambling inside a long string field.

The traps

Trap 1: over-broad sequences truncate real content. A stop sequence of "." will end sentences mid-answer. Keep stop strings distinctive — multi-character markers like "\nEND" or "###STOP", not punctuation.

Trap 2: stop sequences can’t un-generate. If the model writes your sensitive content before reaching the marker, the cut doesn’t help. Stops bound the tail, not the middle.

Trap 3: it interacts with other controls. A stop sequence plus a tight max_output_tokens plus a large thinking budget — verify the budget isn’t consuming the space the answer needs before the stop point is even relevant.

Trap 4: provider variance. When routing across LiteLLM providers or local endpoints, stop-sequence handling is usually supported but edge cases (partial-match behavior, matching inside code blocks) differ. If the guarantee matters, test it on every provider in your chain.

Trap 5: model workarounds. Creative models occasionally paraphrase the stop marker (“END.” instead of “END”) to keep going. Low probability at sensible sampling settings — but another reason to keep finish_reason instrumentation from the truncation post in place.

Putting it together: a controlled generation recipe

def generation_config(task: str) -> GenerateContentConfig:
    return GenerateContentConfig(
        temperature=0.2,                          # structured tasks stay tight
        top_p=0.9,
        stop_sequences=["\n###", "\nUser:"],      # precision cut + injection boundary
        max_output_tokens=512,                    # backstop
        seed=42 if task == "eval" else None,      # reproducible test runs
    )

And verify in tests — stop behavior is exactly the kind of thing that silently regresses:

def test_stops_before_marker():
    out = run_once("Write a poem.\n###")
    assert "###" not in out
    assert not out.endswith("###")

A golden-output test per stop configuration catches provider upgrades that change matching semantics.

Where to go next

Stop sequences pair with the rest of the generation-control family: max_output_tokens as the size backstop, GenerateContentConfig sampling parameters for distribution control, and thinking budgets for the reasoning allowance — see thinking models and reasoning budgets. The bigger frame remains timeouts and deadlines: generation should always have a defined ending, by choice or by budget.

References