1. Home
  2. Blog
  3. Artificial Intelligence

Artificial Intelligence

LLM Structured Output Explained: Getting Reliable JSON From AI Models

AI features often need data, not prose: an invoice total, a category, a list of fields. Structured output gets models to return machine-readable JSON. We ran six realistic model responses through a validator to show how output breaks and how to catch it.

10 min read
LLM structured output explained: getting reliable JSON from AI models

Key takeaways

  • Structured output means asking a model for data in a defined format, usually JSON matching a schema.
  • Prompting alone is unreliable. In our test, 4 of 6 realistic responses failed validation on first parse.
  • Provider features that constrain generation to a schema greatly reduce format errors where available.
  • Always validate in your own code, and add semantic checks: valid JSON can still contain wrong values.

An app asks a model to read an invoice and return the number, date, total and currency. Most of the time it works. Then one response arrives wrapped in a Markdown code block, another adds “Let me know if you need more!”, and a third writes the date as 10/11/2026. The code that parses the reply crashes, or worse, stores the wrong date. Structured output techniques exist to make AI responses as dependable as an API.

We did not call a live model for this article. Instead we wrote six responses that imitate common real-world failures and validated them with Pydantic 2.14 in Python 3.13. The validation results below come from that run.

What is structured output?

Structured output is any approach that makes a large language model return data in a fixed, machine-readable shape instead of free text, so code can use it directly. JSON is the usual format, described by a JSON Schema: which fields exist, their types, which are required and which values are allowed. Typical uses include extraction from documents, classification, form filling, routing requests and calling tools or functions.

Levels of enforcement

Approach How it works Reliability
Prompt only “Reply in JSON with these fields…” Lowest; format drifts
JSON mode Provider guarantees valid JSON syntax Valid JSON, but any shape
Schema-constrained output / tool calling Provider constrains generation to your schema Highest for format
Your own validation Parse and validate every response in your code Always required

The last row is not optional at any level. Provider features change, models are swapped, and no format guarantee covers whether the values are true.

Defining the schema

from typing import Literal
from pydantic import BaseModel, Field, field_validator

class Invoice(BaseModel):
    invoice_no: str
    date: str = Field(pattern=r"^\d{4}-\d{2}-\d{2}$")
    total: float = Field(ge=0)
    currency: Literal["INR", "USD", "EUR"]

    @field_validator("total")
    @classmethod
    def two_decimals(cls, v):
        if round(v, 2) != v:
            raise ValueError("total must have at most 2 decimals")
        return v

Pydantic generated a matching JSON Schema with Invoice.model_json_schema(): properties invoice_no, date, total and currency, all required. That schema can be sent to providers that support schema-constrained output, so one definition drives both generation and validation. In TypeScript, Zod plays the same role. If type hints and dataclasses are familiar, Pydantic models will feel natural.

How model output breaks

We validated six responses with Invoice.model_validate_json():

good            OK  1180.0
markdown fence  FAIL (1) ['root: json_invalid']
trailing text   FAIL (1) ['root: json_invalid']
wrong types     FAIL (4) ['invoice_no: string_type', 'date: string_pattern_mismatch',
                          'total: float_parsing', 'currency: literal_error']
missing field   FAIL (1) ['date: missing']
string number   OK  1180.0

Each failure mirrors something models really do when only prompted:

  • Markdown fences: the JSON arrives inside ```json ... ```, because chat-tuned models format answers for humans.
  • Chatty extras: a friendly sentence after the JSON makes it invalid.
  • Wrong types and formats: the invoice number as a number, the date as “10/11/2026”, the total as “1,180” and the currency as “Rs”. Four errors in one response.
  • Missing fields: a field the model could not find was simply left out.

Rescuing wrapped JSON

def extract_json(text):
    s, e = text.find("{"), text.rfind("}")
    return text[s:e + 1] if s != -1 and e > s else text

# markdown fence  after extract_json: OK INV-104 1180.0
# trailing text   after extract_json: OK INV-104 1180.0

Taking the text between the first { and the last } recovered both wrapped responses. It is a useful safety net, but a fragile one: it fails for arrays, for responses containing several objects, or when explanatory text itself contains braces. Treat it as a fallback, not a design.

Lax vs strict parsing

The “string number” response sent "total": "1180.00", a string rather than a number, and it passed. Pydantic’s default lax mode converts clean numeric strings to floats. That is convenient, but it means a type error in the model’s output can go unnoticed. If you want to detect when the model ignores the schema, for example to measure reliability, use strict mode, which would reject it. Choose deliberately: lax mode for robustness, strict mode for measurement and for fields where a type change would be suspicious.

Constrained decoding

Several providers and open-source inference tools offer schema-constrained output. Conceptually, the schema is turned into rules about which tokens may come next, and tokens that would break the format are blocked during generation. The model physically cannot produce a Markdown fence or a missing brace. This removes almost all syntax and shape errors. Some write-ups report that heavy constraints can slightly reduce answer quality on reasoning-heavy tasks, so measure on your own data. Supported schema features also vary between providers, so check what your provider accepts.

Tip: For extraction tasks, set a low temperature, give field descriptions in the schema, and allow an explicit “not found” value, such as null, for optional fields. A model forced to fill a required field with no source data is being invited to hallucinate.

Valid is not the same as correct

Schema validation checks shape. It cannot tell whether 1080 or 1180 is the right total. We added a simple semantic check, confirming the extracted total appears in the source text:

semantic check (total in source): True
semantic check (wrong total):     False

A response with total 1080 was perfectly valid JSON with the right types, and it was still wrong. Business-rule checks catch these: totals that match line items, dates that are not in the future, IDs that exist in your database, values that appear in the source document. These are the checks that protect real users.

Retry and repair loops

  1. Call the model with the schema and clear instructions.
  2. Parse and validate the response.
  3. If it fails, call again with the validation errors included, such as “date must match YYYY-MM-DD”.
  4. Stop after a small number of attempts, then fall back: queue for human review, return a clear error, or use a default.
  5. Log every failure with the raw response so you can improve the prompt or schema.

Pydantic’s error list, such as date: string_pattern_mismatch, is precise enough to feed back to the model. Keep retries bounded; an unbounded loop can multiply costs quickly.

Schema design tips

  • Keep it flat and small. Deeply nested schemas fail more often.
  • Use enums for categories instead of free text.
  • Use explicit formats for dates and amounts, and say so in field descriptions.
  • Allow null for information that may be missing.
  • Add a confidence or notes field only if your code will actually use it.
  • Version your schema, since changing it is a contract change, as discussed in API contract testing.

Testing structured output

Build a test set of real inputs with expected outputs, including messy documents and cases where fields are missing. Run it on every prompt, schema or model change, and track three numbers: the share of responses that parse, the share that pass validation, and the share whose values are correct. Unit-test your validators with deliberately broken outputs, like our six examples, so that parsing code never surprises you in production.

Putting it together: a minimal pipeline

  1. One model definition in Pydantic or Zod, with field descriptions and allowed values.
  2. Generate the JSON Schema from it and pass it to the provider’s structured-output or tool-calling feature.
  3. Parse and validate the reply with the same model, falling back to JSON extraction only if needed.
  4. Run semantic checks against the source data and business rules.
  5. Retry once or twice with the error messages, then route failures to a human queue.
  6. Log the raw input, raw output, errors and settings for every call, so failures can be reproduced and fixed.

Each layer catches problems the others miss. Together they turn a probabilistic model into a component the rest of your system can depend on.

Final thoughts

Getting JSON from a model is easy; getting reliable JSON takes layers. Define the schema once, in Pydantic or Zod, use your provider’s schema-constrained output where available, validate every response in your own code, add semantic checks for values that matter, and retry with error feedback a limited number of times. In our test, four of six prompt-style responses failed validation on first parse, and schema checks alone would have accepted a wrong total.

Frequently asked questions

What is structured output in LLMs?

A way of getting a language model to return data in a defined format, usually JSON matching a schema, so that application code can use it directly.

Is JSON mode the same as structured output?

Not quite. JSON mode guarantees valid JSON syntax but not your fields or types. Schema-based structured output constrains the response to a specific schema.

Why does the model wrap JSON in markdown?

Chat-tuned models format answers for people. Use provider structured-output features, or extract the JSON object from the text as a fallback.

Do I still need validation with constrained decoding?

Yes. Validation in your code protects against provider changes and model swaps, and semantic checks catch values that are well-formed but wrong.

Which library should I use to validate LLM output?

Pydantic is the common choice in Python and Zod in TypeScript. Both can generate JSON Schema from the same definitions you validate with.

Keep learning

Work with Stack Quora

Need help with testing, WordPress or SEO?

We help teams ship better software and grow their sites. Tell us what you are working on and we will suggest a clear next step.

Keep reading

More guides on testing, AI & modern development

Enjoyed this article? Pick a topic and jump straight into our newest tutorials.

Artificial Intelligence

LLM Structured Output Explained: Getting Reliable JSON From AI Models

LLM structured output explained with validation we ran in Pydantic: JSON mode and schemas, constrained decoding, the ways model output…

Read article →
DevOps

SSH Keys Explained: How They Work, ssh-keygen, Ed25519 and Safe Habits

SSH keys explained with keys we generated: public vs private keys, ssh-keygen, Ed25519 vs RSA, fingerprints, passphrases, ssh-agent, authorized_keys, config…

Read article →
DevOps

HTTP Caching Explained: Cache-Control, ETag and 304 Responses, With a Live Test

HTTP caching explained with a small server we ran: Cache-Control directives, max-age, no-cache vs no-store, ETag revalidation and 304 responses,…

Read article →
Test Automation

API Contract Testing Explained: Catch Breaking Changes Before They Ship

API contract testing explained with a schema check we ran: what a contract is, consumer-driven contracts, Pact, OpenAPI, which changes…

Read article →
Software Testing

Risk-Based Testing Explained: Score Risks, Build a Matrix and Test What Matters

Risk-based testing explained step by step: identifying risks, scoring likelihood and impact, building a risk matrix, mapping risk to test…

Read article →
Databases & SQL

SQL Constraints Explained: NOT NULL, UNIQUE, CHECK and FOREIGN KEY, Tested

SQL constraints explained with tests we ran: NOT NULL, UNIQUE, CHECK, DEFAULT, PRIMARY and FOREIGN KEY, the NULL loopholes, SQLite's…

Read article →
Databases & SQL

SQL Date Functions Explained: Adding, Comparing and Grouping Dates Without Bugs

SQL date functions explained with queries we ran: adding intervals, month-end surprises, date differences, the BETWEEN trap, grouping by day,…

Read article →
Software Development

Python asyncio Explained: async, await, gather and TaskGroup With Real Timings

Python asyncio explained with code we timed: coroutines, await, gather, TaskGroup, error handling, timeouts, limiting concurrency and the blocking-call mistake…

Read article →
Software Development

Debounce vs Throttle in JavaScript: How They Work, When to Use Each, Tested

Debounce vs throttle in JavaScript explained with timings we measured in Node.js: how each works, simple implementations, leading and trailing…

Read article →
Software Development

Python Context Managers Explained: The with Statement, contextlib and Real Uses

Python context managers explained with code we ran: how with works, __enter__ and __exit__, contextlib.contextmanager, suppress, ExitStack, database transactions and…

Read article →
Artificial Intelligence

LLM Temperature and Top-p Explained: How AI Models Choose Their Next Word

LLM temperature and top-p explained with a simulation we ran: how probabilities are reshaped, what top-p keeps, recommended settings by…

Read article →
DevOps

YAML Explained: Syntax, the Norway Problem and Other Traps We Tested

YAML explained with a parser test: basic syntax, lists and maps, the Norway problem, versions turning into floats, octal zip…

Read article →
DevOps

Cron Jobs Explained: Syntax, Real Schedules and the Mistakes That Break Them

Cron jobs explained with schedules we verified: the five fields, operators, real examples, the day-of-month OR day-of-week trap, environment problems,…

Read article →
Software Testing

Bug Life Cycle in Software Testing: Every Status, Who Owns It and Common Mistakes

The bug life cycle explained: every defect status from New to Closed, who owns each step, rejected, deferred and reopened…

Read article →
Test Automation

Property-Based Testing in Python: Hypothesis Finds the Bugs Your Examples Miss

Property-based testing explained with Hypothesis tests we ran: properties vs examples, strategies, shrinking, the real bugs it found in our…

Read article →
Databases & SQL

SQL Pagination Explained: OFFSET vs Keyset, With a Million-Row Test

SQL pagination explained with a million-row test we ran: LIMIT and OFFSET, why deep pages get slow, keyset (cursor) pagination,…

Read article →
Databases & SQL

SQL EXISTS vs IN: Differences, the NOT IN NULL Trap and Performance

SQL EXISTS vs IN explained with queries we ran: how each works, why NOT IN returns no rows when a…

Read article →
Software Development

Python Logging Explained: Levels, Handlers, Formatters and Mistakes to Avoid

Python logging explained with code we ran: levels, basicConfig quirks, named loggers, handlers and formatters, logger.exception, lazy formatting, duplicate logs…

Read article →
Software Development

JavaScript Map vs Object: Key Differences, Pitfalls and a Benchmark

JavaScript Map vs Object explained with code we ran in Node.js: key types, ordering, the prototype trap, JSON, size, WeakMap…

Read article →
Software Development

Python Type Hints Explained: Annotations, mypy and the Errors It Catches

Python type hints explained with a real mypy run: basic annotations, Optional and unions, TypedDict, Literal, Protocol, generics, Callable, strict…

Read article →
Artificial Intelligence

LLM Tokens Explained: How AI Models Read Text, Count Costs and Fill Context Windows

LLM tokens explained with a tokenizer we ran: how text is split, why counts differ by language and tokenizer, context…

Read article →
DevOps

Semantic Versioning Explained: MAJOR.MINOR.PATCH, Ranges and Release Rules

Semantic versioning explained with code we ran: MAJOR.MINOR.PATCH rules, pre-releases, correct version sorting, caret and tilde ranges, 0.x versions, lockfiles…

Read article →
DevOps

Git Reset vs Revert: How to Undo Commits Safely, With a Tested Example

Git reset vs revert explained with a repository we built: soft, mixed and hard reset, revert commits, reverting merges, recovering…

Read article →
Software Testing

The Test Pyramid Explained: Layers, Ratios and When to Break the Shape

The test pyramid explained: unit, integration and end-to-end layers, sensible ratios, the ice cream cone anti-pattern, the testing trophy and…

Read article →
Test Automation

pytest Fixtures Explained: Scope, yield Teardown, conftest.py and Factories

pytest fixtures explained with a suite we ran: how fixtures work, scopes, yield teardown, conftest.py, factory fixtures, parametrized fixtures, built-ins…

Read article →
Databases & SQL

SQL Upsert Explained: INSERT ON CONFLICT, MERGE and the REPLACE Trap

SQL upsert explained with queries we ran: INSERT ON CONFLICT DO UPDATE and DO NOTHING, the excluded row, conditional updates,…

Read article →
Databases & SQL

SQL LIKE Operator Explained: Wildcards, Case Sensitivity and Performance

The SQL LIKE operator explained with queries we ran: % and _ wildcards, escaping, NOT LIKE and NULL, case sensitivity…

Read article →
Artificial Intelligence

AI Hallucinations Explained: Why Language Models Make Things Up and How to Reduce It

AI hallucinations explained: what they are, why language models produce them, common types, how to reduce them with grounding and…

Read article →
Test Automation

Mocking in Python: unittest.mock, patch and the Mistakes That Make Tests Lie

Mocking in Python with unittest.mock, tested: Mock and return_value, side_effect, patching where a name is used, spec and autospec, mocking…

Read article →
Software Testing

Code Coverage Explained: Line vs Branch Coverage and What 100% Really Means

Code coverage explained with a real coverage.py run: line, branch and condition coverage, reading a report, why 100% coverage can…

Read article →
Artificial Intelligence

What Are AI Agents? How They Work, With a Simple Agent Loop You Can Run

What are AI agents? A plain guide to the agent loop, tools, memory and guardrails, with a small Python loop…

Read article →
Test Automation

TDD vs BDD: Key Differences, One Feature Built Both Ways and When to Use Each

TDD vs BDD explained with one discount feature built both ways: red-green-refactor with code we ran, Given-When-Then scenarios, tools, trade-offs…

Read article →
Software Testing

User Acceptance Testing (UAT): Process, Checklist and Real Examples

User acceptance testing explained: who runs it, how it differs from QA, a seven-step process, a UAT test case template,…

Read article →
Artificial Intelligence

What Are Embeddings? Vectors and Cosine Similarity Explained Simply

What are embeddings? A plain-language guide to vectors, cosine similarity and semantic search, with a small example we ran, common…

Read article →
Test Automation

Flaky Tests: What Causes Them and How to Fix Them for Good

Flaky tests explained with demos we ran: the main causes, how to confirm and diagnose one, proper fixes for timing,…

Read article →
Software Testing

Load Testing vs Stress Testing: Differences, Metrics and k6 Examples

Load testing vs stress testing explained: what each proves, spike and soak tests, the metrics that matter, why averages mislead,…

Read article →