Most business uses of AI end in code. A product description goes into a CMS, an extracted invoice total goes into an accounting system, a ticket category triggers a workflow. Free text breaks those handoffs: a missing field, an extra sentence before the JSON or a value outside the allowed list stops the pipeline or, worse, passes bad data downstream.
Reliable structured output comes from four layers working together: a schema the model is constrained to follow, validation of business rules the schema cannot express, automatic retries or rejection when a response fails and tests that run whenever prompts, schemas or models change.
This article explains the methods for getting structured output, how to design schemas, what to validate after generation, how to handle failures and how a media publisher generates about 100 product reviews a week in a fixed format. It does not cover model fine-tuning.
Key takeaways
- Prompting alone produces the right format most of the time, which is not enough for an automated pipeline.
- Schema-constrained generation, offered by major model providers as structured outputs or strict tool use, makes responses follow your JSON schema.
- A valid schema does not mean a correct answer. Validate business rules separately: links, IDs, lengths, ranges and banned phrases.
- Plan for refusals, truncated responses and API errors, which can still produce output that does not match the schema.
- Reject or retry failed responses automatically, and send repeated failures to a review queue.
- In a delivered project, a strict response schema, catalog-based link rules and automatic rejection of malformed drafts let a multi-brand publisher produce about 100 uniform product reviews a week.
Why free-text answers break applications
| Failure | Example | What it breaks |
|---|---|---|
| Wrapper text | "Sure! Here is the JSON:" before the object | Parsers fail |
| Missing fields | No price in one response out of fifty | Records saved incomplete |
| Wrong types | "twelve" in a numeric field | Calculations and imports |
| Values outside the list | A category the system does not have | Routing and reporting |
| Invented references | A product link or customer ID that does not exist | Revenue, trust, data integrity |
| Format drift | Headlines grow longer, sections change order | Templates and page layouts |
These failures are rare in a demo and constant at volume. A pipeline that processes 1,000 items a day with a 2% format failure rate produces 20 broken items every day.
Four ways to get structured output
| Method | How it works | Format reliability | Use it for |
|---|---|---|---|
| Prompt instructions | The prompt describes the format and gives an example | Good, with occasional drift | Prototypes and low-volume tools |
| JSON mode | The provider guarantees valid JSON, without checking it against a schema | Valid JSON, fields can still be missing or wrong | Older integrations |
| Schema-constrained output | The model's output is constrained to a JSON schema you provide | Follows the schema, except for refusals and cutoffs | Most production pipelines |
| Tool or function calling | The model fills in the arguments of a function you define, optionally in strict mode | Follows the tool's schema in strict mode | Agents and workflows that call your systems |
OpenAI's Structured Outputs guide explains that JSON mode only guarantees valid JSON, while Structured Outputs makes responses follow the supplied schema, and recommends the latter where available. Anthropic's structured outputs documentation describes the same approach for Claude, using constrained decoding for JSON outputs and strict tool use, and lists its limits: refusals and responses cut off by token limits can still break the schema, and complex schemas have size limits.

Designing the schema
Schemas are written in JSON Schema, the standard vocabulary for describing JSON data, or generated from typed definitions such as Pydantic in Python or Zod in TypeScript.
- Name fields for meaning. "headline" and "why_buy" guide the model better than "field1" and "text".
- Describe each field. Field descriptions act as instructions: "Two sentences, no superlatives, under 280 characters."
- Use enums for choices. If a value must come from a list, such as a category or sentiment, define the list in the schema.
- Make the right fields required. Optional fields are often left out.
- Allow an honest empty answer. Add a way to say "not found" or "not applicable", so the model does not invent a value to fill a required field.
- Keep it flat and small. Deep nesting and dozens of optional fields make output slower and less reliable, and can hit provider limits.
- Version the schema. Store the version with each output, so downstream systems know which format they received.
What to validate after generation
A response can follow the schema perfectly and still be wrong. Validation in your own code covers what the schema cannot express.
- References exist. Product URLs, SKUs, customer IDs and document numbers must match real records. The safest pattern gives the model a list of allowed values and checks the output against that same list.
- Lengths and counts. Headline length, number of bullets, word limits for a template.
- Ranges and consistency. Dates in the past, totals that equal the sum of line items, percentages under 100.
- Content rules. Banned phrases, required disclosures, tone markers such as excessive exclamation marks.
- Duplicates. The same text generated twice for different items.
Our guide to context engineering covers how to give the model the right lists and examples in the first place.
Building an AI feature that has to feed clean data into your systems? We design prompts, schemas, validation and review queues for production AI pipelines.
Explore AI servicesHandling failures
- Check the response type first. Detect refusals, truncated responses and API errors before parsing, using the fields and stop reasons the provider returns.
- Validate the schema and business rules. Collect every error in one pass.
- Retry with the errors. Send the failed output and the list of errors back to the model once or twice, asking for a corrected version.
- Stop after a limit. After two or three failed attempts, move the item to a review queue for a person. Our guide to dead letter queues covers the pattern.
- Log everything. Store the prompt version, schema version, model, response and validation result for each item, so failure patterns can be analyzed.
- Watch the rates. Track the share of responses that pass on the first attempt. A sudden drop usually means a model update, a prompt change or new kinds of input.
A real case: about 100 product reviews a week for a multi-brand publisher
A US media group runs several ad-supported brands that publish deal and product review content. It needed about 100 short, uniform product reviews every week without a large team of writers. Early experiments with ChatGPT drifted from the required structure, often produced wrong product links and sounded too promotional.
A .wrk team of frontend and backend developers, working with the client's product team:
- Defined a strict response schema for each review: headline, a two-sentence description and a "why buy" section.
- Fixed affiliate link accuracy with explicit catalog instructions and automated validation of each draft's structure.
- Set up automatic rejection of low-quality or malformed drafts before they reach publishing.
- Built a React and Node.js admin panel where editors experiment with the tone of review introductions without developers, while developers own the structure and the quality gates.
- Iterated prompts on real deal inventory with the product team, then scaled to about 100 articles a week in production.
The pipeline brings in thousands of dollars a week in ad and referral revenue at existing traffic levels, and editors spend their time on more complex pieces. Read the AI product review case study.

Testing structured output before changes go live
- Keep a test set. Collect a few dozen real inputs with known correct outputs, including difficult and unusual cases.
- Run it on every change. Prompt edits, schema changes and model upgrades all run against the test set before deployment.
- Measure three numbers. Schema pass rate, business-rule pass rate and the quality score of a human or automated review of the content itself.
- Pin model versions. Upgrade deliberately, after the test set passes on the new version.
Our guide on adding AI to an existing app explains where this layer sits in the application.
Common mistakes
- Trusting the prompt alone. Formats that work in testing drift at volume.
- Treating schema-valid as correct. Real errors live in the values: wrong links, invented IDs, inconsistent totals.
- Forcing an answer. Required fields with no way to say "unknown" invite made-up values.
- Ignoring refusals and cutoffs. These responses break parsers if code assumes every response is complete.
- Silent failures. Items that fail validation must go somewhere visible, never disappear.
- No ownership split. Let editors adjust tone and wording safely, and keep structure and validation with developers.
Frequently asked questions
What is structured output in LLMs?
Structured output is a model response that follows a predefined format, usually JSON that matches a schema, so applications can read the fields directly. Major model providers can constrain generation to a supplied schema.
What is the difference between JSON mode and structured outputs?
JSON mode guarantees that the response is valid JSON, but fields can be missing or have the wrong type. Structured outputs constrain the response to a specific JSON schema, so required fields, types and allowed values follow that schema.
Can structured outputs still fail?
Yes. Refusals, responses cut off by token limits and API errors can produce output that does not match the schema, and schema-valid output can still contain wrong values. Applications need checks, retries and a review queue.
How do you validate LLM output?
Validate it against the JSON schema, then check business rules in code: references exist in your systems, lengths and ranges are within limits, totals are consistent and content rules are met. Retry or reject responses that fail.
Should I use tool calling or structured outputs?
Use structured outputs when you want the model's answer in a fixed format. Use tool calling when the model should choose and call functions in your system. Both can follow strict schemas.
To sum up
Reliable structured output needs a schema the model must follow, validation of the values in your own code, defined handling of refusals and truncated responses, automatic retries with a limit, a review queue for what still fails and a test set that runs on every change. With those layers, AI output can feed websites, databases and workflows at volume.
.wrk builds AI features and content pipelines for companies in the US and Europe, with prompts, schemas, validation and admin tools that let teams run them safely.
Want AI output your systems can trust? Share your use case and volumes, and we will propose a schema, validation and review design.
Explore AI services