Structured Outputs in LLM APIs: JSON Schema Prompts, Validation, and Error Handling
structured outputsJSON SchemaLLM APIsprompt engineeringdeveloper tools

Structured Outputs in LLM APIs: JSON Schema Prompts, Validation, and Error Handling

PPromptCraft Lab
2026-12-06
7 min read

A practical guide to reliable JSON from LLM APIs, covering schemas, validation, refusals, repair, retries, and provider checks.

Reliable JSON from an LLM requires more than asking a model to “return JSON.” This guide provides a practical workflow for structured outputs in LLM APIs, including schema design, prompt templates, validation, refusals, repair strategies, safe retries, and provider checks you can reuse whenever an output type, model, or API changes.

Overview

Structured output is the practice of constraining an LLM response so an application can consume it as predictable data rather than as free-form text. A typical workflow asks a model to extract fields, classify a request, summarize a document, or create an action plan. The application then parses the response and uses those fields in a database, user interface, search index, or downstream API.

There are three related but different approaches:

  • Prompt-only JSON: You describe the required format in natural language and hope the model follows it. This is easy to prototype but offers the weakest guarantees.
  • JSON mode: A provider-level setting may encourage valid JSON syntax. It can reduce formatting errors, but it does not necessarily guarantee that every required field, type, or constraint is present.
  • Schema-constrained output: You provide a JSON Schema or equivalent typed definition. When supported by the selected model and API, this gives the application a stronger contract to validate against.

The safest design treats the model as an untrusted, probabilistic component. A schema helps define the expected shape; application-side validation remains necessary. Your code should also account for refusals, incomplete responses, timeouts, provider errors, and schema features that a particular model or endpoint does not support.

A provider comparison checklist

Capability to compareWhy it mattersQuestion to verify
Native structured outputsMay enforce a schema more reliably than prompt instructions alone.Does the endpoint support schema-constrained responses for the model you selected?
JSON modeCan improve syntax consistency without defining every field.Does JSON mode validate only syntax, or also required fields and types?
Schema dialect and keywordsNot every JSON Schema feature is accepted by every API.Which types, arrays, enums, nesting rules, and additional-properties settings are supported?
Refusal and finish-state signalsA refusal or truncated response should not be parsed as ordinary business data.How does the SDK expose refusals, incomplete output, length limits, and tool errors?
SDK and model compatibilitySyntax and support can differ between models, endpoints, and SDK versions.Is the example valid for the exact model, endpoint, and SDK version in production?

Use provider documentation as the final authority before shipping. API features and model limitations can change, so avoid treating a comparison table as a permanent capability guarantee.

Checklist by scenario

Scenario 1: Extract fields from text

Start with a narrow schema and define what should happen when evidence is missing. For example:

{
  "type": "object",
  "properties": {
    "customer_name": { "type": ["string", "null"] },
    "order_id": { "type": ["string", "null"] },
    "issue_type": {
      "type": "string",
      "enum": ["billing", "technical", "shipping", "other", "unknown"]
    },
    "evidence": { "type": "array", "items": { "type": "string" } }
  },
  "required": ["customer_name", "order_id", "issue_type", "evidence"],
  "additionalProperties": false
}

A useful structured output prompt is:

Extract only information supported by the supplied text.
Use null when a requested value is not present.
Choose issue_type only from the allowed enum values.
Put short supporting quotations or precise references in evidence.
Return data that conforms to the provided schema. Do not add commentary.

Keep evidence separate from the extracted value. This makes review easier and reduces the temptation to treat an inference as a confirmed fact.

Scenario 2: Classify a request

Use an enum for a closed set of labels and include a confidence explanation only if your application needs it. Do not ask for a numerical confidence score unless you have defined how it will be interpreted and tested. A compact schema might contain label, reason, and needs_human_review. Make the review flag a deliberate business rule, not a substitute for validation.

Scenario 3: Generate a multi-step result

For plans, workflows, or content records, represent repeated items as an array of objects. Give each item a stable field such as step_id, title, description, and dependencies. Define whether an empty array is valid. If order matters, state that order explicitly and validate uniqueness of identifiers in application code.

Scenario 4: Extract data for a RAG workflow

Separate retrieved content from the model’s answer. A useful output can include answer, source_ids, unanswered_questions, and requires_escalation. Tell the model to use only the supplied context and to mark unsupported questions rather than fill gaps from general knowledge. Structured outputs improve transport and validation, but they do not by themselves prevent prompt injection or unreliable retrieval. Review the prompt injection defense checklist for RAG and AI agents before connecting retrieved text to actions.

Scenario 5: Return data to a production application

Validate the response at the boundary before writing to a database or invoking another service. Reject unknown fields when possible, enforce maximum string lengths, check enum values, and apply business rules such as valid dates, permitted identifiers, and safe numeric ranges. Log a redacted validation result rather than automatically storing sensitive raw prompts or responses.

What to double-check

  1. Schema semantics: Decide whether missing, empty, null, and unknown mean different things. Express those distinctions consistently.
  2. Required fields: A field being required does not mean its value is factually available. Allow a controlled unknown or null state where appropriate.
  3. Additional properties: Rejecting unexpected fields can expose prompt or model drift early. If you allow them, define how they are handled.
  4. Nested complexity: Deeply nested schemas are harder to test and may not be supported uniformly. Flatten the design when a simpler representation works.
  5. String limits: Set application-level limits for free text, arrays, and item counts. A valid response can still be too large or expensive for your workflow.
  6. Refusals and incomplete output: Check provider-specific response metadata before calling a JSON parser. A refusal message is not a valid business record.
  7. Retries: Retry transient transport failures and selected provider errors, not every validation failure. Include a bounded attempt count and backoff.
  8. Repair: Use a repair step only for narrowly defined formatting problems. Do not silently “repair” missing facts, invalid identifiers, or unsafe actions.
  9. Observability: Record model identifier, schema version, latency, token usage where available, validation outcome, and retry count. The LLM observability guide provides a broader monitoring framework.

A defensive processing sequence looks like this:

response = call_model(request, schema)

if response.is_refusal:
    return human_review_or_safe_fallback()

if response.is_incomplete:
    return bounded_retry_or_failure()

try:
    data = parse_json(response.text)
except ParseError:
    return bounded_format_retry(response.text)

if not schema_validator(data):
    return bounded_semantic_retry(data)

if not business_rules_pass(data):
    return human_review_or_failure()

return data

The exact SDK properties differ, but the separation of transport handling, parsing, schema validation, and business validation is portable across providers.

Common mistakes

  • Relying on “return JSON” alone: Natural-language instructions do not create a machine-enforced contract.
  • Confusing valid JSON with correct data: A syntactically valid object can contain invented, incomplete, or misclassified values.
  • Using one giant schema for every task: Smaller task-specific outputs are easier to test, version, and troubleshoot.
  • Ignoring provider limitations: A schema that works with one endpoint may fail or behave differently with another. Verify support for the exact model and API path.
  • Retrying without changing anything: Repeating the same request can repeat the same failure. On a validation retry, provide concise failure details and preserve the original source text.
  • Repairing with an unconstrained second call: A repair prompt should preserve the original schema and prohibit adding unsupported information.
  • Skipping adversarial tests: Test empty input, conflicting evidence, long input, malformed source text, prompt injection, refusal-triggering requests, and partial provider responses.
  • Breaking consumers during schema changes: Version output contracts and update readers before producers when a field is renamed, removed, or retyped.

For production quality, create a fixture set of representative inputs and expected validation outcomes. Run it when you change the prompt, schema, model, SDK, temperature settings, or retry policy. Pair this with prompt regression testing and task-specific benchmarking rather than relying on a handful of successful examples.

When to revisit

Return to this checklist before a seasonal planning cycle, whenever a workflow or tool changes, and whenever a new output type is introduced. It should also be part of your release process when you upgrade a model, switch providers, change an SDK, alter a schema, or move from experimentation to production.

At each review, confirm the provider’s current structured-output and JSON-mode documentation, supported schema features, refusal and incomplete-response behavior, rate and size limits, and SDK syntax. Re-run your fixture suite and compare parsing failures, validation failures, retries, latency, and cost against the previous version. If the model is being replaced or retired, use the model deprecation checklist and test the new model against the same contract.

A practical final sign-off is:

  • Schema version is recorded and reviewed.
  • Unknown, null, and empty values have defined meanings.
  • Provider support was checked for the exact model and endpoint.
  • Refusals, truncation, parse errors, and validation failures have separate paths.
  • Retries are bounded, observable, and safe.
  • Business rules run after schema validation.
  • Regression fixtures cover normal, missing, adversarial, and oversized inputs.
  • Downstream consumers can handle the current contract.

Structured outputs are most dependable when treated as one layer in a broader AI development workflow: prompt engineering defines intent, schemas define shape, validators enforce structure, business rules protect the application, and monitoring reveals when the system needs attention.

Related Topics

#structured outputs#JSON Schema#LLM APIs#prompt engineering#developer tools
P

PromptCraft Lab

AI Development Editor

Senior editor and content strategist. Writing about technology, design, and the future of digital media. Follow along for deep dives into the industry's moving parts.