A Finite State Machine (FSM) is an abstract mathematical model of computation consisting of a finite number of states, transitions between those states, and actions. In the context of structured output formatting, an FSM acts as a hard constraint mechanism during guided decoding, where each state represents a specific point in a target schema (e.g., inside a JSON string, expecting a comma, or closing an object). The model's tokenizer is mapped to the FSM's alphabet, and the machine physically prevents the generation of any token that does not correspond to a valid transition from the current state, guaranteeing syntactically perfect output.
Glossary
Finite State Machine (FSM)

What is Finite State Machine (FSM)?
A finite state machine is an abstract computational model used in guided generation to track the current valid state of an output sequence and determine the set of permissible next tokens.
Unlike probabilistic methods like logit bias or post-hoc schema validation, an FSM provides a strict mathematical guarantee of format adherence by manipulating the transition probabilities at the sampler level. Libraries such as Outlines compile a Context-Free Grammar (CFG) or a regular expression into an Abstract Syntax Tree (AST) and then into an index-based FSM. During each decoding step, the FSM evaluates the current state and returns a mask that sets the probability of all invalid tokens to zero, a process known as token masking. This ensures that the final output is a valid string in the formal language defined by the schema, eliminating syntax errors entirely.
Core Characteristics of FSM-Guided Generation
Finite State Machines provide the mathematical backbone for guaranteeing syntactically valid output from language models by dynamically constraining the token sampling process to only permissible next steps.
Deterministic State Tracking
An FSM tracks the exact position within a formal grammar during generation. Unlike probabilistic prompting, the FSM maintains a current state that represents what has been generated so far. This state determines the set of valid next tokens, physically preventing the model from producing syntactically invalid sequences. For example, after generating an opening bracket [, the FSM transitions to a state where only array elements or a closing bracket ] are permissible.
Token-Level Masking
At each decoding step, the FSM computes a valid token mask by evaluating all possible tokens against the current state's transition rules. Tokens that would violate the schema have their logit probabilities set to negative infinity before the softmax operation. This is fundamentally different from post-hoc validation because it guarantees validity at the physical sampling layer, not just the application layer. The model's probability distribution is surgically altered to zero out invalid continuations.
Guaranteed Schema Compliance
FSM-guided generation provides a mathematical guarantee that the output will conform to a predefined schema or grammar. This eliminates entire categories of errors:
- Unclosed brackets or braces in JSON
- Invalid data types in required fields
- Missing required keys in structured objects
- Malformed string escapes in complex outputs The guarantee is absolute because the model is physically incapable of selecting tokens that would break the grammar.
Index-Based Generation
Modern FSM implementations like the Outlines library use index-based generation rather than full grammar parsing at each step. The FSM pre-computes a compact index mapping each state to its valid token set. During generation, the current state index is used for an O(1) lookup of the valid token mask. This optimization reduces the computational overhead of guided generation to near-negligible levels, making it suitable for production latency budgets.
Grammar Formalisms
FSM-guided generation supports multiple grammar definition formats:
- GBNF Grammar: Used by llama.cpp for defining syntactical rules in a Backus-Naur Form variant
- JSON Schema: Automatically compiled into an FSM that enforces structural constraints
- Context-Free Grammars (CFG): Recursive production rules that define all valid strings in a formal language
- Regular Expressions: Compiled into deterministic finite automata for pattern-constrained generation The FSM compiler converts these declarative schemas into executable state machines.
Performance Characteristics
FSM-guided generation introduces minimal latency overhead while providing absolute format guarantees:
- Token mask computation: Typically < 1ms per step with pre-compiled indexes
- Memory overhead: Compact state representations require minimal additional VRAM
- Throughput impact: Negligible compared to unconstrained generation when using optimized FSM compilers
- Batching compatibility: Valid token masks can be computed independently for each sequence in a batch The deterministic nature also enables caching of state transitions for repeated schema patterns.
Frequently Asked Questions
Explore the core concepts behind using finite state machines to enforce strict output schemas and eliminate syntax errors in language model generation.
A Finite State Machine (FSM) is an abstract computational model used in guided decoding to track the current valid state of an output sequence and determine the set of permissible next tokens. In structured generation, the FSM defines a formal grammar—such as a JSON Schema or a Context-Free Grammar (CFG)—that the model's output must strictly adhere to. As the language model generates text token by token, the FSM transitions between states (e.g., from 'Object Open' to 'Key' to 'Value'). At each step, it computes a token mask that sets the probability of all syntactically invalid tokens to zero, physically preventing the model from producing malformed JSON or drifting out of schema. This guarantees that the final output is a syntactically valid, parseable data structure without requiring post-hoc output parsing or error correction.
Practical Applications in AI Systems
Finite State Machines provide a rigorous, deterministic backbone for constraining language model outputs, ensuring generated sequences strictly adhere to predefined schemas, grammars, or interaction protocols.
JSON Schema Enforcement
FSMs are the core mechanism for guaranteeing syntactically valid JSON output. The FSM tracks the current parsing context (e.g., inside a string, expecting a comma, or closing an object) and masks any token that would violate the JSON specification.
- State Transitions: Moving from
KeytoValuetoCommastates based on generated tokens. - Contextual Awareness: The FSM knows if an array is open, preventing invalid primitive tokens.
- Library Integration: Frameworks like
Outlinesandllama.cppcompile JSON Schema directly into an FSM for guided decoding.
Tool-Use Protocol Validation
In function calling, the model must output a specific structure (e.g., {"name": "...", "arguments": {...}}). An FSM enforces this exact sequence, preventing malformed tool calls that would crash an agentic loop.
- Token-Level Control: The FSM forces the opening
{, the"name"key, and the function name string. - Argument Integrity: It ensures the
argumentsvalue is a valid JSON object, not a hallucinated string. - Stop Sequence Enforcement: The FSM can mandate a specific closing
}to signal the end of the tool call.
Grammar-Constrained Generation
For domain-specific languages or formal grammars (e.g., GBNF), an FSM compiled from a Context-Free Grammar (CFG) restricts generation to only valid syntactical paths. This is critical for generating executable code or mathematical proofs.
- Lexer State Tracking: The FSM mirrors a lexer, ensuring keywords and identifiers are correctly formed.
- Recursive Rule Expansion: It manages the stack for recursive grammar rules, preventing infinite loops.
- AST Guarantee: The output is guaranteed to parse into a valid Abstract Syntax Tree.
ReAct Agent Loop Control
The ReAct (Reasoning + Acting) paradigm requires a strict interleaving of Thought, Action, and Observation tokens. An FSM governs this sequential protocol, preventing the model from generating an Action before a Thought or skipping the Observation step.
- Phase Locking: The FSM transitions through a fixed cycle:
Thought->Action->Observation. - Token Forcing: It forces the generation of the next required keyword (e.g.,
"Action:") at the correct state. - Loop Termination: The FSM defines valid terminal states (e.g.,
Final Answer) to end the agent's execution.
Slot Filling for Conversational AI
In task-oriented dialogue, an FSM tracks which slots in a semantic frame have been filled. It constrains the model's output to only ask for missing required information, ensuring a deterministic, efficient information-gathering flow.
- State as Frame: Each state represents the current fill-status of slots (e.g.,
date,time,location). - Conditional Prompting: The FSM transitions to a prompt state that specifically asks for the next missing slot.
- Confirmation State: It enforces a final confirmation step before executing a transaction.
Multi-Modal Output Coordination
For systems generating interleaved text and structured actions (like image generation commands), an FSM coordinates the output sequence. It ensures a text description is completed before switching to a state that generates a structured API call for an image model.
- Mode Switching: States define whether the next token is free-form text or part of a structured command.
- Resource Integrity: The FSM validates that generated URLs or file paths conform to a required pattern.
- Sequence Guarantee: It enforces a strict order:
Caption->Image_Generation_Command->Metadata_Block.
FSM vs. Other Structured Output Methods
A technical comparison of Finite State Machine-based generation against other common structured output enforcement techniques for large language models.
| Feature | Finite State Machine (FSM) | JSON Schema (Post-hoc) | Context-Free Grammar (CFG) |
|---|---|---|---|
Enforcement Timing | During token generation | After full generation | During token generation |
Guarantees Valid Output | |||
Handles Recursive Structures | |||
Computational Overhead | Low (O(1) per step) | Negligible | Moderate (O(n) per step) |
Schema Flexibility | Rigid (state graph) | Highly flexible | Flexible (production rules) |
Typical Failure Mode | Trapped in state | Schema validation error | Stack overflow |
Retry Penalty on Failure | 0 tokens wasted | Full generation wasted | 0 tokens wasted |
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
Finite State Machines provide the theoretical backbone for deterministic structured output. Explore the key concepts, libraries, and techniques that leverage FSMs to guarantee schema-compliant generation from language models.
Guided Decoding
The practical application of Finite State Machines during token generation. It constrains the model's output distribution at each step, masking invalid tokens to ensure the final sequence strictly adheres to a predefined JSON Schema or Context-Free Grammar. This eliminates the need for post-hoc regex fixing.
Outlines Library
An open-source Python library that uses index-based guided generation. It compiles a regex or JSON schema into an FSM and uses it to index valid logits during decoding. This guarantees output format adherence without modifying the underlying model weights, ensuring robust Deterministic Output.
GBNF Grammar
A formal grammar notation used by frameworks like llama.cpp to define syntactical rules for constrained decoding. It allows developers to specify an FSM directly as a set of production rules, forcing the model to generate text that strictly conforms to the defined structure, such as a specific JSON format.
Token Masking
The low-level mechanism that enforces FSM constraints. At each decoding step, the logit bias for all invalid tokens is set to negative infinity, setting their probability to zero. This physically prevents the model from sampling a token that would violate the Schema Validation rules.
JSON Schema
A vocabulary for annotating and validating JSON documents. It defines the structure, required properties, and data types for structured output. When paired with an FSM, a JSON Schema provides the exact constraints needed for Guided Decoding to generate valid, parseable JSON objects.
Instructor Library
A Python library that patches language model clients to simplify Structured Data Extraction. It uses Pydantic models as the target schema and leverages techniques like Function Calling or Logit Bias under the hood to ensure the model's output parses directly into the specified data structure.

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