Structured outputs from an LLM: JSON schema, validation and retries
Structured outputs make an LLM reply in JSON that matches a schema you supply, so your code can parse it without guessing. Anthropic's version constrains the model's decoding to the schema rather than asking nicely in the prompt.1 It guarantees the shape of the answer, not that the answer is right, so you still validate.
Two features, one idea
| Feature | How you use it | What it checks |
|---|---|---|
| JSON outputs | Set output_config.format to json_schema with your schema; the JSON arrives in the response text | The reply matches the schema1 |
| Strict tool use | Add strict: true to a tool definition | Tool names and inputs match the tool's schema1 |
You can use either alone or both in one request. Anthropic's page lists all models as supported on the Messages API, and says the feature is also available through batch processing at the 50% discount, the same lever covered in LLM cost optimization.1
What a schema does not guarantee
Read the limits before you remove your own checks. According to Anthropic's documentation:1
- Refusals and cut-off replies can break the shape. If the stop reason is
refusalormax_tokens, the output may not match the schema. For the second, retry with a highermax_tokens. - Some constraints are not enforced. The page lists
minimum,maximum,minLengthandmaxLengthas unsupported; the SDK helpers move them into field descriptions instead. A schema cannot reliably say "amount above zero". - Capitalisation of enum values is not guaranteed, so compare case-insensitively.
- Citations and message prefilling do not work with it. Turning on citations alongside a JSON schema returns a 400 error.
- The first request with a new schema is slower, because the grammar has to compile. Compiled grammars are cached for 24 hours from last use.
- Changing the format invalidates the prompt cache for that conversation.
The theme: the schema controls the structure, and your code still owns the meaning. A reply can be perfectly shaped and still wrong, which is why a validator and an eval set belong next to the schema.
A validate-and-retry loop you can run
This version needs no API. It checks what the schema cannot (a positive amount, an allowed currency), and when a reply is rejected it sends the exact reason back to the model for another try. The model call is a stand-in that is wrong twice and then right; swap in your real call. The same loop is the fallback when you use a model or provider without schema enforcement.
import json
FIELDS = ["name", "amount", "currency"]
CURRENCIES = {"INR", "USD", "EUR"}
def validate(text):
"""Return (data, None) if the reply is usable, else (None, why not)."""
try:
data = json.loads(text)
except json.JSONDecodeError as e:
return None, "not valid JSON: " + e.msg
if not isinstance(data, dict):
return None, "the top level must be an object"
for key in FIELDS:
if key not in data:
return None, "missing field: " + key
if set(data) - set(FIELDS):
return None, "unexpected fields: " + ", ".join(sorted(set(data) - set(FIELDS)))
if not isinstance(data["amount"], (int, float)) or isinstance(data["amount"], bool):
return None, "amount must be a number, not text"
if data["amount"] <= 0:
return None, "amount must be above zero"
if str(data["currency"]).upper() not in CURRENCIES:
return None, "currency must be one of " + ", ".join(sorted(CURRENCIES))
return data, None
def extract(call_model, document, max_tries=3):
prompt = "Return only JSON with name, amount and currency from:\n" + document
for attempt in range(1, max_tries + 1):
data, why = validate(call_model(prompt))
if data:
return data
prompt += "\n\nYour last reply was rejected: " + why + ". Return only the corrected JSON."
raise ValueError("no valid reply after " + str(max_tries) + " tries: " + why)
# A stand-in for a real model call: wrong twice, then right.
replies = iter([
'Sure! {"name": "Asha"}',
'{"name": "Asha", "amount": "1200", "currency": "INR"}',
'{"name": "Asha", "amount": 1200, "currency": "INR"}',
])
print(extract(lambda prompt: next(replies), "Invoice: Asha paid 1,200 rupees"))
Output:
{'name': 'Asha', 'amount': 1200, 'currency': 'INR'}
Three details matter. The error message goes back to the model, so the retry is informed rather than blind. The number of tries is capped, so a stubborn failure raises an error instead of looping and spending money. And the amount is checked as a number, not text, because "1200" parses as valid JSON and still breaks the arithmetic later.
Where it fits in an agent
Anything that hands model output to other code needs this: extracting fields from documents, routing a request, or the arguments of a tool call in an agent. Log every rejected reply, since the rejection rate is a cheap quality signal, and a good input to observability. Model output that came from untrusted text should also be treated as untrusted, as covered in prompt injection explained: a valid shape does not make a value safe.
What this does not tell you
- The details above are from Anthropic's documentation as read on 28 November 2026. Other providers offer similar features with different limits, so check their pages.
- The sample shows the pattern, not a production extractor. Real documents need real test cases.
Getting reliable structured data out of a model is one of the first things a client project needs. Zero to FDE covers structured outputs and tool calling in its roadmap; it is self-paced and written, and the course does not include live classes, mentors or a certificate.
Zero to FDE is a self-paced 16-week course, ₹2,999 once, with a 7-day full refund. Week 1 is free, and one Week 4 lesson is free if you already write backend code. It has no live classes, no mentors and no accredited certificate.
Sources
Zero to FDE is a 16-week path, for working engineers and AIML graduates, to the work Forward Deployed Engineers do: backend basics, LLMs, RAG, agents, evaluation and deployment, with a shipped deliverable every week. Week 1 is free and complete, no card needed.
Start Week 1 freeMore from the blog
- Forward Deployed Engineer jobs in 2026: what the data says
- What is RAG? Retrieval-augmented generation, explained with working code
- What is an AI agent? The agent loop, explained with code
- AI engineer roadmap 2026: what to learn, and in what order
- Will AI replace software engineers? What the data says in 2026
- Forward Deployed Engineer courses in India (2026): fees, format and how they compare
- Forward Deployed Engineer vs ML engineer: which AI role fits you?
- Forward Deployed Engineer salary in India: what the 2026 data says for 2027
- Forward Deployed Engineer interview questions: the six rounds and how to answer
- Why Forward Deployed Engineer is a smart next move for a software engineer
- Forward Deployed Engineer certification in 2026: what exists, what it costs, and what employers check
- Forward Deployed Engineer skills: what 1,000 job posts ask for
- Forward Deployed Engineer vs Solutions Engineer: the real difference
- Forward Deployed Engineer resume: what to put on one page
- Forward Deployed Software Engineer (FDSE): what the Palantir title means
- Forward deployed AI engineer, AI deployment engineer, FDE: the titles explained
- Prompt injection explained: what it is and how to defend against it
- Context engineering explained: beyond prompt engineering
- RAG vs fine-tuning: which one to use, and when
- LLM evals explained: how to test a system that gives different answers
- LLM observability explained: traces, cost and what to log
- Tool calling explained: how an LLM uses your functions
- What is MCP? The Model Context Protocol explained
- AI agent vs workflow: which one does your problem need?
- AI engineer vs ML engineer: what each one does
- AI engineer interview questions: 25 that test whether you have built anything
- What is a vector database? Explained with a 30-line example
- EY now hires Forward Deployed Engineers for audit. The role is leaving the AI labs
- LangGraph explained: state, nodes and edges, with a 30-line example
- Randstad: 90% of Indian employers are growing tech teams for AI. What it means for engineers
- AI agent memory explained: short-term vs long-term, with a tested example
- LLM cost optimization: prompt caching, batching and model routing, with the numbers
- Embeddings explained: vectors, cosine similarity and dimensions
- Data engineer to AI engineer: what carries over and what to learn
- AWS launches a Forward Deployed Engineering Competency, with Infosys, TCS and Coforge among 22 launch partners
- Forward Deployed Architect: what the role is, certifications and courses
- Persistent launches a Forward Deployed Engineering program with Microsoft, a day after NIIT's FDE talent blueprint
- How to become an AI engineer in India: the route depends on where you start
- Self-paced Forward Deployed Engineer courses in India under ₹10,000 (and under ₹3,000)
- AWS and OpenAI will jointly staff forward deployed engineering teams inside customer environments
- Backend developer to AI engineer: what carries over and what to learn
- Claude now runs on premises in customers' own data centers through AWS AI Factories
- Agentic AI courses compared: four free options, and what a course must make you build
- AWS: attacks on AI systems grew about 800% in 2026, and an AI agent broke into a decoy MCP server in 12.7 minutes