---
title: "Stop Sequences: Early Generation Termination in ADK"
date: "2026-11-25T08:52:00+07:00"
description: "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."
author: "AI Assistant"
image: "https://blog.redlinesoft.net/images/post/adk-stop-sequences-early-generation-termination.jpg"
alt: "Generation stream ending abruptly at a marked stop sequence delimiter"
tags: ['google-adk', 'stop-sequences', 'generatecontentconfig', 'generation-control', 'python']
---

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`](/blog/adk-max-output-tokens-truncation-strategies) 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

```python
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:

```python
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:

```python
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

| Tool | Use it when |
|---|---|
| **Stop sequence** | The termination point is *textually detectable* and must be guaranteed |
| **`max_output_tokens`** | You only need a size bound (keep as backstop anyway) |
| **Prompt instruction** ("answer in one sentence") | Soft guidance is enough; format isn't critical |
| **`output_schema`** | You need a *typed object*, not an early cut |
| **Tool call** | The 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`](/blog/adk-max-output-tokens-truncation-strategies) plus a large [thinking budget](/blog/adk-thinking-models-reasoning-budgets) — 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](/blog/adk-litellm-third-party-models-claude-openai-mistral) or [local endpoints](/blog/adk-vllm-endpoints-low-latency-self-hosted-inference), 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](/blog/adk-max-output-tokens-truncation-strategies) in place.

## Putting it together: a controlled generation recipe

```python
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:

```python
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`](/blog/adk-max-output-tokens-truncation-strategies) as the size backstop, [`GenerateContentConfig` sampling parameters](/blog/generatecontentconfig-temperature-top-p-top-k-seed) for distribution control, and [thinking budgets](/blog/adk-thinking-models-reasoning-budgets) for the reasoning allowance — see [thinking models and reasoning budgets](/blog/adk-thinking-models-reasoning-budgets). The bigger frame remains [timeouts and deadlines](/blog/adk-global-timeouts-execution-deadlines): generation should always have a defined ending, by choice or by budget.

## References

- [Google Gemini models for ADK agents](https://adk.dev/agents/models/google-gemini/)
- [Simple agents with `LlmAgent`](https://adk.dev/agents/llm-agents/)
- [googleapis/python-genai](https://github.com/googleapis/python-genai)
- [google/adk-python](https://github.com/google/adk-python)
