Structured Output Generation
Independent educational resource, not an official Anthropic course. Facts about the API, prices and limits were checked against Anthropic's documentation on 15 November 2026 and the code was run against a local mock of the API, not the live service. Check the linked official pages before relying on a number, and test with your own key.
You've already seen the schema-based structured outputs feature in lesson 2.8. This lesson is the prompt-side companion: how to get reliably formatted output when you're steering with words, what changed now that prefilling is gone, and how to build the validate-and-retry loop that keeps a bad reply from reaching your database.
What you'll learn
- When to use the structured outputs feature and when prompt-based formatting is enough.
- How to replace the old prefill tricks on current models.
- How to parse JSON from a model reply that isn't perfectly clean.
- How to validate and retry with the specific error.
Before you start
Pick the right tool
There are three ways to get structured output, and the right one depends on how strict you need to be.
- The schema-based feature. You give the API a JSON Schema and the response is constrained to match it. This is the strongest option when valid, schema-shaped data is the whole point. Use it for extraction, classification into fixed labels, and anything that goes straight into a typed system.
- Tool use with a schema. Anthropic suggests tools with an enum field for classification tasks. You'll meet tools in module 4.
- Asking in the prompt. Describe the format, show an example, maybe use tags. Anthropic's migration notes say newer models can reliably match complex schemas when told to, especially if you implement retries. It's the right choice for mixed output (a little prose plus a value), for models or setups where the feature isn't available, and for quick work where the occasional retry is acceptable.
Whichever you use, the rule is the same: never trust the shape, always validate it.
What happened to prefill
For a while, a common trick was to put the start of the answer in the assistant turn, for example a lone {, so the model had to continue the JSON. On Claude 4.6 and later, prefilled assistant messages on the last turn aren't supported and return a 400 error. Anthropic's guide lists replacements for each old use:
- Forcing a format (JSON, YAML, a label): use structured outputs, or ask for the format directly, with retries. For classification, use tools with an enum or structured outputs.
- Skipping the preamble ("Here is the summary:"): say so in the system prompt: "Respond directly without preamble. Do not start with phrases like 'Here is...' or 'Based on...'". Or ask for the answer inside a tag. If one slips through, strip it in code.
- Continuing an interrupted answer: put the partial text in a user message and ask the model to continue from where it stopped.
If you see "This model does not support assistant message prefill", this is why.
Asking for JSON in the prompt
A prompt that works well names every key, gives its type, says "only" and keeps the data in a tag:
Extract the sender's details from the email below. Reply with only a JSON object with the keys
"name" (string), "email" (string) and "wants_demo" (true or false).
<email>
...
</email>
"Reply with only a JSON object" matters, but it isn't a guarantee. You will occasionally get a sentence before the JSON, a code fence around it, or a missing key. So the code that receives it has to be tolerant of the harmless variations and strict about the rest.
Parse tolerantly, validate strictly, retry with the reason
This module strips code fences and surrounding sentences, parses the JSON, validates it with Pydantic, and on failure sends the model the exact complaint:
import json
import re
from typing import Callable
from pydantic import BaseModel, ValidationError
class Lead(BaseModel):
name: str
email: str
wants_demo: bool
FENCE = re.compile(r"^```(?:json)?\s*(.*?)\s*```$", re.DOTALL)
def parse_json_reply(text: str) -> dict:
"""Models sometimes wrap JSON in a code fence or add a sentence around it. Strip the common cases."""
text = text.strip()
if m := FENCE.match(text):
text = m.group(1)
start, end = text.find("{"), text.rfind("}")
if start == -1 or end == -1:
raise ValueError("no JSON object found")
return json.loads(text[start : end + 1])
def extract_lead(email: str, ask: Callable[[list[dict]], str], max_attempts: int = 3) -> Lead:
"""Use this when you cannot use structured outputs (see lesson 2.8). Validate, and on failure tell the
model exactly what was wrong. Newer models can match a described schema reliably, especially with retries."""
prompt = (
"Extract the sender's details from the email. Reply with only a JSON object with the keys "
'"name" (string), "email" (string) and "wants_demo" (true or false).\n\n'
f"<email>\n{email}\n</email>"
)
messages = [{"role": "user", "content": prompt}]
last_error = ""
for _ in range(max_attempts):
reply = ask(messages)
try:
return Lead.model_validate(parse_json_reply(reply))
except (ValueError, ValidationError) as e:
last_error = str(e).splitlines()[0]
messages += [
{"role": "assistant", "content": reply},
{"role": "user", "content": f"That was not valid. Problem: {last_error}\nReply with only the corrected JSON object."},
]
raise ValueError(f"No valid JSON after {max_attempts} attempts: {last_error}")
Walk through what extract_lead does when things go wrong. If the model answers "Sure, the name is Sam." there's no JSON object, so the first error is "no JSON object found". The retry message says exactly that and repeats the format request. If the second attempt has a name and email but forgets wants_demo, Pydantic's first error line ("Field required") goes back to the model. The third attempt, wrapped in a code fence, parses and validates. After max_attempts it raises a clear error so your calling code can queue the email for a human instead of storing garbage.
All of that was exercised with a scripted stand-in for the model: clean JSON, fenced JSON, JSON inside a chatty sentence, no JSON at all, missing key then success on the third try (the message list grew from 1 to 3 to 5 entries as the corrections accumulated), and a model that never recovers. Each case behaved as described.
In Laravel, the same ideas apply: json_decode($text, true, flags: JSON_THROW_ON_ERROR) for strict parsing, then Validator::make() for the shape and rules, exactly as in the extractor from lesson 2.8.
Real-world use case (illustrative scenario)
This scenario is an invented example to show how the ideas fit together. It is not a case study and its details are not measured results.
A small CRM add-on reads enquiry emails from a shared inbox. For most emails the model's reply is clean JSON; some have a fence or a lead-in sentence, and now and then a field is missing. Instead of switching off the feature or hand-fixing records, the add-on parses tolerantly, validates, retries once with the error, and sends anything that still fails to a "needs review" folder. Nothing malformed reaches the CRM, and the review folder tells the team how often the model needs help.
Mistakes to avoid
- Prefilling the assistant turn on current models, which returns a 400.
- Calling
json_decode or json.loads on the raw reply with no fallback.
- Validating the shape but not the meaning (a valid string that isn't an email).
- Retrying with "that was wrong, try again" and no reason.
- Retrying forever. Cap the attempts and have a human fallback.
- Parsing a reply that stopped at
max_tokens. It's cut off, so raise the limit.
Security notes
The reply was produced by a model that read untrusted text, so its fields are untrusted too. Validate lengths and formats, use parameterised queries when saving, escape on output, and never use a field from the reply as a file path, command or SQL fragment.
Cost and speed
Every retry is another full request. If you see a retry rate above a few percent, improve the prompt (add an example, name the keys more clearly) or switch to the schema-based feature rather than paying for retries forever. Log how often each attempt number succeeds. That ratio is a good, cheap quality measure.
Key takeaways
- Use the schema feature when strict, valid data matters; use prompts and retries for lighter needs.
- Prefill is gone on current models. Ask directly, use tags, or use structured outputs.
- Parse tolerantly, validate strictly, retry with the specific error, and cap attempts.
- Treat extracted fields as untrusted input.
Lesson recap: parse tolerantly, validate strictly, retry with the reason.
Quick quiz
- What happens if you send a prefilled assistant message to Claude 4.6 or later?
- Name two replacements for the old "start the answer for the model" trick.
- Why validate even when the model "replied in JSON"?
- What should the retry message contain?
- When should you stop retrying?
Answers and explanations
- The API returns a 400 error. Prefill on the last assistant turn isn't supported.
- Structured outputs, asking for the format in the prompt (with retries), answers inside tags, and for classification, tools with an enum.
- The format can vary slightly, keys can be missing, and a valid-looking value can still be wrong (a bad email, a number out of range).
- The model's previous reply and the specific problem found, plus a request for the corrected output only.
- After a small, fixed number of attempts, then fall back to a human review path.
Official references and further reading
Related tutorials