Introduction
Welcome to the first lesson of our course on engineering agentic systems. Your goal is to build complex, production-grade agents, and the first step toward that is ensuring reliable communication with the Large Language Model (LLM) at the core. In production systems, predictability is paramount. Simply asking an LLM to "respond in JSON" and then parsing the resulting text is brittle and prone to failure. This leads to errors from malformed syntax, hallucinated data fields, or incorrect data types—issues that are unacceptable in the reliable, event-driven architectures you're accustomed to building.
In this lesson, you will learn how to enforce structured output at the source. We will move beyond simple prompting and explore the mechanisms of constrained decoding, a technique that guarantees an LLM's output will conform to a specified JSON schema. We will start from first principles, examining how grammars and state machines can guide the model's token generation process. We'll then translate this theory into practice, implementing structured output using Pydantic for schema definition with both proprietary APIs and open-source models.
The Challenge of Unstructured LLM Outputs
When an LLM generates free-form text, it's optimized for human readability, not machine parsing. A request for JSON might yield a valid object, but it might also be wrapped in a Markdown block, contain conversational filler text, or have subtle syntax errors.
{
"thought": "The user wants a summary. Here is the summary in JSON format.",
"summary": {
"title": "Meeting Notes",
"participants": ["Alice", "Bob"]
}
// Missing closing brace
An example of an incomplete and conversational LLM response.
Relying on regular expressions or custom parsing logic to handle these variations creates a fragile system. A 5-15% failure rate in parsing, as reported in some production environments, translates directly to failed tasks, increased costs from retries, and a poor user experience. To build robust agents, we need to eliminate this uncertainty.
The Principle of Constrained Decoding
The solution is not to "request" a format, but to "enforce" it. Constrained decoding (also known as guided generation) intervenes directly in the LLM's token generation loop. At each step, the model produces a probability distribution over its entire vocabulary for the next token. Constrained decoding acts as a filter on this distribution. Before the model samples the next token, we apply a "mask" to the logits (the raw, pre-softmax scores), effectively setting the probability of any grammatically invalid tokens to zero.

This process guarantees that every token generated is part of a valid sequence, making it impossible for the model to produce a syntactically incorrect output. The core challenge then becomes: how do we determine the set of valid tokens at each step? The answer lies in formal grammars.
From Schema to State Machine
To determine which tokens are valid at any given point, we need a formal definition of the desired output structure. A JSON schema provides this definition, but we need to convert it into a system that can guide the token-by-token generation process. The most common approach involves converting the schema into a regular expression, which can then be compiled into a Finite State Machine (FSM).

An FSM is a mathematical model of computation that exists in one of a finite number of states. Given a sequence of inputs (in our case, tokens), it transitions from state to state. For our purposes:
- We start in the FSM's initial state.
- Before generating a token, we ask the FSM: "From the current state, which tokens lead to a valid next state?"
- We mask the LLM's logits to allow only this set of valid tokens.
- The LLM samples a token from the allowed set.
- We update the FSM to its new state based on the token that was generated.
- Repeat until the model generates an end-of-sequence token and the FSM is in an accepting state.
For a deeper insight into this mechanism, the following video provides an excellent conceptual overview of the journey from regex to FSMs and how they are used to guide generation.
Structured Output from LLMs: Grammars, Regex, and State Machines
Watch this segment from the "Efficient NLP" channel for a clear explanation of how regular expressions are converted into FSMs and used to filter LLM token outputs.
Focus on the explanation of how the FSM tracks the generation process from state to state and how this is used to filter tokens at each step. Also, note the optimization discussed regarding pre-computation, which is possible because FSMs are memoryless.
While FSMs are powerful, they cannot easily handle arbitrarily nested structures, which are common in JSON (e.g., a list of objects, where each object can contain other lists). To handle full JSON grammar, including recursion, a more powerful model called a Context-Free Grammar (CFG) and its corresponding automaton, the Pushdown Automaton (PDA), is required. The principle is similar, but the PDA includes a stack to keep track of nesting levels.
For a first-principles understanding of these two approaches, please read the following section from the "Chaos and Order" blog.
This article section explains the core principles of both FSM-based and CFG-based constrained decoding, including the token masking mechanism at the heart of the process.
Please read the section titled Constrained Decoding Principle. Pay close attention to the distinction between the FSM-based approach, which is simpler but struggles with recursion, and the CFG-based approach, which handles full JSON grammar. The Python snippet demonstrating logit masking is a direct implementation of the core concept we've been discussing.
A Practical Path: From Pydantic to Regex
Building a full FSM or CFG compiler is a significant undertaking. However, understanding the first step—compiling a JSON schema to a regular expression—provides a solid foundation. The blog post "Pydantic to Regex" walks through this process from scratch. It demonstrates how to recursively build a single, comprehensive regex that validates an entire JSON object defined by a Pydantic model.
Pydantic to Regex: Compiling JSON Schemas for Structured Outputs
This article provides a step-by-step guide to building a compiler that converts a Pydantic model into a validating regular expression. This is the first major step in FSM-based constrained decoding.
First, read the high-level overview of the process: JSON Schema to FSM. Then, focus on the "Processing our JSON Schema" and the subsequent code block. The author first builds a regex manually, then automates it with a recursive Python function. Study the complete implementation of the pydantic_to_regex function to understand how it handles primitives, nested objects, arrays, and other JSON Schema constructs.
Implementing Structured Output in Practice
With the theory established, let's turn to implementation. You don't need to build the full constraint mechanism yourself, as both proprietary APIs and open-source libraries provide robust solutions.
Using API-Native Methods (e.g., OpenAI)
Major LLM providers like OpenAI have integrated structured output capabilities directly into their APIs. They handle the complexities of constrained decoding on their backend. In Python, the most common and type-safe way to define the desired schema is with Pydantic.
Pydantic is a data validation library that uses Python type hints. You define a class that inherits from BaseModel, and Pydantic can automatically generate a corresponding JSON schema. This Pydantic model can then be passed directly to the API client.
The following video from Microsoft Reactor is a comprehensive tutorial on using Pydantic with the OpenAI API to achieve structured outputs. It covers defining schemas, adding descriptions to guide the model, using enums for constrained choices, and handling nested data structures.
Python + AI: Structured outputs
This tutorial provides a practical, code-first demonstration of generating structured outputs with Python, Pydantic, and the OpenAI API.
Watch the segment on defining schemas using Pydantic's BaseModel. Next, see how to integrate this with the client and access the parsed object. Learn how to add descriptions to fields and use enums to constrain values by watching from this point. The speaker also demonstrates a great debugging trick by inspecting the raw JSON schema sent to the API. Finally, observe how to create nested structures by embedding one BaseModel within another. You can also review how to define optional fields.
Using Open-Source Libraries
When working with local models via Ollama or other open-source inference engines, you need a library that implements constrained decoding on the client side. Outlines is a popular library that does exactly this, implementing the FSM-based approach we discussed. It takes a Pydantic model (or a raw regex), compiles it, and hooks into the generation loop of models from libraries like transformers.
The "Efficient NLP" video we saw earlier has a great segment demonstrating Outlines.
Structured Output from LLMs: Grammars, Regex, and State Machines
This segment demonstrates how to use the Outlines library to enforce structured output on open-source models.
Watch from this timestamp to see how Outlines can generate JSON from a Pydantic schema and also enforce a raw regular expression. The narrator correctly points out that even JSON schema validation is converted to a regular expression under the hood in Outlines.
Production Considerations
While constrained decoding guarantees syntactic validity, it doesn't guarantee semantic correctness. The model is still responsible for filling the schema with meaningful content. To get the best results in a production environment, careful schema design and monitoring are essential.
This resource provides a set of practical guidelines, failure cases, and a pre-production checklist for implementing structured output reliably.
Read the sections on Schema design principles and Performance implications to understand the trade-offs. Then, review the Failure cases and recovery for real-world examples of problems and their solutions. Finally, go through the comprehensive Checklist to internalize the key considerations for building a production-grade system.
Conclusion
In this lesson, we established the critical importance of structured output for building reliable agentic systems. You learned that the most robust method is constrained decoding, which forces an LLM to adhere to a specific grammar by masking invalid tokens at each step of the generation process.
Here are the key takeaways:
- Problem: Free-form LLM outputs are unreliable for programmatic use, leading to parsing failures and unpredictable behavior.
- Solution: Constrained decoding guarantees syntactically valid output by manipulating the model's logits based on a formal grammar.
- Mechanism: The process typically involves converting a JSON schema (often defined via a Pydantic model) into a Regular Expression or Context-Free Grammar, which is then compiled into a Finite State Machine (FSM) or Pushdown Automaton (PDA) to guide token generation.
- Implementation: You can leverage this technology through built-in API features (like OpenAI's structured output) or with open-source libraries like
Outlinesfor local models. - Best Practices: Effective schema design—using clear descriptions, enums, and appropriate constraints—is crucial for both performance and semantic accuracy.
You now have a firm grasp of the principles and practices for getting reliable, structured data from an LLM. This is the first building block of our agent. In the next lesson, we will build directly on this foundation to implement function calling, where we'll use these structured schemas to define tools that an agent can invoke.