How to master LLM outputs for reliable AI systems
Published: 2025-10-14
URL: https://www.decodingai.com/p/llm-structured-outputs-the-only-way
Welcome to the AI Agents Foundations series—a 9-part journey from Python developer to AI Engineer. Made by busy people. For busy people. Everyone’s talking about AI agents. But what actually is an agent?
When do we need them? How do they plan and use tools? How do we pick the correct AI tools and agentic architecture? …and most importantly, where do we even start? To answer all these questions (and more!), We’ve started a 9-article straight-to-the-point series to build the skills and mental models to ship real AI agents in production. We will write everything from scratch, jumping directly into the building blocks that will teach you “how to fish”. What’s ahead: Workflows vs. Agents Context Engineering Structured Outputs ← You are here The 5 Workflow Patterns Tool Calling From Scratch Planning: ReAct & Plan-and-Execute ReAct Agents From Scratch AI Agent’s Memory Multimodal Agents By the end, you’ll have a deep understanding of how to design agents that think, plan, and execute—and most importantly, how to integrate them in your AI apps without being overly reliant on any AI framework.
Let’s get started. Opik: Open-Source LLMOps Platform (Sponsored) This AI Agents Foundations series is brought to you by Opik - the LLMOps open-source platform that we keep returning to in all our open-source courses and real-world AI products. Why? Because it makes our AI products actually work in production. Opik is the observability platform for AI engineers who need answers, not dashboards: See every decision - Complete traces of LLM calls with costs and latency breakdown at each reasoning step Catch issues fast - Automated AI Evals plugged into your production traces Optimize your system - Run experiments using LLM judges, compare results and pick your best configuration Stop manual prompt engineering - Agent Optimizer handles prompt optimization automatically Opik is fully open-source and works with custom code or any agent framework.
You can also use the managed version for free (w/ 25K spans/month on their generous free tier). Try Opik for free Structured Outputs In a recent project I am working on, our production AI system crashed right before an important demo. Why? Because we were not using structured outputs consistently across our Large Language Model (LLM) workflows. Our staging environment had been working fine with simple regex parsing of LLM responses, but when we deployed to production, everything fell apart. Our regex patterns failed to match slightly different response formats, data types were inconsistent, and downstream processes couldn’t handle the unpredictable data, causing cascading failures.
When demo day arrived, our system was completely unusable. The problem was clear: we had been relying on fragile string parsing, hoping the LLM would always respond in the exact same format. But in production, especially with AI systems, users will always enter inputs you never expect. Without structured outputs, we had no data validation, no type checking, and no real control over how the output should look. Just like lock files ensure consistent dependencies, structured outputs ensure consistent AI data contracts by defining the expected structure for LLM responses.
In our previous article from the AI Agents Foundations series, we explored the difference between workflows and agents. Now, we will tackle a fundamental challenge: getting reliable information out of an LLM. To understand exactly what happens, we will first write everything from scratch and then move to using popular LLM APIs such as Gemini’s GenAI SDK: From scratch using JSON From scratch using Pydantic (We love Pydantic!) Using the Gemini SDK and Pydantic Understanding why structured outputs are important Before we start coding, it is important to understand why structured outputs are foundational to building reliable AI applications.
When an LLM returns a free-form string, you face the messy task of parsing it. This often involves fragile regular expressions or string-splitting logic that can easily break if the model outputs change slightly [1], [2]. Structured outputs solve this by forcing the model’s response into a predictable format like JSON or Pydantic.
This approach offers several key benefits. First, structured outputs are easy to parse and manipulate programmatically. Instead of wrestling with raw text, you work with clean Python objects, making your code more predictable and easier to debug. Using libraries like Pydantic adds a layer of data and type validation [3], [4]. If the LLM returns a string where an integer is expected, your application raises a clear validation error immediately, preventing bad data from propagating. Image 1: The benefits of structured outputs from LLMs, acting as a bridge between LLM (Software 3.0) and Python (Software 1.0) for downstream processing.
Furthermore, structured outputs are easier to orchestrate between steps in a workflow. When you know what information you have available, it is much simpler to pass it to the next LLM call or a downstream system like a database or API [5], [6].
This control also reduces costs. By ensuring the LLM generates only the necessary data without useless artifacts (e.g., “Here is the output you requested...”), you reduce the number of output tokens. 💡 Quick Tip: You can easily compute the costs of running your workflows or agent by plugging in an LLMOps open-source tool such as Opik. Ultimately, structured outputs create a formal contract between the LLM (Software 3.0) and your application code (Software 1.0). They are the standard method for modeling domain objects in AI engineering, connecting the probabilistic nature of LLMs with deterministic code.
Implementing Structured Outputs From Scratch Using JSON To understand how modern LLM APIs such as OpenAI and Gemini work under the hood, we will first implement structured outputs from scratch. Our goal is to prompt a model to return a JSON object and then parse it into a Python dictionary. We will use an “LLM-as-judge” evaluation as our example, where we ask an LLM to compare a generated text against a ground-truth document and score it based on predefined criteria.
This is a great use case, as it requires extracting specific, structured information from a large context. First, we define our sample documents for the evaluation. These will serve as the input for our LLM judge: GENERATED_DOCUMENT = “”“
Q3 2023 Financial Performance Analysis
The Q3 earnings report shows a 20% increase in revenue and a 15% growth in user engagement, beating market expectations. These impressive results reflect our successful product strategy and strong market positioning. Our core business segments demonstrated remarkable resilience, with digital services leading the growth at 25% year-over-year.
The expansion into new markets has proven particularly successful, contributing to 30% of the total revenue increase. Customer acquisition costs decreased by 10% while retention rates improved to 92%, marking our best performance to date.
These metrics, combined with our healthy cash flow position, provide a strong foundation for continued growth into Q4 and beyond. “”“ GROUNDTRUTHDOCUMENT = “”“
Q3 2023 Financial Performance Analysis
The Q3 earnings report shows a 18% increase in revenue and a 15% growth in user engagement, slightly below market expectations. These results reflect our product strategy adjustments and competitive market positioning challenges. Our core business segments showed mixed performance, with digital services growing at 22% year-over-year.
The expansion into new markets has been challenging, contributing to only 15% of the total revenue increase. Customer acquisition costs increased by 5% while retention rates remained at 88%, indicating areas for improvement.
These metrics, combined with our cash flow position, suggest we need strategic adjustments for Q4 growth. “”“Next, we craft a prompt that instructs the LLM to evaluate the generated document against the ground truth and format the output as JSON. We provide a clear example of the desired structure and use XML tags like <document> to separate inputs from instructions.
This is an effective prompt engineering technique for improving clarity and guiding the model’s output [7], [8]. The key is to be explicit about the format, keys, and value types you expect: prompt = f”“” You are an expert evaluator. Compare the generated document with the ground truth document and provide a score for each criterion.
The output must be a single, valid JSON object with the following structure: {{ “scores”: [ {{ “criterion”: “revenueforecast”, “score”: 0 or 1, “reason”: “Your reasoning here.” }}, {{ “criterion”: “usergrowth”, “score”: 0 or 1, “reason”: “Your reasoning here.” }}, {{ “criterion”: “facts”, “score”: 0 or 1, “reason”: “Your reasoning here.” }} ] }} Here are the documents: <generateddocument> {GENERATEDDOCUMENT} </generateddocument> <groundtruthdocument> {GROUNDTRUTHDOCUMENT} </groundtruth_document> “”“We send the prompt to the model and inspect the raw response.
As expected, the model returns a JSON object, wrapped in Markdown ```json code blocks: from google import genai client = genai.Client() response = client.models.generate_content(model=”gemini-2.5-flash”, contents=prompt)It outputs: