If your application asks an LLM to return JSON, getting valid JSON is only half the problem. The model might return the right format but omit a field your code depends on, use an unexpected category, or put a paragraph where your application expects a string.
The better solution is to define the structure before asking the model to generate data. With Structured Outputs, you can give an LLM a JSON Schema and constrain its response to that schema. In Python, the OpenAI SDK can use a Pydantic model to define the structure and parse the result into a typed object.
In this tutorial, we'll build a small support-ticket extraction tool. It will read a customer message and return a consistent JSON object containing a summary, category, priority, tags, and whether a human should review the ticket. You'll learn how to define the schema, call the model, handle missing results, and test the data your application receives.
Table of Contents
Why Asking for JSON Is Not Enough
Step 1: Set Up the Python Project
Step 2: Define a Pydantic Schema
Step 3: Generate Structured Output With an LLM
Step 4: Inspect and Use the Parsed Result
Step 5: Test the Structure and Handle Edge Cases
When Structured Outputs Are Not Enough
Why Asking for JSON Is Not Enough
A basic prompt might say, "Return the answer as JSON." This can work for simple experiments, but it does not define a reliable contract between the model and your application.
For example, one response might contain "priority": "high", while another returns "priority": 3. A third might omit the priority field entirely. All three could be valid JSON, but only one may match what your application expects.
There are two approaches worth distinguishing:
JSON Mode: Helps ensure the response is valid JSON, but does not guarantee that it follows your specific field definitions.
Structured Outputs: Uses a JSON Schema to constrain the response to a defined structure, including supported field types and enum values.
If your application needs predictable fields, Structured Outputs is generally the better starting point when the selected model supports it. It does not guarantee that the extracted information is factually correct, however. Schema compliance and content accuracy are two different problems.
Step 1: Set Up the Python Project
Create a project directory and activate a virtual environment:
mkdir structured-llm-output
cd structured-llm-output
python -m venv .venv
# macOS / Linux
source .venv/bin/activate
# Windows PowerShell
.venv\Scripts\Activate.ps1Install the required packages:
pip install openai pydantic python-dotenvCreate a .env file:
OPENAI_API_KEY=your_api_key_here
OPENAI_MODEL=gpt-5.5Replace the example key with your own API key. Add .env to .gitignore so credentials are not committed to your repository. The model name is configurable: use a model available to your API account that supports Structured Outputs.

Step 2: Define a Pydantic Schema
Before calling the model, decide exactly what information your application needs. For our support-ticket example, we want five fields:
Field | Type | Purpose |
|---|---|---|
| String | Short description of the issue |
| Enum | Billing, technical, account, or other |
| Enum | Low, normal, high, or urgent |
| Array of strings | Useful classification labels |
| Boolean | Whether a person should review it |
Create schemas.py and define the model:
from typing import Literal
from pydantic import BaseModel, Field
class SupportTicket(BaseModel):
summary: str = Field(
description="A concise summary of the customer's issue"
)
category: Literal[
"billing",
"technical",
"account",
"other"
]
priority: Literal[
"low",
"normal",
"high",
"urgent"
]
tags: list[str] = Field(
description="Short labels describing the issue"
)
needs_human: bool = Field(
description="Whether a human support agent should review it"
)The important part is that the schema describes the output your application expects, not just the general topic of the prompt.
Using Literal limits the category and priority to known values. That is much safer than accepting arbitrary strings and trying to interpret them later. The field descriptions also help explain what each property means.

Step 3: Generate Structured Output With an LLM
Now create main.py. The OpenAI Python SDK provides a responses.parse() helper that accepts a Pydantic model through the text_format parameter.
import os
from dotenv import load_dotenv
from openai import OpenAI
from schemas import SupportTicket
load_dotenv()
client = OpenAI()
MODEL = os.getenv("OPENAI_MODEL", "gpt-5.5")
def extract_ticket(message: str) -> SupportTicket:
response = client.responses.parse(
model=MODEL,
instructions=(
"Extract support ticket information from the "
"customer message. Use only the provided message. "
"Do not invent customer details."
),
input=message,
text_format=SupportTicket,
)
result = response.output_parsed
if result is None:
raise ValueError(
"The model did not return a parsed ticket."
)
return result
if __name__ == "__main__":
customer_message = """
I was charged twice for my monthly subscription.
I only placed one order, and I need the extra charge
refunded as soon as possible.
"""
ticket = extract_ticket(customer_message)
print(ticket.model_dump_json(indent=2))Notice what we did not do: we did not ask the model to write JSON and then manually remove Markdown fences or pass a text string into json.loads().
Instead, the SDK uses the Pydantic model to provide the output schema and parse the result. The output_parsed property gives us a SupportTicket object when parsing succeeds.
Run the script:
python main.pyA successful result should follow this general structure:
{
"summary": "Customer reports a duplicate subscription charge.",
"category": "billing",
"priority": "high",
"tags": ["duplicate charge", "subscription", "refund"],
"needs_human": true
}The exact wording and classification are generated by the model, so your output may differ. What matters is that the returned data follows the defined schema.
Step 4: Inspect and Use the Parsed Result
Once you have a parsed object, you can use its fields directly in Python:
ticket = extract_ticket(customer_message)
print(ticket.category)
print(ticket.priority)
if ticket.needs_human:
print("Send ticket for human review")
if ticket.category == "billing":
print("Route to billing support")This is where structured output becomes useful. Your application can route a ticket, display a summary, or store classification fields without repeatedly interpreting an unstructured paragraph.
You can also convert the object into a dictionary:
ticket_data = ticket.model_dump()Or serialize it into JSON:
ticket_json = ticket.model_dump_json(indent=2)Remember that predictable structure does not mean the model has verified the customer's claims. If a classification triggers refunds, account changes, or other consequential actions, add business rules and human approval where appropriate.
Step 5: Test the Structure and Handle Edge Cases
Do not test only one well-written support message. Try different inputs, including a technical issue, an unclear complaint, and a message with multiple problems.
You should also test your schema independently of the model call:
from pydantic import ValidationError
from schemas import SupportTicket
valid_ticket = {
"summary": "Cannot reset account password.",
"category": "account",
"priority": "normal",
"tags": ["password", "login"],
"needs_human": False
}
ticket = SupportTicket.model_validate(valid_ticket)
print(ticket.category)
invalid_ticket = {
"summary": "Payment failed.",
"category": "payments",
"priority": "normal",
"tags": [],
"needs_human": False
}
try:
SupportTicket.model_validate(invalid_ticket)
except ValidationError as exc:
print("Validation failed:")
print(exc)The invalid example uses "payments", which is not one of the allowed category values. Pydantic should reject it.
There are also API-level cases to handle. A model may refuse a request, or a response may be incomplete because generation was interrupted or reached a limit. A missing output_parsed value should not be treated as a successful extraction. Inspect the response and handle refusal and incomplete-output cases explicitly in your application.

When Structured Outputs Are Not Enough
Structured Outputs solves an important formatting and schema problem, but it does not eliminate every validation requirement.
Business rules: A priority value may be structurally valid but still be an inappropriate classification.
Missing information: Decide how your schema represents unknown or unavailable values instead of encouraging the model to guess.
Schema limitations: Strict Structured Outputs supports a subset of JSON Schema, so check the official documentation before using advanced constraints.
Model compatibility: Confirm that the model you select supports the feature and that your SDK version supports the parsing helper.
Keep the schema focused. Adding dozens of fields does not automatically improve extraction quality. Start with the information your application actually uses, then add fields when testing shows a real need.
Conclusion: Define the Data Contract Before You Ask the Model
If your application depends on predictable JSON, do not rely on prompt wording alone. Define the expected structure with Pydantic, use Structured Outputs to constrain the model response, and work with the parsed object rather than treating generated text as trusted data.
Start with a small schema, test valid and invalid inputs, and add business validation before using the result to trigger important actions. This gives your LLM application a much more dependable interface between generated language and ordinary Python code.
Build it. Break it. Understand it. Fix it.
