LLM Structured Output
Overview
Extract typed, validated data from LLM API responses instead of parsing free-text. This skill covers the three main provider approaches — OpenAI's response_format with JSON Schema, Anthropic's tool_use block for structured extraction, and Google's responseSchema in Gemini — plus constrained decoding for local models. You will learn when each approach works, when it breaks, and how to build retry logic around schema validation failures that every production system encounters.
When to Use
Use this skill when:
- The user needs to extract structured data (JSON objects, arrays, enums) from an LLM response.
- The user is building a pipeline where LLM output feeds directly into code (database writes, API calls, UI rendering).
- The user asks about
response_format, json_mode, json_object, or json_schema in OpenAI.
- The user asks about using Anthropic's
tool_use or tool_result blocks for data extraction (not for actual tool execution).
- The user asks about Zod schemas with
zodResponseFormat() from the openai npm package.
- The user needs to parse LLM output into Pydantic models using
instructor, marvin, or manual validation.
- The user is getting malformed JSON, missing fields, or wrong types from LLM responses and needs a fix.
- The user asks about
controlled generation, constrained decoding, or grammar-based sampling in local models.
Do NOT use this skill when:
- The user wants free-form text generation (summaries, essays, chat).
- The user is asking about Zod for form validation or API input validation (use
zod-validation-expert instead).
- The user needs prompt engineering for better text quality (not structure).
- The user wants to call real external tools/APIs (this skill covers using
tool_use as a structured output hack, not actual tool orchestration).
Prerequisites
- An API key for the target provider (OpenAI, Anthropic, or Google). Use placeholder
YOUR_KEY in examples — never commit live secrets.
- Python 3.10+ with
openai, anthropic, or google-generativeai SDK installed, or Node.js 18+ with the openai npm package.
- For Pydantic workflows:
pip install pydantic openai instructor (or marvin if preferred).
- For Zod workflows:
npm install openai zod.
- For local model constrained decoding:
llama.cpp (GBNF grammars) or vLLM (--json-schema flag).
- Windows host is primary. Use PowerShell for all CLI commands. Path separators in examples use backslash on Windows.
Procedure
Step 1 — Identify the target schema
Ask the user what fields they need extracted. Define every field with its type, whether it is required or optional, and valid enum values if applicable. Do not proceed without a concrete schema.
Step 2 — Choose the provider-appropriate method
| Provider |
Method |
Key Setting |
| OpenAI (gpt-4o, gpt-4o-mini) |
response_format: { type: "json_schema", json_schema: { ... } } |
Set "strict": true for constrained decoding |
| Anthropic (Claude) |
Define a single tool with target schema as input_schema |
Set tool_choice: { type: "tool", name: "extract_data" } |
| Google (Gemini) |
generationConfig.responseSchema + responseMimeType: "application/json" |
Provide a JSON Schema object |
| Local models (llama.cpp, vLLM) |
GBNF grammars or --json-schema flag |
Constrained decoding at token level |
Step 3 — Write the schema in the user's language
- Python: Define a Pydantic
BaseModel.
- TypeScript: Define a Zod schema and convert with
zodResponseFormat().
- Raw API calls: Write JSON Schema directly.
Step 4 — Include field-level descriptions in the schema
Every field must have a description string that tells the model what to put there. Models use these descriptions as implicit prompt instructions. A field described as "The user's sentiment as positive, negative, or neutral" produces better results than a bare sentiment: str with no context.
Step 5 — Set the system prompt to reinforce structure
Tell the model its job is data extraction, not conversation.
Example system prompt:
You are a data extraction system. Analyze the input and return the requested fields. Do not include explanations outside the JSON structure.
Step 6 — Enable strict mode (OpenAI)
If using OpenAI's json_schema mode, set "strict": true in the schema definition. This activates constrained decoding where the model can only output tokens that conform to the schema. Without strict: true, the model may still produce invalid JSON.
Step 7 — Extract data from the correct block (Anthropic)
If using Anthropic's tool_use approach, extract the structured data from response.content by finding the block where type == "tool_use" and reading its input field. Do not parse the text blocks — the structured data lives exclusively in the tool_use block.
Step 8 — Validate the response in application code
Even with constrained decoding, validate with Pydantic's model_validate() or Zod's .parse() before passing data downstream. This catches semantic issues (empty strings, out-of-range numbers) that schema conformance alone cannot prevent.
Step 9 — Build a retry loop for validation failures
When validation fails, send the original input plus the failed output and the validation error back to the model with an instruction like:
Your previous output failed validation: {error}. Fix the output.
Cap retries at 3 attempts.
Step 10 — Log every structured output call
Log: the input, the raw response, the parsed result, and any validation errors. When structured output breaks in production, you need these logs to determine whether the failure was a schema design issue, a prompt issue, or a model regression.
Examples
Example 1: OpenAI Structured Outputs with Pydantic (Python)
from pydantic import BaseModel, Field
from openai import OpenAI
from enum import Enum
class Sentiment(str, Enum):
positive = "positive"
negative = "negative"
neutral = "neutral"
class ReviewAnalysis(BaseModel):
sentiment: Sentiment = Field(description="Overall sentiment of the review")
key_topics: list[str] = Field(description="Main topics mentioned, max 5")
purchase_intent: bool = Field(description="Whether the reviewer would buy again")
confidence_score: float = Field(ge=0.0, le=1.0, description="Model confidence 0-1")
client = OpenAI()
response = client.beta.chat.completions.parse(
model="gpt-4o-2024-08-06",
messages=[
{"role": "system", "content": "Extract structured review analysis."},
{"role": "user", "content": "This laptop is amazing. The battery lasts forever and the keyboard feels great. Definitely buying the next version."}
],
response_format=ReviewAnalysis,
)
result = response.choices[0].message.parsed
# result.sentiment == Sentiment.positive
# result.key_topics == ["battery life", "keyboard"]
# result.purchase_intent == True
Example 2: Anthropic tool_use for Structured Extraction (Python)
import anthropic
client = anthropic.Anthropic()
response = client.messages.create(
model="claude-sonnet-4-20250514",
max_tokens=1024,
system="You are a data extraction system. Use the provided tool to return structured data.",
tools=[{
"name": "extract_invoice",
"description": "Extract invoice fields from text",
"input_schema": {
"type": "object",
"properties": {
"vendor_name": {"type": "string", "description": "Company that issued the invoice"},
"total_amount": {"type": "number", "description": "Total amount in USD"},
"line_items": {
"type": "array",
"items": {
"type": "object",
"properties": {
"description": {"type": "string"},
"quantity": {"type": "integer"},
"unit_price": {"type": "number"}
},
"required": ["description", "quantity", "unit_price"]
}
}
},
"required": ["vendor_name", "total_amount", "line_items"]
}
}],
tool_choice={"type": "tool", "name": "extract_invoice"},
messages=[{"role": "user", "content": "Invoice from Acme Corp: 3x Widget A at $10 each, 1x Widget B at $25. Total: $55."}]
)
# Find the tool_use block — do NOT parse text blocks
tool_block = next(b for b in response.content if b.type == "tool_use")
invoice = tool_block.input
# invoice["vendor_name"] == "Acme Corp"
# invoice["total_amount"] == 55.0
Example 3: TypeScript with Zod + zodResponseFormat
import OpenAI from "openai";
import { z } from "zod";
import { zodResponseFormat } from "openai/helpers/zod";
const EventSchema = z.object({
event_name: z.string().describe("Name of the event"),
date: z.string().describe("ISO 8601 date string"),
location: z.string().describe("City and venue"),
attendee_count: z.number().int().describe("Expected number of attendees"),
is_virtual: z.boolean().describe("Whether the event is online-only"),
});
const client = new OpenAI();
const completion = await client.beta.chat.completions.parse({
model: "gpt-4o-2024-08-06",
messages: [
{ role: "system", content: "Extract event details from the text." },
{ role: "user", content: "Tech Summit 2025 in Austin at the Convention Center on March 15th. Expecting 2000 attendees, in-person only." },
],
response_format: zodResponseFormat(EventSchema, "event_extraction"),
});
const event = completion.choices[0].message.parsed;
// event.event_name === "Tech Summit 2025"
// event.is_virtual === false
Pitfalls
HARD RULES — never violate these
Never use response_format: { type: "json_object" } without a schema. This is OpenAI's legacy JSON mode — it guarantees valid JSON syntax but not schema conformance. The model can return {"result": "hello"} when you expected {"name": str, "age": int}. Always use json_schema with a full schema definition instead.
Never parse Anthropic's text blocks for structured data. When using tool_choice to force structured output, the data is in the tool_use content block, not in any text block. Parsing response.content[0].text will either return empty string or a conversational preamble — never the data you need.
Never define schema fields without descriptions. A field named status with no description can mean HTTP status, order status, or review status. Models use field descriptions as extraction instructions. Omitting them is equivalent to omitting half your prompt.
Never use additionalProperties: true in strict mode schemas. OpenAI's strict mode requires additionalProperties: false on every object in the schema. If you set it to true or omit it, the API rejects the request with a 400 error — not at response time. You will never get a response at all.
Never put extraction instructions only in the user message and not the system prompt. The system prompt has higher attention weight for behavioral instructions. Putting "extract the following fields" only in the user message alongside the source text forces the model to split attention between the instruction and the data. System prompt defines behavior; user message provides input data.
Never assume structured output means correct output. Constrained decoding guarantees the response matches the schema's types and structure. It does not guarantee the values are correct. A model can return {"sentiment": "positive"} for a negative review if the source text is ambiguous. Always validate semantics in application code after schema validation.
Never use recursive or deeply nested schemas without testing. Recursive types ($ref pointing to the same definition) and schemas deeper than 3 levels increase decoding latency significantly and raise the probability of the model hitting max_tokens before completing the JSON structure. Flatten nested schemas where possible.
Edge cases to watch for
Long source text exceeding context window. When the input text is too long, the model may truncate its reading and return incomplete extractions. Split long documents into chunks, extract from each chunk independently, then merge results in application code. Do not rely on the model to handle 50-page documents in a single call.
The model returns a refusal instead of structured data. OpenAI's structured output can return a refusal field when the model considers the request unsafe. Check response.choices[0].message.refusal before accessing .parsed. If refusal is not None, the parsed data will be None and accessing it throws an error.
Array fields returning empty when data exists. Models sometimes return [] for array fields when the source text contains the data but the field description is too vague. Fix by making the description prescriptive: "List of all product names mentioned in the text. Return at least one if any product is referenced.".
Enum values not matching due to casing. If you define an enum as ["Active", "Inactive"] but the model returns "active", validation fails. Either lowercase all enum values in the schema or add a normalization step before validation. OpenAI's strict mode respects exact casing; Anthropic may not.
Streaming with structured output. OpenAI supports streaming structured output where partial JSON arrives chunk by chunk. You cannot parse intermediate chunks as valid JSON. Use the openai SDK's built-in partial parsing or buffer chunks until the stream completes. Anthropic's tool_use blocks arrive complete in a single content_block_stop event — no partial assembly needed.
Verification
After implementing a structured output pipeline, verify correctness with these checks:
Schema conformance check — confirm the API accepts the schema:
# Python: run a single extraction and confirm no 400 error
python -c "from your_module import extract; print(extract('test input'))"
If you see a 400 Bad Request mentioning additionalProperties or strict, your schema is missing "additionalProperties": false on one or more objects.
Parsed result is not None:
result = response.choices[0].message.parsed
assert result is not None, "Parsed result is None — check for refusal or schema error"
Refusal check (OpenAI):
if response.choices[0].message.refusal is not None:
print(f"Model refused: {response.choices[0].message.refusal}")
# Do not proceed — handle safety refusal
Tool_use block exists (Anthropic):
tool_blocks = [b for b in response.content if b.type == "tool_use"]
assert len(tool_blocks) == 1, f"Expected 1 tool_use block, got {len(tool_blocks)}"
Semantic validation passes:
# Pydantic validation with constraints
validated = ReviewAnalysis.model_validate(result)
assert 0.0 <= validated.confidence_score <= 1.0
assert len(validated.key_topics) <= 5
Retry loop fires on bad output:
Inject a deliberately malformed response into your retry path and confirm the loop sends the validation error back to the model and retries up to 3 times.
Logs contain all four fields:
Confirm your log entries include: input text, raw API response, parsed result, and any validation errors. Without all four, production debugging is impossible.
Best Practices
Start with the simplest schema that solves the problem. Flat objects with 3–5 fields produce higher accuracy than nested schemas with 20+ fields. If you need complex data, extract in two passes: first extract top-level entities, then make a second call to extract details for each entity.
Use enums instead of free-form strings for categorical data. A field mood: str can return anything. A field mood: Literal["happy", "sad", "neutral", "angry"] constrains the model to exactly those values. This reduces downstream parsing logic to zero.
Pin the model version in production. gpt-4o is an alias that changes when OpenAI releases new versions. Structured output behavior can change between versions. Use gpt-4o-2024-08-06 explicitly so that your schema+prompt combination remains stable until you deliberately upgrade.
Test schema changes against 20+ real inputs before deploying. Schema changes (adding a field, changing a type, modifying a description) can break extraction on inputs that previously worked. Build a test suite of real inputs with expected outputs and run it on every schema change. This is the structured output equivalent of unit testing.
Use default values in Pydantic models for optional fields. When a field might not have relevant data in the source text, define it as Optional[str] = None in Pydantic or .optional() in Zod. Without defaults, the model is forced to hallucinate a value for fields where the source text has no answer.
Separate extraction schemas from application schemas. Your LLM extraction schema should match what the model can reliably produce. Your application database schema may have additional computed fields, foreign keys, or constraints. Map between them in application code — do not force the LLM to understand your database schema.
Limitations
- Use this skill only when the task clearly matches the scope described above.
- Do not treat the output as a substitute for environment-specific validation, testing, or expert review.
- Stop and ask for clarification if required inputs, permissions, safety boundaries, or success criteria are missing.
Related Skills
zod-validation-expert — for Zod-based form and API input validation (not LLM structured output).
prompt-engineering — for improving free-form text generation quality.
1---2name: llm-structured-output3description: Gets schema-constrained JSON from LLMs via OpenAI json_schema, Anthropic tool_use extraction, Gemini responseSchema, or local GBNF. Use when extracting typed objects, enums, or validated JSON from model APIs (zodResponseFormat, instructor, marvin). Not for free-form prose, Zod form/API validation (zod-validation-expert), or real tool orchestration.4---5
6# LLM Structured Output
7
8## Overview
9
10Extract typed, validated data from LLM API responses instead of parsing free-text. This skill covers the three main provider approaches — OpenAI's `response_format` with JSON Schema, Anthropic's `tool_use` block for structured extraction, and Google's `responseSchema` in Gemini — plus constrained decoding for local models. You will learn when each approach works, when it breaks, and how to build retry logic around schema validation failures that every production system encounters.
11
12## When to Use
13
14Use this skill when:
15
16- The user needs to extract structured data (JSON objects, arrays, enums) from an LLM response.
17- The user is building a pipeline where LLM output feeds directly into code (database writes, API calls, UI rendering).
18- The user asks about `response_format`, `json_mode`, `json_object`, or `json_schema` in OpenAI.
19- The user asks about using Anthropic's `tool_use` or `tool_result` blocks for data extraction (not for actual tool execution).
20- The user asks about Zod schemas with `zodResponseFormat()` from the `openai` npm package.
21- The user needs to parse LLM output into Pydantic models using `instructor`, `marvin`, or manual validation.
22- The user is getting malformed JSON, missing fields, or wrong types from LLM responses and needs a fix.
23- The user asks about `controlled generation`, `constrained decoding`, or `grammar-based sampling` in local models.
24
25Do NOT use this skill when:
26
27- The user wants free-form text generation (summaries, essays, chat).
28- The user is asking about Zod for form validation or API input validation (use `zod-validation-expert` instead).
29- The user needs prompt engineering for better text quality (not structure).
30- The user wants to call real external tools/APIs (this skill covers using `tool_use` as a structured output hack, not actual tool orchestration).
31
32## Prerequisites
33
34- An API key for the target provider (OpenAI, Anthropic, or Google). Use placeholder `YOUR_KEY` in examples — never commit live secrets.
35- Python 3.10+ with `openai`, `anthropic`, or `google-generativeai` SDK installed, or Node.js 18+ with the `openai` npm package.
36- For Pydantic workflows: `pip install pydantic openai instructor` (or `marvin` if preferred).
37- For Zod workflows: `npm install openai zod`.
38- For local model constrained decoding: `llama.cpp` (GBNF grammars) or `vLLM` (`--json-schema` flag).
39- Windows host is primary. Use PowerShell for all CLI commands. Path separators in examples use backslash on Windows.
40
41## Procedure
42
43### Step 1 — Identify the target schema
44
45Ask the user what fields they need extracted. Define every field with its type, whether it is required or optional, and valid enum values if applicable. Do not proceed without a concrete schema.
46
47### Step 2 — Choose the provider-appropriate method
48
49| Provider | Method | Key Setting |
50|---|---|---|
51| OpenAI (gpt-4o, gpt-4o-mini) | `response_format: { type: "json_schema", json_schema: { ... } }` | Set `"strict": true` for constrained decoding |
52| Anthropic (Claude) | Define a single tool with target schema as `input_schema` | Set `tool_choice: { type: "tool", name: "extract_data" }` |
53| Google (Gemini) | `generationConfig.responseSchema` + `responseMimeType: "application/json"` | Provide a JSON Schema object |
54| Local models (llama.cpp, vLLM) | GBNF grammars or `--json-schema` flag | Constrained decoding at token level |
55
56### Step 3 — Write the schema in the user's language
57
58- **Python:** Define a Pydantic `BaseModel`.
59- **TypeScript:** Define a Zod schema and convert with `zodResponseFormat()`.
60- **Raw API calls:** Write JSON Schema directly.
61
62### Step 4 — Include field-level descriptions in the schema
63
64Every field must have a `description` string that tells the model what to put there. Models use these descriptions as implicit prompt instructions. A field described as `"The user's sentiment as positive, negative, or neutral"` produces better results than a bare `sentiment: str` with no context.
65
66### Step 5 — Set the system prompt to reinforce structure
67
68Tell the model its job is data extraction, not conversation.
69
70Example system prompt:
71
72```
73You are a data extraction system. Analyze the input and return the requested fields. Do not include explanations outside the JSON structure.
74```
75
76### Step 6 — Enable strict mode (OpenAI)
77
78If using OpenAI's `json_schema` mode, set `"strict": true` in the schema definition. This activates constrained decoding where the model can only output tokens that conform to the schema. Without `strict: true`, the model may still produce invalid JSON.
79
80### Step 7 — Extract data from the correct block (Anthropic)
81
82If using Anthropic's `tool_use` approach, extract the structured data from `response.content` by finding the block where `type == "tool_use"` and reading its `input` field. Do not parse the text blocks — the structured data lives exclusively in the `tool_use` block.
83
84### Step 8 — Validate the response in application code
85
86Even with constrained decoding, validate with Pydantic's `model_validate()` or Zod's `.parse()` before passing data downstream. This catches semantic issues (empty strings, out-of-range numbers) that schema conformance alone cannot prevent.
87
88### Step 9 — Build a retry loop for validation failures
89
90When validation fails, send the original input plus the failed output and the validation error back to the model with an instruction like:
91
92```
93Your previous output failed validation: {error}. Fix the output.
94```
95
96Cap retries at 3 attempts.
97
98### Step 10 — Log every structured output call
99
100Log: the input, the raw response, the parsed result, and any validation errors. When structured output breaks in production, you need these logs to determine whether the failure was a schema design issue, a prompt issue, or a model regression.
101
102## Examples
103
104### Example 1: OpenAI Structured Outputs with Pydantic (Python)
105
106```python
107from pydantic import BaseModel, Field
108from openai import OpenAI
109from enum import Enum
110
111class Sentiment(str, Enum):
112 positive = "positive"
113 negative = "negative"
114 neutral = "neutral"
115
116class ReviewAnalysis(BaseModel):
117 sentiment: Sentiment = Field(description="Overall sentiment of the review")
118 key_topics: list[str] = Field(description="Main topics mentioned, max 5")
119 purchase_intent: bool = Field(description="Whether the reviewer would buy again")
120 confidence_score: float = Field(ge=0.0, le=1.0, description="Model confidence 0-1")
121
122client = OpenAI()
123response = client.beta.chat.completions.parse(
124 model="gpt-4o-2024-08-06",
125 messages=[
126 {"role": "system", "content": "Extract structured review analysis."},
127 {"role": "user", "content": "This laptop is amazing. The battery lasts forever and the keyboard feels great. Definitely buying the next version."}
128 ],
129 response_format=ReviewAnalysis,
130)
131result = response.choices[0].message.parsed
132# result.sentiment == Sentiment.positive
133# result.key_topics == ["battery life", "keyboard"]
134# result.purchase_intent == True
135```
136
137### Example 2: Anthropic tool_use for Structured Extraction (Python)
138
139```python
140import anthropic
141
142client = anthropic.Anthropic()
143response = client.messages.create(
144 model="claude-sonnet-4-20250514",
145 max_tokens=1024,
146 system="You are a data extraction system. Use the provided tool to return structured data.",
147 tools=[{
148 "name": "extract_invoice",
149 "description": "Extract invoice fields from text",
150 "input_schema": {
151 "type": "object",
152 "properties": {
153 "vendor_name": {"type": "string", "description": "Company that issued the invoice"},
154 "total_amount": {"type": "number", "description": "Total amount in USD"},
155 "line_items": {
156 "type": "array",
157 "items": {
158 "type": "object",
159 "properties": {
160 "description": {"type": "string"},
161 "quantity": {"type": "integer"},
162 "unit_price": {"type": "number"}
163 },
164 "required": ["description", "quantity", "unit_price"]
165 }
166 }
167 },
168 "required": ["vendor_name", "total_amount", "line_items"]
169 }
170 }],
171 tool_choice={"type": "tool", "name": "extract_invoice"},
172 messages=[{"role": "user", "content": "Invoice from Acme Corp: 3x Widget A at $10 each, 1x Widget B at $25. Total: $55."}]
173)
174# Find the tool_use block — do NOT parse text blocks
175tool_block = next(b for b in response.content if b.type == "tool_use")
176invoice = tool_block.input
177# invoice["vendor_name"] == "Acme Corp"
178# invoice["total_amount"] == 55.0
179```
180
181### Example 3: TypeScript with Zod + zodResponseFormat
182
183```typescript
184import OpenAI from "openai";
185import { z } from "zod";
186import { zodResponseFormat } from "openai/helpers/zod";
187
188const EventSchema = z.object({
189 event_name: z.string().describe("Name of the event"),
190 date: z.string().describe("ISO 8601 date string"),
191 location: z.string().describe("City and venue"),
192 attendee_count: z.number().int().describe("Expected number of attendees"),
193 is_virtual: z.boolean().describe("Whether the event is online-only"),
194});
195
196const client = new OpenAI();
197const completion = await client.beta.chat.completions.parse({
198 model: "gpt-4o-2024-08-06",
199 messages: [
200 { role: "system", content: "Extract event details from the text." },
201 { role: "user", content: "Tech Summit 2025 in Austin at the Convention Center on March 15th. Expecting 2000 attendees, in-person only." },
202 ],
203 response_format: zodResponseFormat(EventSchema, "event_extraction"),
204});
205const event = completion.choices[0].message.parsed;
206// event.event_name === "Tech Summit 2025"
207// event.is_virtual === false
208```
209
210## Pitfalls
211
212### HARD RULES — never violate these
213
2141. **Never use `response_format: { type: "json_object" }` without a schema.** This is OpenAI's legacy JSON mode — it guarantees valid JSON syntax but not schema conformance. The model can return `{"result": "hello"}` when you expected `{"name": str, "age": int}`. Always use `json_schema` with a full schema definition instead.
215
2162. **Never parse Anthropic's text blocks for structured data.** When using `tool_choice` to force structured output, the data is in the `tool_use` content block, not in any `text` block. Parsing `response.content[0].text` will either return empty string or a conversational preamble — never the data you need.
217
2183. **Never define schema fields without descriptions.** A field named `status` with no description can mean HTTP status, order status, or review status. Models use field descriptions as extraction instructions. Omitting them is equivalent to omitting half your prompt.
219
2204. **Never use `additionalProperties: true` in strict mode schemas.** OpenAI's strict mode requires `additionalProperties: false` on every object in the schema. If you set it to true or omit it, the API rejects the request with a 400 error — not at response time. You will never get a response at all.
221
2225. **Never put extraction instructions only in the user message and not the system prompt.** The system prompt has higher attention weight for behavioral instructions. Putting "extract the following fields" only in the user message alongside the source text forces the model to split attention between the instruction and the data. System prompt defines behavior; user message provides input data.
223
2246. **Never assume structured output means correct output.** Constrained decoding guarantees the response matches the schema's types and structure. It does not guarantee the values are correct. A model can return `{"sentiment": "positive"}` for a negative review if the source text is ambiguous. Always validate semantics in application code after schema validation.
225
2267. **Never use recursive or deeply nested schemas without testing.** Recursive types (`$ref` pointing to the same definition) and schemas deeper than 3 levels increase decoding latency significantly and raise the probability of the model hitting `max_tokens` before completing the JSON structure. Flatten nested schemas where possible.
227
228### Edge cases to watch for
229
2301. **Long source text exceeding context window.** When the input text is too long, the model may truncate its reading and return incomplete extractions. Split long documents into chunks, extract from each chunk independently, then merge results in application code. Do not rely on the model to handle 50-page documents in a single call.
231
2322. **The model returns a `refusal` instead of structured data.** OpenAI's structured output can return a `refusal` field when the model considers the request unsafe. Check `response.choices[0].message.refusal` before accessing `.parsed`. If `refusal` is not None, the parsed data will be None and accessing it throws an error.
233
2343. **Array fields returning empty when data exists.** Models sometimes return `[]` for array fields when the source text contains the data but the field description is too vague. Fix by making the description prescriptive: `"List of all product names mentioned in the text. Return at least one if any product is referenced."`.
235
2364. **Enum values not matching due to casing.** If you define an enum as `["Active", "Inactive"]` but the model returns `"active"`, validation fails. Either lowercase all enum values in the schema or add a normalization step before validation. OpenAI's strict mode respects exact casing; Anthropic may not.
237
2385. **Streaming with structured output.** OpenAI supports streaming structured output where partial JSON arrives chunk by chunk. You cannot parse intermediate chunks as valid JSON. Use the `openai` SDK's built-in partial parsing or buffer chunks until the stream completes. Anthropic's `tool_use` blocks arrive complete in a single `content_block_stop` event — no partial assembly needed.
239
240## Verification
241
242After implementing a structured output pipeline, verify correctness with these checks:
243
2441. **Schema conformance check — confirm the API accepts the schema:**
245
246 ```powershell
247 # Python: run a single extraction and confirm no 400 error
248 python -c "from your_module import extract; print(extract('test input'))"
249 ```
250
251 If you see a `400 Bad Request` mentioning `additionalProperties` or `strict`, your schema is missing `"additionalProperties": false` on one or more objects.
252
2532. **Parsed result is not None:**
254
255 ```python
256 result = response.choices[0].message.parsed
257 assert result is not None, "Parsed result is None — check for refusal or schema error"
258 ```
259
2603. **Refusal check (OpenAI):**
261
262 ```python
263 if response.choices[0].message.refusal is not None:
264 print(f"Model refused: {response.choices[0].message.refusal}")
265 # Do not proceed — handle safety refusal
266 ```
267
2684. **Tool_use block exists (Anthropic):**
269
270 ```python
271 tool_blocks = [b for b in response.content if b.type == "tool_use"]
272 assert len(tool_blocks) == 1, f"Expected 1 tool_use block, got {len(tool_blocks)}"
273 ```
274
2755. **Semantic validation passes:**
276
277 ```python
278 # Pydantic validation with constraints
279 validated = ReviewAnalysis.model_validate(result)
280 assert 0.0 <= validated.confidence_score <= 1.0
281 assert len(validated.key_topics) <= 5
282 ```
283
2846. **Retry loop fires on bad output:**
285
286 Inject a deliberately malformed response into your retry path and confirm the loop sends the validation error back to the model and retries up to 3 times.
287
2887. **Logs contain all four fields:**
289
290 Confirm your log entries include: input text, raw API response, parsed result, and any validation errors. Without all four, production debugging is impossible.
291
292## Best Practices
293
2941. **Start with the simplest schema that solves the problem.** Flat objects with 3–5 fields produce higher accuracy than nested schemas with 20+ fields. If you need complex data, extract in two passes: first extract top-level entities, then make a second call to extract details for each entity.
295
2962. **Use enums instead of free-form strings for categorical data.** A field `mood: str` can return anything. A field `mood: Literal["happy", "sad", "neutral", "angry"]` constrains the model to exactly those values. This reduces downstream parsing logic to zero.
297
2983. **Pin the model version in production.** `gpt-4o` is an alias that changes when OpenAI releases new versions. Structured output behavior can change between versions. Use `gpt-4o-2024-08-06` explicitly so that your schema+prompt combination remains stable until you deliberately upgrade.
299
3004. **Test schema changes against 20+ real inputs before deploying.** Schema changes (adding a field, changing a type, modifying a description) can break extraction on inputs that previously worked. Build a test suite of real inputs with expected outputs and run it on every schema change. This is the structured output equivalent of unit testing.
301
3025. **Use `default` values in Pydantic models for optional fields.** When a field might not have relevant data in the source text, define it as `Optional[str] = None` in Pydantic or `.optional()` in Zod. Without defaults, the model is forced to hallucinate a value for fields where the source text has no answer.
303
3046. **Separate extraction schemas from application schemas.** Your LLM extraction schema should match what the model can reliably produce. Your application database schema may have additional computed fields, foreign keys, or constraints. Map between them in application code — do not force the LLM to understand your database schema.
305
306## Limitations
307
308- Use this skill only when the task clearly matches the scope described above.
309- Do not treat the output as a substitute for environment-specific validation, testing, or expert review.
310- Stop and ask for clarification if required inputs, permissions, safety boundaries, or success criteria are missing.
311
312## Related Skills
313
314- `zod-validation-expert` — for Zod-based form and API input validation (not LLM structured output).
315- `prompt-engineering` — for improving free-form text generation quality.