Structured outputs make LLM applications easier to integrate, test, and maintain. This guide shows how to design a practical JSON Schema, estimate token and processing costs, validate model responses, recover from failures, and version your contract as an application changes.
Overview
A request such as “return the answer as JSON” is a formatting instruction, not a complete reliability strategy. A model may return valid-looking JSON with missing fields, incorrect data types, unexpected keys, or values that do not match the assumptions in your code. The dependable approach is to combine structured output support from the provider with explicit schema design and application-side validation.
The basic workflow is:
- Define the smallest useful response contract.
- Send that contract through the provider’s structured-output or JSON response feature when available.
- Ask the model to produce only the requested object.
- Parse the response and validate it against the same schema in your application.
- Log failures, retry selectively, and route unresolved cases to a fallback or human review.
Provider features differ. Some APIs accept a JSON Schema directly, while others offer a JSON mode that guarantees or encourages JSON syntax without enforcing every field rule. Before implementation, check the current provider documentation for supported models, schema keywords, nesting limits, refusal behavior, and SDK syntax. The provider comparison guide on AI API platforms is useful when comparing these capabilities.
Structured outputs do not make factual claims true. They constrain shape and, depending on the implementation, some values. If the response depends on private or changing information, pair the workflow with retrieval, citations, or tools. See the RAG tutorial for a retrieval-based design.
How to estimate
For planning purposes, estimate a structured-output request in three layers: input tokens, output tokens, and operational overhead. This gives you a repeatable way to compare schema designs and model configurations without relying on a fixed price or benchmark.
1. Estimate input tokens
Include the system instructions, user request, examples, retrieved context, tool results, and the serialized schema or response definition if the provider counts it as input. A simple estimate is:
Input tokens per request = instructions + user content + context + schema overhead
Schema overhead grows with long property descriptions, repeated nested objects, verbose enum labels, and few-shot examples. Keep descriptions useful but concise. Do not add fields merely because they might be useful later; every field increases the contract that must be generated, validated, documented, and maintained.
2. Estimate output tokens
List the expected fields and estimate the serialized size of a typical response. Include property names, punctuation, values, arrays, and nested objects. Then create a high-side estimate for unusually long values. Your planning figure can be:
Expected output tokens = typical response tokens
Safety limit = expected output tokens + allowance for valid variation
Set a maximum output limit that is large enough for legitimate responses but not so large that an accidental long explanation consumes unnecessary capacity. A schema can require a field such as summary, but it cannot by itself ensure that the summary is short or accurate unless you add application checks.
3. Estimate failure and retry overhead
Track the proportion of requests that fail parsing, fail schema validation, time out, or require a second attempt. A practical planning formula is:
Expected requests processed = initial requests × (1 + retry rate)
For example, if a batch contains 1,000 initial requests and your observed retry rate is 0.08, plan for 1,080 model calls before accounting for unrelated API retries. Keep transport retries separate from content-repair retries so you can identify whether the issue is rate limiting, a provider error, a weak prompt, or an unsuitable schema. The guide to LLM API error handling covers the transport side.
When comparing options, record input tokens, output tokens, latency, validation-pass rate, retry rate, and useful-task accuracy. A cheaper response that fails validation frequently may cost more after recovery work.
Inputs and assumptions
A good schema expresses the application’s decision boundary, not every detail the model could mention. Start by deciding what downstream code actually needs.
| Pattern | Use it when | Design guidance |
|---|---|---|
| Required scalar | The application cannot continue without a value | Use a clear type and validate range, length, or format in code. |
| Optional field | The value may legitimately be unavailable | Define whether omission, null, or an empty array represents unavailable data. |
| Enum | Only a controlled set of states is valid | Use stable machine values such as approved or needs_review. |
| Nested object | Several fields belong to one reusable concept | Keep nesting shallow unless the domain genuinely requires hierarchy. |
| Array | The result contains zero or more repeated items | Specify item shape and set a maximum length in application validation. |
Required and optional fields
Mark a field as required only when its absence is an actionable failure. If a classifier may not have enough evidence to identify a category, represent uncertainty explicitly with a controlled value such as unknown or with a nullable field. This is safer than forcing the model to invent a value.
Enums and nested objects
Enums reduce ambiguity, but they also create a maintenance obligation. Choose values that are stable in code and provide human-readable labels separately if needed. For nested objects, define each child’s required fields and decide what an empty object means. A common failure is validating the outer object while never checking the contents of its nested arrays.
Reusable schema pattern
{
"schema_version": "1.0",
"classification": "needs_review",
"confidence": 0.72,
"reasons": [
"The request contains an unresolved reference."
],
"next_action": {
"type": "ask_clarifying_question",
"question": "Which product line should be used?"
}
}
This example separates a controlled decision from supporting explanation and a suggested action. In production, validate that confidence is within the intended range, reasons has an allowed length, and next_action.type belongs to a known set. A system prompt can explain the role and rules, but the validator remains the final gate. For more on that distinction, see system prompt design.
Reusable prompt template
Return one JSON object that conforms to the supplied schema.
Do not include Markdown fences, commentary, or additional top-level keys.
Use only the enum values defined by the schema.
If the evidence is insufficient, use the permitted unknown or null value.
Do not infer facts that are absent from the input.
Before responding, check required fields, data types, and nested item shapes.
Use provider-native structured output settings in addition to this instruction where supported. Prompting alone is less predictable than a schema-aware API feature plus validation.
Worked examples
Example 1: A document extraction request
Suppose an application extracts an invoice number, date, supplier, currency, and line items. The first version should include only fields required by the accounting workflow. Estimate one typical response and one large response with many line items. If line items are unbounded, choose an application limit and define what happens when it is exceeded: reject the response, truncate with an explicit flag, or split the document into smaller extraction tasks.
Validation should occur in stages:
- Confirm the response is a JSON object, not a string containing JSON or Markdown.
- Validate required keys and data types.
- Check date and currency formats.
- Check that each line item has the required child fields.
- Apply business rules, such as a non-negative quantity or a total that is within an accepted tolerance.
Schema validation can catch a missing currency; it cannot determine whether the extracted currency is correct. That requires a domain check, comparison with source text, or human review.
Example 2: Recovering from malformed output
If parsing fails, do not blindly resend the entire conversation. Capture the error category and try a bounded recovery path. A repair request can include the original output and say: “Return the same information in the required schema. Do not add information. If a value cannot be recovered, use the permitted null or unknown value.” Avoid asking the model to explain the error inside the production response, because that explanation can create another schema failure.
If validation fails because a value is semantically wrong, a repair attempt may not help. Route the item to a fallback model, a deterministic parser, or human review based on its risk. For high-impact workflows, keep the original input, raw response, validation errors, schema version, and retry outcome for auditing and regression tests.
Build a small test set containing valid, ambiguous, empty, adversarial, and unusually long inputs. Run it whenever you change the prompt, schema, model, retrieval settings, or provider. The LLM evaluation guide provides a broader framework for this kind of regression testing.
When to recalculate
Revisit your estimates and compatibility checklist whenever a provider changes model behavior, response-format support, token accounting, context limits, SDK syntax, or pricing inputs. Also recalculate after changing the schema, adding few-shot examples, increasing retrieved context, or allowing longer user content.
Operationally, review the workflow when any of these signals move:
- Validation-pass rate declines.
- Retry or fallback volume increases.
- Average output length grows.
- Latency becomes unacceptable for the user experience.
- A new field or enum value is needed by downstream code.
- A model migration changes refusal, truncation, or structured-output behavior.
Version schemas explicitly, for example with schema_version: 1.0. Prefer additive changes when possible: introduce an optional field before making it required, and support old versions during a migration window. If you rename an enum or change the meaning of a field, treat it as a contract change rather than a prompt edit.
Before shipping, use this checklist:
- Define required, optional, nullable, and enum values.
- Confirm the provider and selected model support the intended response format.
- Keep schema descriptions and prompts concise.
- Parse and validate every response in application code.
- Apply business rules after schema validation.
- Set bounded timeouts, retries, and recovery paths.
- Log schema version, validation errors, token usage, and outcome.
- Re-run representative tests after every prompt, model, schema, or API change.
This process turns structured output from a formatting preference into a maintainable interface. Recalculate the estimates when inputs or provider behavior change, and keep the schema as carefully versioned as any other API contract.