Structured Outputs & JSON Schema
Fundamentals beginner 15 min
Sources verified Dec 22
Constrain AI responses to follow a specific format using JSON Schema, enabling reliable data extraction and type-safe integrations.
When you call an LLM API, by default you get back unstructured text. This is fine for chat, but problematic when you need to:
- Extract specific fields from documents
- Generate data for downstream systems
- Ensure consistent response formats
Structured outputs solve this by constraining the model's response to match a predefined schema.
structured_output_example.ts
// OpenAI structured outputs example
const response = await openai.chat.completions.create({
model: 'gpt-4o',
messages: [{ role: 'user', content: 'Extract the person info: John is 30 years old' }],
response_format: {
type: 'json_schema',
json_schema: {
name: 'person_info',
schema: {
type: 'object',
properties: {
name: { type: 'string' },
age: { type: 'integer' }
},
required: ['name', 'age']
}
}
}
});
// Response is guaranteed to be valid JSON matching the schema
const person = JSON.parse(response.choices[0].message.content);
console.log(person.name); // "John"
console.log(person.age); // 30 L6: The response_format tells the API to constrain output
L18: The response is guaranteed to match this schema
Why This Matters
- Type Safety: Your downstream code can rely on the structure
- No Parsing Errors: The API guarantees valid JSON
- Reduced Hallucination: The model is constrained to the schema
- Better Validation: Schema defines what's required vs optional
Key Takeaways
- Structured outputs guarantee response format using JSON Schema
- They eliminate parsing errors and reduce hallucination
- Use them whenever you need to extract specific data
- OpenAI, Anthropic, and most providers support this pattern
In This Platform
This entire learning platform uses structured outputs. Every question, dimension, concept, and recommendation is defined by JSON Schema. The build system validates all content at compile time.
Relevant Files:
- schema/survey.schema.json
- schema/concept.schema.json
- dimensions/adoption.json
- build.js
dimensions/adoption.json (excerpt)
{
"id": "adoption_q1",
"text": "What percentage of developers use AI tools?",
"type": "single_choice",
"options": [
{ "value": "a", "label": "< 25%", "score": 1 },
{ "value": "b", "label": "25-50%", "score": 2 }
],
"max_score": 4
} Sources
Tempered AI — Forged Through Practice, Not Hype
? Keyboard shortcuts