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.
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
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.
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 contents3. 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
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.
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 contents5. 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 contents6. 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 contents7. Production Architecture
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 contents8. 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.
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 contents10. 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
- Receive a supplier invoice.
- Extract text and document layout information.
- Ask the model for fields matching an invoice schema.
- Validate the returned structure.
- Check arithmetic and required business fields.
- Match supplier and purchase-order information.
- Route mismatches to a human reviewer.
- 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.
11. Engineering Design Decisions
Before implementing structured outputs, the engineer must decide:
- Which fields are genuinely required by downstream applications?
- Should an unknown value be null, omitted, or an explicit status?
- Which fields require controlled enumerations?
- Which constraints belong in the schema versus business validation?
- What happens when the model refuses, times out, or returns incomplete data?
- When is retry appropriate, and when should the system escalate?
- How will schema versions be managed across multiple consuming services?
- 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 contents12. 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
This is an illustrative expected result. The actual priority must follow a documented support policy.
Student Tasks
- Define a schema with category, priority, summary, and needs_human_review.
- Restrict category to access, billing, technical, or other.
- Restrict priority to low, medium, or high.
- Submit at least 20 varied test messages to an AI model.
- Validate each output with a JSON Schema validator.
- Compare the classification with human-reviewed expected labels.
- 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.
Extend the project by rejecting empty summaries, checking ticket categories against policy, and routing uncertain classifications to review.
↑ Back to contents13. 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 contents14. Connected Living Glossary Terms
- #006 — Prompt Engineering : Define the task and output expectations.
- #007 — Evals : Measure structural and semantic correctness.
- #009 — Grounding : Connect extracted facts to evidence.
- #010 — Guardrails : Enforce validation and safety boundaries.
- #011 — Observability : Monitor failures and operational quality.
- #013 — Tool Calling : Use structured arguments for tool requests.
- #014 — Workflows : Pass validated data between processing steps.
- #017 — Model Context Protocol : Standardize how applications connect to external tools and context sources.
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 contents16. 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 contents17. References and Further Learning
- JSON Schema — Official Documentation
- OpenAI — Structured Outputs
- Anthropic — Developer Documentation
- OWASP — Top 10 for LLM Applications
- NIST — AI Risk Management Framework
- Python jsonschema — Documentation




