With this introductory guide to practical constraint decoding, you’ll no longer need to beg your model to “output valid JSON without including any markdown.”
<!– –>

# Introduction
Practical constraint decoding, also known as structured generation or guided decoding, encompasses the engineering strategies to force a large language model (LLM) to generate text outputs that strictly abide by a specified data schema, grammar, or regular expression (regex) at the token selection stage.
With this introductory guide to practical constraint decoding, you’ll no longer need to beg your model to “output valid JSON without including any markdown.” Constraint decoding makes it mathematically impossible for the LLM to deliver anything outside the defined constraints.
# How Does Practical Constraint Decoding Work?
While the typical LLM generation process works as an “act of faith” where you pass a prompt and hope for a usable response, practical constraint decoding takes a subtly distinct approach. It treats the prompt and text generation as a single, interleaved program. This makes it possible to lock down characters key to maintaining a required syntax while allowing the model to “fill in the blanks” in between.
When an LLM outputs the next token, it initially produces a vector of raw scores, or logits, one for every possible token in the vocabulary. This typically entails thousands of possible options to choose from.
But with practical constraint decoding, something happens earlier, before inference starts: a finite state machine is built that compiles the target constraint, for instance through a Pydantic model in Python. At each inference step, the state machine evaluates the current state and provides a list of allowed next tokens. This “whitelist” masks the LLM’s raw logits vector, setting the logit for any token outside the list to negative infinity (-inf in Python).
After masking, the model runs its softmax normalization and sampling as usual (using parameters like temperature, top-p, or top-k) on the surviving tokens to select and generate the most probable one.
Applying this process to a vocabulary of thousands of tokens might seem slow, but modern Python libraries pre-compile the static vocabulary before you even type your prompt. The state machine never needs to scan the entire vocabulary, so latency overhead stays minimal.
The current gold standard for implementing practical constraint decoding is the outlines library. It lets you define and pass Pydantic models, JSON schemas, or regex directly to a wrapped version of a pre-trained model, constraining its output freedom.
# Example
Let’s walk through an example. First, install outlines:
pip install outlines[transformers]
Now onto the code:
from pydantic import BaseModel
import outlines
from transformers import AutoTokenizer, AutoModelForCausalLM
class UserProfile(BaseModel):
name: str
age: int
is_active: bool
model_name = "TinyLlama/TinyLlama-1.1B-Chat-v1.0"
llm = AutoModelForCausalLM.from_pretrained(model_name)
tokenizer = AutoTokenizer.from_pretrained(model_name)
model = outlines.from_transformers(llm, tokenizer)
result = model("Extract the user: John is a 34 year old pilot.", UserProfile)
print(result)
Output:
{"name": "John", "age": 34, "is_active": true}
This example shows how to use outlines to wrap a pre-trained model and its tokenizer, constraining it to output JSON objects matching the custom class UserProfile (inheriting Pydantic’s BaseModel).
# Wrapping Up
Practical constraint decoding comes with a series of trade-offs. Here are some of them.
Strengths:
- If used correctly, it provides a 100% guarantee of correct syntax, eliminating the need for parsing logic in your code.
- It saves tokens in your prompts by removing the need for few-shot examples showing the model what a correct JSON object looks like.
- It helps democratize small models — a “tiny” 1B-parameter model that would otherwise struggle with JSON generation becomes a reliable data constructor.
Limitations:
- If the LLM needs to say it cannot answer, but the schema forces an integer output, it will do so — making it no longer honest in edge cases.
- On the first run of a Pydantic schema against an LLM, you may experience a freeze of a few seconds while the finite state machine builds, making the first run noticeably slower (subsequent runs are smooth).
This article introduces practical constraint decoding, explaining why it is necessary in certain LLM-driven situations, how it works, and what the most widely adopted solution is: the outlines library. An example of its use is provided.
Iván Palomares Carrascosa is a leader, writer, speaker, and adviser in AI, machine learning, deep learning, and LLMs. He trains and guides others in harnessing AI in the real world.

Get the FREE ebook ‘KDnuggets Artificial Intelligence Pocket Dictionary’ along with the leading newsletter on Data Science, Machine Learning, AI & Analytics straight to your inbox.
By subscribing you accept KDnuggets Privacy Policy

