AIYINGFrom AI Awareness to Accomplishment
Showing posts with label Structured Outputs. Show all posts
Showing posts with label Structured Outputs. Show all posts

Thursday, November 12, 2026

AI Engineering Active Concepts #007 — Structured Outputs: Making AI Responses Machine-Readable and Reliable

AI ENGINEERING — ACTIVE CONCEPTS & PRACTICES | #007

Structured Outputs: Making AI Responses Machine-Readable and Reliable



Chapter 2: Engineering AI Applications and Agents

AIYING — Accomplishing with AI

The Big Idea: AI applications need more than fluent answers. They need outputs that software can interpret, validate, and use consistently.

Structured outputs help transform generative AI from a conversational capability into a component of operational software systems.

Engineering question: How can we turn an AI-generated response into dependable application data?

Contents

  1. Why Structured Outputs Matter
  2. UNDERSTAND — The Concept
  3. CONNECT — Related AI Engineering Concepts
  4. The Structured Output Pipeline
  5. APPLY — Food Quality Inspection Workflow
  6. Worked Example: From Text to JSON
  7. Engineering Decisions and Trade-offs
  8. Active Industry Practices
  9. ACCOMPLISH — Practical Exercise
  10. Student and Practitioner Project
  11. Check Your Understanding
  12. Active Connections
  13. References and Further Reading

1. Why Structured Outputs Matter

Imagine an AI assistant reviewing food manufacturing quality inspection reports.

An inspector writes:

"Batch B204 was inspected at 09:30. Packaging seal integrity failed on three samples. The batch has been placed on hold pending QA review."

A generative AI model might respond:

"The inspection identified three failed packaging seals, and the batch should remain on hold for quality review."

This response is understandable to a human.

But what if an application must automatically populate a database, create a review task, or display the findings on a dashboard?

The software needs clearly defined fields such as batch ID, inspection time, defect category, affected samples, and review status.

A free-form paragraph does not reliably provide those fields.

Structured outputs create a predictable interface between generative AI and conventional software.

↑ Back to Contents

2. UNDERSTAND — The Concept

What are structured outputs?

Structured outputs are AI-generated responses organized according to a predefined data format or schema.

Common formats include JSON objects, typed records, and application-specific data structures.

A schema specifies the expected fields, data types, allowed values, and sometimes additional constraints.

Three levels of output control

ApproachWhat It ProvidesLimitation
Prompt instructionsRequests a specific formatThe model may not consistently comply
JSON modeHelps produce syntactically valid JSONDoes not necessarily enforce a particular schema
Schema-constrained outputConstrains generation to a supported schemaSchema compliance does not guarantee factual accuracy

Capabilities differ across providers, models, and APIs. Some support strict schema-constrained generation, while others require validation and repair after generation.

What is a schema?

A schema is a contract describing the structure of data.

For example, a quality inspection record might require:

  • batch_id: string
  • defect_type: string
  • failed_samples: integer
  • batch_status: defined category
  • review_required: boolean

Four distinct levels of correctness

  1. Syntax: Is the output valid JSON?
  2. Schema: Does it contain the correct fields and types?
  3. Semantic validity: Do the values make sense under business rules?
  4. Factual accuracy: Are the values supported by the original evidence?

A response can pass the first two checks and still contain an incorrect batch number or invented inspection result.

Important: Structured outputs improve format reliability, not truthfulness by themselves.

↑ Back to Contents

3. CONNECT — Related AI Engineering Concepts

ConceptConnection to Structured Outputs
Prompt EngineeringCommunicates extraction rules and task instructions
Context EngineeringSupplies the source information required for accurate output
JSON SchemaDefines permitted data structures and constraints
Type SystemsSupports predictable integration with application code
Function CallingUses structured arguments to invoke tools and APIs
Workflow AutomationConsumes validated data for subsequent operations
AI AgentsExchange structured results between steps and tools
EvaluationMeasures schema adherence and extraction accuracy
ObservabilityTracks validation failures and output quality
AI GovernanceDefines approval, traceability, and accountability requirements

Structured output versus tool calling

Structured output specifies the format of a model's response.

Tool calling allows a model to propose or request an operation using structured arguments, depending on the application's architecture.

The two capabilities are related but not identical. A valid structured tool call must still be authorized, validated, and executed by application logic.

↑ Back to Contents

4. The Structured Output Pipeline

Source Document or User Input

↓

Task Instructions + Output Schema

↓

Generative AI Model

↓

Structured Response

↓

Schema and Business-Rule Validation

↓

Evidence Verification / Human Review

↓

Approved Application Action

Step 1 — Define the data contract

Specify required fields, types, enumerations, and missing-value handling.

Step 2 — Supply reliable source information

Provide the text or retrieved evidence from which the output should be derived.

Step 3 — Generate structured data

Use schema-constrained generation when supported, or a suitable generation-and-validation workflow.

Step 4 — Validate the response

Check types, required fields, permissible values, and application rules.

Step 5 — Verify critical facts

Compare extracted values with source records and identify uncertainty.

Step 6 — Perform authorized actions

Only validated and appropriately approved data should trigger consequential downstream operations.

↑ Back to Contents

5. APPLY — Food Quality Inspection Workflow

Scenario: AI-Assisted Quality Documentation

A food manufacturing organization receives inspection reports from production facilities.

These reports contain batch identifiers, inspection findings, deviations, and recommended follow-up actions.

The organization wants an AI application to extract structured findings and prepare quality review records.

Approach A — Free-form extraction

The model produces a narrative summary.

Employees must manually locate relevant values and enter them into the quality management system.

Different responses may use inconsistent terminology or omit required fields.

Approach B — Structured extraction

The engineering team defines a quality inspection schema.

The AI application extracts fields into a predictable representation.

Validation checks identify missing or invalid values.

Uncertain or critical findings are routed to qualified personnel for verification.

Engineering outcome

The system can reduce repetitive data entry and improve consistency, provided extracted information is verified and workflow controls remain in place.

For regulated quality processes, a schema-valid response must not be treated as automatically approved evidence.

↑ Back to Contents

6. Worked Example: From Text to JSON

Original inspection note

Batch B204 was inspected at 09:30. Packaging seal integrity failed on three samples. The batch has been placed on hold pending QA review.

Illustrative structured response

{
  "batch_id": "B204",
  "inspection_time": "09:30",
  "defect_type": "seal_integrity",
  "failed_samples": 3,
  "batch_status": "on_hold",
  "review_required": true,
  "confirmed_cause": null
}

The null value indicates that the cause has not been established from the supplied note.

Illustrative JSON Schema

{
  "type": "object",
  "properties": {
    "batch_id": {
      "type": "string"
    },
    "inspection_time": {
      "type": "string",
      "pattern": "^([01][0-9]|2[0-3]):[0-5][0-9]$"
    },
    "defect_type": {
      "type": "string"
    },
    "failed_samples": {
      "type": "integer",
      "minimum": 0
    },
    "batch_status": {
      "type": "string",
      "enum": ["on_hold", "released", "rejected"]
    },
    "review_required": {
      "type": "boolean"
    },
    "confirmed_cause": {
      "type": ["string", "null"]
    }
  },
  "required": [
    "batch_id",
    "inspection_time",
    "defect_type",
    "failed_samples",
    "batch_status",
    "review_required",
    "confirmed_cause"
  ],
  "additionalProperties": false
}

This is a general JSON Schema example. Some model APIs support only a subset of JSON Schema features. Adjust the schema to the selected provider's documented requirements.

What does validation catch?

Potential ErrorValidation Response
Missing batch IDRequired-field failure
"three" instead of integer 3Type validation failure
Unknown status valueEnumeration failure
Negative failed-sample countRange validation failure
Invented cause of failureRequires evidence verification; may pass schema checks

The final example demonstrates why schema validation and factual verification must remain separate.

↑ Back to Contents

7. Engineering Decisions and Trade-offs

DecisionPotential BenefitTrade-off
Strict schemaPredictable integrationLess flexibility for unexpected information
Optional fieldsHandles incomplete sourcesMore downstream missing-value logic
Enumerated valuesConsistent classificationsMay exclude legitimate new categories
Automatic retriesCan recover from transient failuresAdditional cost and latency
Human reviewOversight of critical recordsAdditional operational effort
Detailed schemasStronger data contractsMaintenance and versioning complexity
Automatic downstream actionsFaster workflowsGreater consequences from incorrect data

Important failure modes

  • Schema-valid but factually incorrect values
  • Unsupported or invented information
  • Incorrect classification of ambiguous records
  • Missing-value handling failures
  • Schema changes that break downstream integrations
  • Untrusted source text attempting to override instructions
  • Unauthorized actions triggered by extracted data
The strongest data contract is not a substitute for evidence verification, business validation, and authorization.

↑ Back to Contents

8. Active Industry Practices

Established practices

  • JSON-based application integration
  • Schema-constrained model responses
  • Typed data validation
  • Structured tool arguments
  • Application-level business-rule checks
  • Human review for consequential decisions

Evolving practices

  • Schema-first AI application development
  • Typed interfaces between agent components
  • Automated schema-conformance evaluation
  • Versioned contracts for multi-agent systems
  • Structured multimodal information extraction
  • Adaptive validation and exception routing

Where structured outputs are used

Structured outputs support invoice processing, document intelligence, customer-support ticket classification, enterprise workflows, software development assistants, information extraction, and agent orchestration.

Practice status: Established software integration approach with expanding generative AI support.

Reviewed: November 2026.

↑ Back to Contents

9. ACCOMPLISH — Practical Exercise

Exercise: Turn an Inspection Note into Validated Data

Use the following fictional note:

Batch F318 was inspected at 14:15. Two packages showed incorrect labeling. The batch is on hold. The cause has not been confirmed. QA review is required.

Your tasks

  1. Identify the information that should be extracted.
  2. Define a JSON structure for the inspection record.
  3. Identify required and optional values.
  4. Specify permitted batch-status values.
  5. Represent the unconfirmed cause without inventing one.
  6. Generate a structured response using an AI tool.
  7. Validate its fields and types.
  8. Compare every extracted value with the original note.

Reusable AI-assisted prompt

Act as an AI information extraction engineer.

Extract a structured inspection record
from the source note below.

Return only a JSON object with these fields:
batch_id, inspection_time, defect_type,
failed_samples, batch_status,
review_required, confirmed_cause.

Rules:
1. Use only information in the source.
2. Do not invent missing values.
3. Use null for unknown values.
4. Use integers for numerical counts.
5. Use booleans for true/false fields.
6. Flag ambiguity for human review.
7. Do not infer a root cause.

Source note:
[PASTE INSPECTION NOTE]

Accomplishment: Produce a structured inspection record and explain how you would validate it before allowing downstream use.

↑ Back to Contents

10. Student and Practitioner Project

Mini Project: AI Quality Report Extractor

Objective: Build or prototype an application that converts inspection notes into validated structured records.

Project requirements

  1. Create 20 fictional inspection reports with varied wording.
  2. Define a JSON Schema for the target records.
  3. Build a structured extraction workflow.
  4. Validate every generated record.
  5. Compare extracted fields with manually prepared reference answers.
  6. Test missing values, ambiguous language, and conflicting statements.
  7. Record validation failures and extraction errors.
  8. Route uncertain records to a simulated human-review queue.
  9. Estimate processing latency and token consumption.
  10. Document recommendations for safe production integration.

Suggested evaluation measures

MetricWhat It Measures
Schema adherence ratePercentage of responses matching the defined schema
Field accuracyPercentage of extracted fields matching reference values
Missing-value accuracyCorrect handling of unavailable information
Unsupported-value rateFrequency of values not supported by the source
Review-routing accuracyWhether uncertain cases are correctly flagged
LatencyTime needed to process a report

Deliverable: A working prototype or design, sample structured records, validation results, and a short engineering recommendation.

↑ Back to Contents

11. Check Your Understanding

  1. Why are free-form AI responses difficult to integrate into software workflows?
  2. What is the difference between JSON validity and schema validity?
  3. Can a schema-valid response still be factually incorrect?
  4. How should missing information be represented?
  5. How are structured outputs related to function calling?
  6. What is the role of business-rule validation?
  7. Why should critical decisions require appropriate oversight?
  8. How would you evaluate a structured extraction application?

Reflection: If an AI model generates perfectly formatted JSON containing one incorrect batch identifier, has the structured-output system succeeded? Which checks would reveal the problem?

↑ Back to Contents

12. Active Connections

Coming next — #008: Tool Calling: Connecting AI Models to Real-World Actions.

↑ Back to Contents

13. References and Further Reading

  1. OpenAI — Structured Outputs
  2. JSON Schema — Getting Started
  3. Pydantic — Data Validation
  4. OpenAI — Function Calling

API capabilities and supported schema features vary. Consult current provider documentation before implementation.


Final Takeaway

Structured outputs make AI responses usable by software. Reliable AI engineering adds validation, evidence checking, and appropriate authorization before those responses become operational actions.

AI Engineering — Active Concepts & Practices
Active Concept #007 — Structured Outputs

AIYING — Accomplishing with AI

Understand → Connect → Apply → Accomplish

AI Engineering — Living Glossary #018 | Structured Outputs: Making AI Responses Machine-Readable and Verifiable

AI Engineering — Living Glossary #018

Lesson 18 | Chapter 3 Finale

Structured Outputs



Making AI Responses Machine-Readable and Verifiable

Chapter 3: Connecting AI to Tools, Workflows, and Agents

Understand the Term. Connect the Technology. Apply the Knowledge.

The Problem: A Correct Answer That Breaks the System

An accounts-payable team introduces an AI assistant to extract information from supplier invoices. The assistant reads an invoice and replies:

The invoice is from Northstar Components. It is for ₹48,500 and is due on 30 November 2026.

The answer looks useful to a human. But the accounting application expects an invoice number, supplier identifier, amount as a number, currency code, and due date in a specific format.

A human can interpret the response. Software should not have to guess where one field ends and another begins.

The engineer therefore changes the design: the AI must return data that conforms to a predefined schema.

Engineering insight: Generating the right words and generating a reliable software interface are different tasks.
↑ Back to contents

1. What Are Structured Outputs?

Structured outputs are AI-generated responses required to follow a defined data structure, typically specified using a schema.

Instead of producing unrestricted prose, the model produces data that an application can parse and validate.

Common representations include JSON objects, typed records, arrays, enumerated values, and other machine-readable formats.

Example

{ "invoice_number": "INV-2048", "supplier": "Northstar Components", "amount": 48500.00, "currency": "INR", "due_date": "2026-11-30", "requires_review": false }

The response now contains named fields, predictable data types, and a standardized date.

However, a valid structure does not prove that the invoice number, amount, or date was extracted correctly.

Critical distinction: Schema validity is not factual accuracy. Both must be checked separately.
↑ Back to contents

2. Why AI Engineers Need Structured Outputs

AI engineering increasingly involves connecting language models to conventional software systems. These systems expect predictable interfaces.

  • Integration: Applications can consume named fields without interpreting prose.
  • Automation: Workflows can route cases using explicit classifications and values.
  • Validation: Programs can reject missing, malformed, or unexpected data.
  • Testing: Outputs can be compared against known reference records.
  • Observability: Engineers can track failures by field and schema version.
  • Governance: Data contracts make downstream responsibilities clearer.

Structured outputs are especially valuable when an AI response triggers another system, creates a database record, or informs a consequential decision.

↑ Back to contents

3. Understanding the Data Contract

A schema defines the shape and constraints of expected data.

It can specify field names, data types, required properties, allowed values, nested objects, and restrictions on additional fields.

Illustrative JSON Schema

{ "type": "object", "properties": { "invoice_number": { "type": "string" }, "amount": { "type": "number" }, "currency": { "type": "string", "enum": ["INR", "USD", "EUR"] }, "due_date": { "type": ["string", "null"] }, "requires_review": { "type": "boolean" } }, "required": [ "invoice_number", "amount", "currency", "due_date", "requires_review" ], "additionalProperties": false }

This schema requires every listed field, restricts the currency to three codes, and prevents undeclared properties.

The due date is nullable because the source document may not contain one. A production application should also validate its date format.

Different model providers support different subsets of JSON Schema. The schema must be designed for the selected API's supported structured-output mode.

Design principle: The schema is an interface contract, not a substitute for business rules.
↑ Back to contents

4. How Structured Outputs Work

Step 1 — Define: The application defines its required schema.

Step 2 — Request: The application supplies the task, source content, and output contract to the model.

Step 3 — Generate: The model produces a structured response. Supported constrained-generation modes can restrict the possible output format.

Step 4 — Validate: Application code checks the output against the schema and business constraints.

Step 5 — Verify: Relevant values are checked against source evidence or authoritative records.

Step 6 — Act: The application accepts, rejects, retries, or escalates the result.

A production implementation must also handle refusals, incomplete responses, timeouts, unsupported schemas, and API-specific failure conditions.

The application—not the language model— ultimately decides whether the output is acceptable for downstream use.

↑ Back to contents

5. Approaches and Implementation Patterns

A. Prompt-Only Formatting

The prompt asks the model to return JSON. This is easy to prototype but does not provide a strong structural guarantee.

B. JSON-Format Mode

Some APIs provide a mode intended to produce syntactically valid JSON. Valid JSON alone does not guarantee the required fields or types.

C. Schema-Constrained Generation

Supported APIs can constrain generation to match a supplied schema or supported schema subset. This offers stronger structural reliability than instructions alone.

D. Application-Side Validation

The application parses and validates the returned object, regardless of the model's generation mode.

E. Validate, Repair, or Escalate

Invalid results can trigger a bounded retry, a correction request, a fallback workflow, or human review.

Repeated retries should not be unlimited: they increase cost and latency without guaranteeing correctness.

↑ Back to contents

6. Structured Outputs vs. Related Concepts

Concept Main Purpose Key Distinction
Prompt Engineering Guide model behavior Instructions alone do not enforce a schema
JSON Mode Produce JSON syntax Valid JSON may violate the expected schema
Structured Outputs Conform to a data contract Focuses on predictable response structure
Tool Calling Propose an external operation Tool arguments can be structured, but execution is separate
Guardrails Constrain unsafe or invalid behavior Schema checks cover only part of the risk
Grounding Connect claims to evidence Addresses factual support, not merely formatting

A model can return perfectly valid JSON containing an incorrect invoice total. Conversely, a factually correct explanation may be impossible for an application to parse.

Reliable systems need both structural correctness and factual verification.

↑ Back to contents

7. Production Architecture

Source Document | v Document Extraction / OCR | v AI Model + Output Schema | v Structured Response | v Schema Validator | v Business Rule Validator | v Source / Record Verification | +---- Failure ----> Retry or Review | v Authorized Application Action | v Audit Log and Monitoring

This architecture separates generation, validation, verification, authorization, and execution.

It also makes failures easier to diagnose: a parsing error is different from an incorrect extracted value or an unauthorized downstream action.

↑ Back to contents

8. Reliability, Safety, and Security

Schema Validity

Check field presence, data types, enumerations, nesting, and unexpected keys.

Semantic Validity

Check whether values make sense. An invoice amount cannot be negative unless the supported document type permits credits or adjustments.

Evidence Verification

Compare extracted values with the original document or trusted systems. A model's confidence claim is not independent evidence.

Prompt Injection

Documents may contain instructions attempting to influence the model. Treat document text as untrusted data, not as authority to change the workflow.

Authorization

Even valid structured data must not automatically authorize payments, record changes, or external communication.

Operational Controls

  • Set maximum retry counts and timeouts.
  • Version schemas and record compatibility changes.
  • Use least-privilege access for downstream systems.
  • Log validation outcomes without unnecessarily exposing sensitive data.
  • Escalate ambiguous or high-risk cases.
Remember: A valid JSON object is not a security approval, a factual guarantee, or permission to execute an action.
↑ Back to contents

9. Industry Applications

Industry Structured Output Downstream Use
Finance Invoice fields Validation and payment review
Customer Support Category, priority, summary Ticket routing
Manufacturing Defect classification Quality workflow
Healthcare Administration Document metadata Administrative processing with appropriate controls
Cybersecurity Alert indicators and severity Analyst triage
Human Resources Application metadata Administrative organization and review

The recurring pattern is the same: language understanding is converted into a predictable software interface.

↑ Back to contents

10. Industry Case: Invoice Processing

Illustrative enterprise scenario, not a claim about a specific company.

The Business Problem

A company receives thousands of supplier invoices in different layouts. Manual entry is slow, while ordinary OCR provides text without always identifying business meaning.

The Proposed AI System

  1. Receive a supplier invoice.
  2. Extract text and document layout information.
  3. Ask the model for fields matching an invoice schema.
  4. Validate the returned structure.
  5. Check arithmetic and required business fields.
  6. Match supplier and purchase-order information.
  7. Route mismatches to a human reviewer.
  8. Submit approved records to the accounting system.

Example Exception

The invoice states a total of ₹48,500. The model returns the same amount, but the purchase order authorizes ₹45,800.

The structured response is valid. The extracted amount may also be accurate. Nevertheless, the transaction should be flagged because it does not match the purchasing record.

What the Engineer Learns

Structural correctness, extraction accuracy, business eligibility, and execution authorization are separate decisions.

Case insight: Structured outputs make exceptions detectable; they do not eliminate the need to investigate exceptions.
↑ Back to contents

11. Engineering Design Decisions

Before implementing structured outputs, the engineer must decide:

  1. Which fields are genuinely required by downstream applications?
  2. Should an unknown value be null, omitted, or an explicit status?
  3. Which fields require controlled enumerations?
  4. Which constraints belong in the schema versus business validation?
  5. What happens when the model refuses, times out, or returns incomplete data?
  6. When is retry appropriate, and when should the system escalate?
  7. How will schema versions be managed across multiple consuming services?
  8. Which actions require human approval?

A good schema should be sufficiently precise for dependable integration without forcing the model to invent information that the source does not contain.

↑ Back to contents

12. Hands-On Mini-Project

Build a Structured Support-Ticket Classifier

Objective: Convert an unstructured customer message into a validated support record.

Input

I cannot sign in to my account after resetting my password. I need access before tomorrow's client meeting.

Required Output

{ "category": "access", "priority": "high", "summary": "User cannot sign in after password reset", "needs_human_review": false }

This is an illustrative expected result. The actual priority must follow a documented support policy.

Student Tasks

  1. Define a schema with category, priority, summary, and needs_human_review.
  2. Restrict category to access, billing, technical, or other.
  3. Restrict priority to low, medium, or high.
  4. Submit at least 20 varied test messages to an AI model.
  5. Validate each output with a JSON Schema validator.
  6. Compare the classification with human-reviewed expected labels.
  7. Record failures and improve the schema or instructions.

Python Validation Example

The following example validates a response already received from a model. It does not make a model API call.

# Install once: # pip install jsonschema from jsonschema import validate, ValidationError schema = { "type": "object", "properties": { "category": { "type": "string", "enum": [ "access", "billing", "technical", "other" ] }, "priority": { "type": "string", "enum": ["low", "medium", "high"] }, "summary": { "type": "string", "minLength": 1 }, "needs_human_review": { "type": "boolean" } }, "required": [ "category", "priority", "summary", "needs_human_review" ], "additionalProperties": False } result = { "category": "access", "priority": "high", "summary": "Cannot sign in after reset", "needs_human_review": False } try: validate(instance=result, schema=schema) print("Schema valid") except ValidationError as error: print("Schema invalid:", error.message)

Extend the project by rejecting empty summaries, checking ticket categories against policy, and routing uncertain classifications to review.

↑ Back to contents

13. Evaluation and Acceptance Criteria

Metric What It Measures Illustrative Target
Schema compliance Percentage passing schema validation 100% before downstream acceptance
Category accuracy Agreement with reviewed labels At least 90% in the exercise
Priority accuracy Agreement with defined policy At least 90% in the exercise
Escalation recall Fraction of review-required cases flagged 100% for designated critical test cases
Retry rate Fraction requiring another attempt Measure and minimize
Latency Time to a validated result Set according to application needs

These are learning targets, not universal production benchmarks. A real deployment requires larger representative datasets, failure analysis, and risk-based thresholds.

The student should report results separately for syntax, schema compliance, classification quality, and business-rule compliance.

↑ Back to contents

14. Connected Living Glossary Terms

↑ Back to contents

15. Living Update

Structured-output capabilities continue to evolve across AI platforms. Engineers should periodically review:

  • Supported schema features and restrictions.
  • Constrained-generation guarantees.
  • Handling of refusals and incomplete responses.
  • Streaming behavior and partial results.
  • SDK validation and parsing capabilities.
  • Compatibility with tool calling and agent systems.

Update discipline: Test schema behavior against the actual model and API version used in production. Do not assume that a provider's entire JSON Schema specification is supported.

↑ Back to contents

16. Key Takeaway and One Action

Understand the Term: Structured outputs require AI responses to follow a defined data contract.

Connect the Technology: Schemas connect language-model generation to conventional software systems.

Apply the Knowledge: Validate the structure, verify the facts, and authorize actions separately.

One Action: Take one AI task that currently returns prose. Design a schema, test 20 examples, and measure the failure rate.

A well-formed response is ready to be checked—not automatically ready to be trusted.

↑ Back to contents

17. References and Further Learning

  1. JSON Schema — Official Documentation
  2. OpenAI — Structured Outputs
  3. Anthropic — Developer Documentation
  4. OWASP — Top 10 for LLM Applications
  5. NIST — AI Risk Management Framework
  6. Python jsonschema — Documentation
↑ Back to contents

AIYING — Accomplishing with AI

The Language of AI Engineering
The Terms AI Engineers Must Truly Understand

One Term. One Industry Connection. One Practical Insight. One Action.

Living Glossary #018 | Chapter 3 Complete | Lesson 18 of 24

Sunday, October 25, 2026

DO this AI Thing Now #015 | Structured Outputs — Stop Broken JSON in AI Applications

DO this AI Thing Now | #015 | INNOVATION

FOR AI ENGINEERS & DEVELOPERS

Stop Broken JSON! Build Reliable AI Applications with Structured Outputs

Your LLM generates JSON. But can your application depend on its structure? Learn how to enforce a schema, validate responses, and handle failures.

1. The Real Engineering Problem

Large language models often produce useful information in unpredictable formats. A response may contain extra commentary, missing fields, inconsistent data types, or JSON that cannot be parsed.

These issues become important when LLM outputs feed APIs, databases, dashboards, automation workflows, or AI agents.

Unreliable output:
{
  task: "Write report",
  priority: high,
  valid: true,
}

This is not valid JSON. Property names must be quoted, the value high is not a valid unquoted JSON value, and the final property has a trailing comma.

Valid structured result:
{
  "task": "Write report",
  "priority": 1,
  "valid": true
}

The second example is valid JSON and matches the field types in our example schema. However, formatting correctness does not prove that the generated information is factually accurate.

2. What Are Structured Outputs?

Structured Outputs allow developers to specify an expected response structure using a supported JSON Schema and request that a compatible model produce data conforming to that structure.

This is different from merely including the instruction "Please respond in JSON" in a prompt.

  • Prompt-only JSON: Asks the model to follow a format.
  • JSON mode: Helps ensure syntactically valid JSON, but does not necessarily enforce your complete schema.
  • Structured Outputs: Uses supported schema constraints to enforce the expected response structure.
  • Application validation: Independently checks the result and its business rules.

3. Practical Example: AI Task Extraction

Imagine an application that reads a short message and extracts a task, priority, and validity flag.

Input:

"Please prepare the quarterly report. It is urgent."

Desired output:

{
  "task": "Prepare the quarterly report",
  "priority": 1,
  "valid": true
}

For this demonstration, priority 1 means high urgency, priority 2 means normal urgency, and priority 3 means low urgency. The valid field indicates whether the input contains an actionable task. These are application-specific conventions.

4. Define the JSON Schema

Here is a schema defining the exact fields and data types.

{
  "type": "object",
  "properties": {
    "task": {
      "type": "string"
    },
    "priority": {
      "type": "integer",
      "enum": [1, 2, 3]
    },
    "valid": {
      "type": "boolean"
    }
  },
  "required": [
    "task",
    "priority",
    "valid"
  ],
  "additionalProperties": false
}

This schema specifies three required fields, constrains priority to the values 1, 2, or 3, and disallows unexpected properties.

5. Hands-On Python Demonstration

The following example uses the OpenAI Python SDK and a compatible structured-output model. It also performs independent application-side validation.

Install dependencies:

pip install -U openai jsonschema

Configure your OPENAI_API_KEY as an environment variable. Never place API keys directly inside published source code.

Python example:

import os
import json

from openai import OpenAI
from jsonschema import validate

client = OpenAI(
    api_key=os.environ["OPENAI_API_KEY"]
)

schema = {
    "type": "object",
    "properties": {
        "task": {"type": "string"},
        "priority": {
            "type": "integer",
            "enum": [1, 2, 3]
        },
        "valid": {"type": "boolean"}
    },
    "required": [
        "task", "priority", "valid"
    ],
    "additionalProperties": False
}

response = client.responses.create(
    model="gpt-4.1-mini",
    instructions=(
        "Extract the actionable task. "
        "Use priority 1 for urgent, "
        "2 for normal, 3 for low. "
        "Set valid to true if an "
        "actionable task exists. "
        "Otherwise use an empty task "
        "and set valid to false."
    ),
    input=(
        "Please prepare the quarterly "
        "report. It is urgent."
    ),
    text={
        "format": {
            "type": "json_schema",
            "name": "task_extraction",
            "strict": True,
            "schema": schema
        }
    }
)

if response.status != "completed":
    raise RuntimeError(
        f"Response status: {response.status}"
    )

if not response.output_text:
    raise RuntimeError(
        "No structured text returned"
    )

data = json.loads(response.output_text)

validate(instance=data, schema=schema)

if data["valid"] and not data["task"].strip():
    raise ValueError(
        "Valid tasks must not be empty"
    )

print(json.dumps(data, indent=2))

This example uses the Responses API structured-output configuration. It assumes the request completes successfully and returns text rather than a refusal. Production systems must also handle API errors, refusals, incomplete responses, and retry policies. Confirm current model support and API syntax in the official documentation.

Illustrative result:

{
  "task": "Prepare the quarterly report",
  "priority": 1,
  "valid": true
}

The output above illustrates the expected result; it is not a claim that the example was executed during publication.

6. Test the Output

Reliable AI engineering requires more than one successful example. Test both the expected structure and your application rules.

from jsonschema import (
    validate,
    ValidationError
)

def is_schema_valid(value):
    try:
        validate(
            instance=value,
            schema=schema
        )
        return True
    except ValidationError:
        return False

assert is_schema_valid({
    "task": "Write report",
    "priority": 1,
    "valid": True
})

assert not is_schema_valid({
    "task": "Write report",
    "priority": "high",
    "valid": True
})

assert not is_schema_valid({
    "task": "Write report",
    "priority": 1
})

assert not is_schema_valid({
    "task": "Write report",
    "priority": 1,
    "valid": True,
    "extra": "unexpected"
})

print("Schema tests passed")

These tests check a valid response, an incorrect type, a missing required field, and an unexpected extra property.

7. Where Structured Outputs Are Useful

Document Processing

Extract invoice fields, dates, categories, and entities into defined structures.

AI Agents

Produce structured plans, classifications, and intermediate results for workflows.

Business Applications

Generate task records, support classifications, and CRM-ready information.

Evaluation Systems

Collect model assessments and test outcomes using consistent field definitions.

8. Engineering Limitations

Structured Outputs are useful, but they are not a complete reliability or security solution.

  • Semantic errors: A schema-valid priority may still be wrong.
  • Refusals: Safety-related refusals may not follow the requested schema.
  • Incomplete generation: Token limits or interruptions may prevent a complete result.
  • Schema support: Not every JSON Schema feature is supported by every model or API.
  • Security: Structured outputs do not eliminate prompt injection or unsafe downstream actions.
  • Business rules: Additional validation may be necessary for dates, identifiers, permissions, and domain-specific constraints.
  • Cost and latency: Model selection and schema complexity may affect performance.

9. Practical Engineering Checklist

☐ Define the exact data contract.

☐ Choose a compatible model and API.

☐ Enable schema-enforced structured outputs.

☐ Validate the returned JSON independently.

☐ Check semantic and business-rule correctness.

☐ Handle refusals, incomplete outputs, and API errors.

☐ Test valid, invalid, and adversarial inputs.

☐ Monitor failures and maintain versioned schemas.

10. Further Learning

Official OpenAI Structured Outputs Guide:
https://platform.openai.com/docs/guides/structured-outputs

OpenAI API Reference:
Responses API Reference

JSON Schema Documentation:
https://json-schema.org/

11. Your AI Action Now

10-Minute Challenge
  1. Choose one LLM feature in an application or prototype.
  2. Define three output fields and their expected types.
  3. Enforce the structure with a compatible API.
  4. Test one valid and three invalid responses.
  5. Document what schema validation does not catch.

One schema. One test. One more reliable AI integration.

DO this AI Thing Now

Less AI talk. More AI action.

Explore practical AI actions, tools, and innovations for students, teachers, professionals, developers, engineers, researchers, and organizations.

Explore the YouTube Playlist

AIYING — Accomplishing with AI
https://dastikop.blogspot.com

Accomplish with AI

Powered by Blogger.

Featured post

AI Engineering Hands-On Lab #001 — Build an AI Answer Reliability Test Bench Without Code

AIYING | Daily 24 — Post 009 AI Engineering Hands-On Lab #001 Build an AI Answer Reliability Test Bench — Without Writing Code Lea...

Search This Blog

List of blogs

Search This Blog

About

Translate

Instant Stories

Read in Your Language

Test

share this

ShareThis

Popular Posts