A stop sequence is a specific string of text, such as ### or </output>, designated as a termination signal during model inference. When the language model generates this exact sequence, the decoding loop breaks instantly, preventing the model from continuing to produce extraneous or rambling text beyond the intended structural endpoint.
Glossary
Stop Sequence

What is a Stop Sequence?
A stop sequence is a predefined string of characters that signals a language model to immediately halt the token generation process, ensuring the output terminates cleanly at a structural boundary.
This mechanism is critical for structured output formatting and API integrations, where a response must end precisely after a JSON object or a specific section. By defining stop sequences, developers enforce syntactic boundaries without relying on post-processing truncation, ensuring the raw output is immediately parseable and free of trailing artifacts.
Key Characteristics of Stop Sequences
Stop sequences are predefined character strings that act as a hard boundary for language model generation, ensuring outputs terminate cleanly at structural or semantic endpoints rather than rambling into irrelevance.
Structural Boundary Enforcement
Stop sequences serve as explicit termination signals that prevent models from generating beyond a defined structural boundary. When the model emits the stop token, generation halts immediately.
- Common stop sequences include
\n\n,###,</output>, or custom delimiters - Essential for JSON mode where a closing brace
}or bracket]must be the final character - Prevents the model from appending conversational filler like 'I hope this helps!' after structured data
- Works in conjunction with token masking to physically block continuation tokens
Token-Level Halting Mechanism
Stop sequences operate at the token level, not the character level. The model's tokenizer must recognize the stop sequence as a distinct token or token sequence to trigger termination.
- A stop sequence like
\n\nmay be a single token or two consecutive newline tokens depending on the tokenizer - Logit bias can be applied to suppress tokens that would extend generation beyond the stop point
- In guided decoding, the finite state machine transitions to a terminal state when the stop sequence is emitted
- Mismatched tokenization can cause stop sequences to fail if the model never generates the exact token pattern
Multi-Sequence Stop Conditions
Production systems typically define multiple stop sequences to handle different termination scenarios within a single generation call.
- A JSON generation might stop on
}for normal completion,\n\nfor error truncation, and a custom[ERROR]token - Stop sequences are evaluated incrementally as each token is generated, not retroactively on the full output
- Frameworks like Outlines and LMQL allow defining stop conditions as part of the grammar specification
- Multiple stop sequences prevent the model from getting stuck in repetitive loops by providing multiple escape paths
Chain-of-Thought Termination
In chain-of-thought structuring, stop sequences delineate the boundary between reasoning traces and final answers, ensuring the model doesn't blend the two.
- A stop sequence like
[ANSWER]signals the transition from internal reasoning to user-facing output - The ReAct agent format uses
Observation:as both a structural delimiter and an implicit stop for the previous section - Without proper stop sequences, reasoning traces can leak into final outputs, creating confusing responses
- Stop sequences enable structured data extraction by cleanly separating the model's scratchpad from its structured payload
Infinite Generation Prevention
Stop sequences act as a critical safety mechanism against runaway generation that consumes compute resources and produces garbage output.
- Combined with a max_tokens parameter as a hard upper bound for defense-in-depth
- Models without stop sequences can enter repetitive loops, generating the same phrase indefinitely
- Grammar-constrained generation uses stop sequences as terminal symbols in the formal grammar definition
- In API deployments, stop sequences prevent billing overages from excessively long generations
Schema-Aware Termination
When generating structured outputs against a JSON Schema, stop sequences must align with the schema's expected closing delimiters to produce valid, parseable results.
- A schema defining an array of objects expects
]as the natural stop point after the final element - Schema validation fails if generation stops prematurely before required fields are emitted
- Pydantic and Instructor libraries implicitly manage stop sequences based on the target model's structure
- Schema drift can occur if stop sequences are hardcoded while the expected output format evolves
Frequently Asked Questions
Clear answers to common questions about using stop sequences to control language model generation and ensure clean, structurally sound outputs.
A stop sequence is a predefined string of characters that signals a language model to immediately halt the token generation process. When the model's output stream matches the exact stop sequence, the inference engine terminates generation, preventing the model from producing extraneous or rambling text beyond a desired structural boundary. This mechanism is implemented at the decoding layer, where the generated text is continuously scanned for the presence of the stop token. Common stop sequences include ###, <|endoftext|>, </s>, or custom delimiters like [END]. By defining a stop sequence, developers enforce a clean termination point, which is critical for structured output formatting tasks where a precise schema boundary must be respected.
Enabling Efficiency, Speed & Accuracy
Intelligent Analysis, Decision & Execution
We build AI systems for teams that need search across company data, workflow automation across tools, or AI features inside products and internal software.
Talk to Us
Search across company data
Give teams answers from docs, tickets, runbooks, and product data with sources and permissions.
Useful when people spend too long searching or get different answers from different systems.

Automate internal workflows
Use AI to route work, draft outputs, trigger actions, and keep approvals and logs in place.
Useful when repetitive work moves across multiple tools and teams.

Add AI to products and internal tools
Build assistants, guided actions, or decision support into the software your team or customers already use.
Useful when AI needs to be part of the product, not a separate tool.
Related Terms
Master the full stack of techniques for constraining language model generation to valid, parseable schemas.
JSON Schema
A vocabulary for annotating and validating JSON documents. Defines the structure, data types, and constraints for structured output generation. Use it to specify required fields, numeric ranges, and enum values, ensuring the model's output is machine-readable and strictly typed.
Guided Decoding
A technique that constrains token generation to adhere to a predefined grammar or schema. Unlike post-processing, guided decoding prevents invalid tokens from being sampled, guaranteeing syntactically valid output at every step of the generation process.
Grammar-Constrained Generation
Forces model output to conform to a formal grammar, such as a Context-Free Grammar (CFG). This method uses a Finite State Machine (FSM) to track the current valid state and mask invalid next tokens, ensuring 100% schema compliance.
Function Calling
A model capability to output structured JSON containing function names and arguments. Enables deterministic integration with external APIs and tools by defining a schema for tool inputs, allowing the model to select the correct function and populate parameters accurately.
Output Parsing
The post-processing step of converting raw string output into structured data. Libraries like Pydantic and Instructor validate and coerce model responses into typed objects. Essential when guided decoding is unavailable, but requires robust error handling for malformed outputs.
Token Masking
A low-level technique that dynamically sets the probability of invalid tokens to zero during decoding. By manipulating the logit bias for tokens that would break the schema, this method physically prevents the model from generating out-of-schema text at the hardware level.

About the author
Prasad Kumkar
CEO & MD, Inference Systems
Prasad Kumkar is the CEO & MD of Inference Systems and writes about AI systems architecture, LLM infrastructure, model serving, evaluation, and production deployment. Over 5+ years, he has worked across computer vision models, L5 autonomous vehicle systems, and LLM research, with a focus on taking complex AI ideas into real-world engineering systems.
His work and writing cover AI systems, large language models, AI agents, multimodal systems, autonomous systems, inference optimization, RAG, evaluation, and production AI engineering.
Partnered with leading AI, data, and software stack.
How We Work
Custom AI workflows for your Business
One-fit-all AI don't work for modern businesses. At Inferensys, we aim to understand your business & custom requirements; which we use to define most efficient agentic workflows, the data, and the tools for your business.
01
Review the use case
We understand the task, the users, and where AI can actually help.
Read more02
Pick the right approach
We define what needs search, automation, or product integration.
Read more03
Build the first useful version
We implement the part that proves the value first.
Read more04
Improve from there
We add the checks and visibility needed to keep it useful.
Read moreThe first call is a practical review of your use case and the right next step.
Talk to Us