What Is Structured Output in LLMs?
Structured output makes an LLM reply in a fixed format such as JSON. Learn why it matters, four ways to get reliable JSON, and a runnable validate-and-retry example.
Short answer: structured output in LLMs means getting a model to reply in a fixed, machine-readable format, usually JSON that matches a schema, instead of free-form text. It lets your code read the answer safely, for example to fill a database field or call a function. You get reliable structured output by asking clearly, using your provider's structured-output feature if it has one, and always validating the result in code.
Why Does Structured Output Matter?
A chatbot reply like “The rating looks like a four, I'd say!” is fine for a person but useless for a program. Your code needs {"rating": 4}. The moment an LLM feeds another system, such as a database, a spreadsheet, a form or a tool call, you need output that is predictable, not just readable.
What Does a Schema Look Like?
A schema describes the shape of the answer: which fields exist, their types, and which values are allowed.
Field | Type | Rule |
|---|---|---|
name | text | Required |
rating | whole number | Between 1 and 5 |
tags | list of text | Zero or more items |
If you are new to the format, read JSON and schemas in our prompt engineering course.
How Do You Get Reliable JSON From an LLM?
1. Ask clearly in the prompt
State the exact fields, show one example, and say what to do when information is missing, such as “use null”. Add “return only JSON, no extra text”. This is plain prompt engineering and often works, but it is not a guarantee.
2. Use a built-in structured-output feature
Many model providers offer a JSON mode or let you pass a schema so the model is steered to follow it. The names and details differ between providers and change over time, so check the official documentation. Even with these features, treat the result as untrusted until your code checks it.
3. Validate in code
Parse the reply, check every field, and reject anything that does not fit. In Python, libraries such as Pydantic do this with type hints, but the idea works with plain code too.
4. Retry or repair
If validation fails, send the error back to the model and ask it to fix the output, with a small limit on attempts. Our chapter on validation and repair covers this pattern in depth.
A Small Example: Validate and Retry
This script needs only the standard library. A fake model returns a broken reply first and a good one second, so you can see the loop work:
import json
REQUIRED = {"name": str, "rating": int, "tags": list}
def validate(text):
data = json.loads(text) # raises ValueError if it is not JSON
for key, kind in REQUIRED.items():
if not isinstance(data.get(key), kind):
raise ValueError(f"'{key}' is missing or not a {kind.__name__}")
if not 1 <= data["rating"] <= 5:
raise ValueError("rating must be between 1 and 5")
return data
def ask_model(prompt, attempt):
# Stand-in for a real model call: the first reply is broken, the second is fine.
replies = [
'Sure! Here is the JSON: {"name": "Cafe Nila", "rating": "great"}',
'{"name": "Cafe Nila", "rating": 4, "tags": ["quiet", "coffee"]}',
]
return replies[min(attempt, len(replies) - 1)]
def get_review(prompt, max_tries=3):
for attempt in range(max_tries):
reply = ask_model(prompt, attempt)
try:
return validate(reply)
except ValueError as err:
print(f"Attempt {attempt + 1} failed: {err}")
raise RuntimeError("No valid output after retries")
print(get_review("Extract name, rating (1-5) and tags from this review."))
Running it prints a failure for the first reply (it contains extra words, so it is not valid JSON), then the clean dictionary from the second reply: {'name': 'Cafe Nila', 'rating': 4, 'tags': ['quiet', 'coffee']}. Replace ask_model with a real model call and the rest stays the same.
Structured Output vs Function Calling
They are related. Structured output controls the shape of the reply. Function calling, also called tool calling, lets the model ask your program to run a function with arguments that follow a schema. Both depend on the same idea: a model that produces data your code can trust after checking.
Common Mistakes
Trusting valid JSON as correct JSON. A reply can parse perfectly and still contain a wrong value. Check ranges and business rules too.
Making the schema too big. Ask for the fields you need and no more; long schemas raise the chance of errors.
No fallback. Decide what happens after the last failed retry: log it, skip it, or send it to a person.
Forgetting missing data. Tell the model to return null instead of guessing, otherwise it may invent a value. See AI hallucination.
Key Takeaway
Structured output turns an LLM's words into data your program can use. Ask for a schema, use provider features where they exist, and always validate and retry in code, because a model that usually follows the format will sometimes break it.
Ready to start? Learn to design schemas, validate model output and build repair loops, with hands-on Python exercises. Begin with the free course Prompt Engineering for AI: Advanced.
Related articles
More in AI Engineering
What Are AI Guardrails? Keeping an AI App Safe
AI guardrails are the checks around a model that keep an app safe and on-topic. Learn the types, a runnable Python example, and why prompts alone are not enough.
4 min readNov 26, 2026What Is Reranking in RAG? Making Answers More Accurate
Reranking re-orders the passages found by your first search so the model sees the best ones. Learn how it works, when it helps, and try a tiny two-stage example in Python.
4 min readNov 22, 2026What Is Chunking in RAG?
Chunking splits documents into pieces a RAG system can search. Learn chunk size, overlap, the main strategies and how to test them, with code.
5 min readNov 16, 2026How to Get an LLM API Key (OpenAI and Gemini) and Understand the Cost
Where to create an OpenAI or Gemini API key, how token-based billing works, how to estimate cost and how to keep your key safe.
4 min readNov 11, 2026What Is Function Calling in LLMs?
Function calling lets an LLM ask your code to run a tool and use the result. Learn the step-by-step flow, a runnable example and the safety rules.
3 min readNov 7, 2026What Is LangChain? When to Use It (and When Not To)
LangChain is a framework for building LLM apps. Learn its core building blocks, a short sketch, and when plain code is the better choice.
4 min readNov 4, 2026
Comments
Sign in to join the discussion.



