Lab: Validated JSON from a Prompt
Ask for JSON that matches a Pydantic v2 schema, validate every reply, retry once with the validation errors, fall back to a person when that fails, then switch on the provider's structured-output mode.
Contentsand lesson path
On this page
- Goal and setup
- Step 1: Describe the reply as a Pydantic model
- Step 2: Validate replies and read the errors
- Step 3: Validate, retry once with the errors, then fall back
- Step 4: Switch on the provider's structured-output mode
- Troubleshooting
- Check your understanding
- Apply it: stretch task
- Review prompt
Lessons of Prompt Basics
- What a Model Needs from a Prompt Concept · 15 min
- Rewriting a Vague Prompt Worked example · 15 min
- Examples, Reasoning Instructions and Voting Concept · 20 min
- Lab: Compare Two Prompts on 20 Inputs Lab · 25 min
- Lab: Validated JSON from a Prompt Lab · 20 min
- Check: Diagnose Prompt Failures Knowledge check · 8 questions
What you will learn
- Request JSON output that matches a schema, using the provider's structured-output mode where available, and validate it in code with a bounded retry before it is used.
01. Goal and setup
In the previous lab the model returned one word. Real features need more: here, a category, an urgency and a one-line summary that another service stores. This lab asks for that as JSON, describes it once as a Pydantic model, and lets nothing reach the rest of the system unless it validates:
- every reply is validated before it is used;
- a reply that fails gets exactly one retry, with the validation errors sent back to the model;
- a ticket that still fails goes to a person instead of being guessed.
Finally you switch on the provider's structured-output mode, which removes most failures but not all of them. The Pydantic lesson in the data-handling skill introduced models, Literal, Field constraints and ValidationError; this lab applies them to model output.
You need Python 3.12 or later. Steps 1 to 3 run offline against a FAKE model. Step 4 needs an Anthropic API key in ANTHROPIC_API_KEY; without one, read it and compare it with the fake version.
json-triage/
schema.py the reply schema and a one-line error formatter
show_schema.py prints the JSON Schema the model receives
try_replies.py validates five sample replies
fake_model.py FAKE model with scripted replies, for offline runs
triage.py validate, retry once with the errors, then fall back
claude_chat.py the same loop with Claude's structured-output modemkdir json-triage && cd json-triage
python3 -m venv .venv
source .venv/bin/activate # Windows (PowerShell): .venv\Scripts\Activate.ps1
python -m pip install "pydantic>=2.7,<3" anthropic
python -c "import pydantic, sys; print(sys.version.split()[0], pydantic.VERSION)"3.12.13 2.14.302. Step 1: Describe the reply as a Pydantic model
One class does three jobs: it documents the reply, it produces the JSON Schema you send to the model, and it validates what comes back. Keeping all three in one place means they cannot drift apart.
from typing import Literal
from pydantic import BaseModel, ConfigDict, Field, ValidationError
class TicketTriage(BaseModel):
"""The JSON object the model must return for one ticket."""
model_config = ConfigDict(extra="forbid")
category: Literal["billing", "bug", "account", "other"]
urgency: Literal["low", "normal", "high"] = Field(
description="high: the customer cannot work or is losing money now"
)
summary: str = Field(
min_length=1, max_length=80, description="One sentence in English"
)
def describe(err: ValidationError) -> str:
"""One line for all problems: where each one is and what is wrong."""
return "; ".join(
f"{'.'.join(map(str, e['loc'])) or 'reply'}: {e['msg']}" for e in err.errors()
)extra="forbid"makes an unexpected field an error instead of silently dropping it, so you notice when a model drifts from the contract.- The
Literalfields list the only values allowed. Thedescriptiontexts travel into the schema, where the model reads them as instructions. - The summary has the length limit that the storing service needs.
describe()turns aValidationErrorinto one line that names each field and its problem. That line is what you log and what you send back to the model.
Print the schema the model will receive:
import json
from schema import TicketTriage
print(json.dumps(TicketTriage.model_json_schema(), indent=2))python show_schema.py{
"additionalProperties": false,
"description": "The JSON object the model must return for one ticket.",
"properties": {
"category": {
"enum": [
"billing",
"bug",
"account",
"other"
],
"title": "Category",
"type": "string"
},
"urgency": {
"description": "high: the customer cannot work or is losing money now",
"enum": [
"low",
"normal",
"high"
],
"title": "Urgency",
"type": "string"
},
"summary": {
"description": "One sentence in English",
"maxLength": 80,
"minLength": 1,
"title": "Summary",
"type": "string"
}
},
"required": [
"category",
"urgency",
"summary"
],
"title": "TicketTriage",
"type": "object"
}03. Step 2: Validate replies and read the errors
Before any model is involved, check how the schema treats replies of the kinds models really produce. model_validate_json() parses and validates in one step and reports every problem it finds.
from pydantic import ValidationError
from schema import TicketTriage, describe
replies = [
'{"category": "bug", "urgency": "high", "summary": "PDF export fails"}',
'{"category": "Bug", "urgency": "high", "summary": "PDF export fails"}',
'{"category": "bug", "urgency": "high", "summary": ""}',
'```json\n{"category": "bug", "urgency": "high", "summary": "PDF export"}\n```',
'{"category": "bug", "summary": "' + "PDF export fails " * 6 + '"}',
]
for number, reply in enumerate(replies, start=1):
try:
result = TicketTriage.model_validate_json(reply)
print(number, "valid:", result)
except ValidationError as err:
print(number, "invalid:", describe(err))python try_replies.py1 valid: category='bug' urgency='high' summary='PDF export fails'
2 invalid: category: Input should be 'billing', 'bug', 'account' or 'other'
3 invalid: summary: String should have at least 1 character
4 invalid: reply: Invalid JSON: expected value at line 1 column 1
5 invalid: urgency: Field required; summary: String should have at most 80 charactersFive replies, five lessons:
- A valid reply becomes a typed object your code can trust.
Bugfails becauseLiteralvalues are exact. Fix that in the prompt or with an explicit normalising step, never by loosening the type.- An empty summary fails
min_length, so a reply cannot pass by leaving a field blank. - JSON wrapped in a Markdown code fence is not JSON. Without structured-output mode this is one of the most common failures, and the error points at line 1, column 1.
- A reply with two problems gets both reported, so a single retry can fix both.
04. Step 3: Validate, retry once with the errors, then fall back
The FAKE model below returns scripted replies, a different one on each attempt, so that one run shows the three outcomes you must handle: a valid reply, an invalid value fixed on the retry, and a ticket that fails twice.
"""FAKE model for offline practice: scripted replies, not an LLM.
For each ticket, the first call returns the first scripted reply and a retry
returns the next one. The replies imitate failures real models produce.
"""
SCRIPT = {
"I was charged twice for the March invoice.": [
'{"category": "billing", "urgency": "normal",'
' "summary": "Charged twice for the March invoice"}',
],
"Export to PDF gives error 500 since this morning.": [
'{"category": "bug", "urgency": "urgent",'
' "summary": "PDF export fails with error 500"}',
'{"category": "bug", "urgency": "high",'
' "summary": "PDF export fails with error 500"}',
],
"My two-factor codes stopped working after I got a new phone.": [
'Here is the triage:\n```json\n{"category": "account"}\n```',
'{"category": "account", "urgency": "high", "confidence": 0.9,'
' "summary": "Two-factor codes fail after a phone change"}',
],
}
def fake_chat(system: str, messages: list[dict[str, str]]) -> str:
replies = next(r for t, r in SCRIPT.items() if t in messages[0]["content"])
attempt = sum(m["role"] == "assistant" for m in messages)
return replies[min(attempt, len(replies) - 1)]"""Ask for JSON, validate it with Pydantic, retry once, then fall back."""
import json
from collections.abc import Callable
from pydantic import ValidationError
from fake_model import fake_chat
from schema import TicketTriage, describe
Chat = Callable[[str, list[dict[str, str]]], str]
MAX_ATTEMPTS = 2 # the first call plus one retry
class GiveUp(Exception):
"""Raised by a chat function when asking again cannot help."""
SYSTEM = (
"You triage support tickets for Lumen, a project-management web app.\n"
"Reply with only a JSON object that matches this JSON Schema, with no other"
" text:\n" + json.dumps(TicketTriage.model_json_schema())
)
def triage(ticket: str, chat: Chat = fake_chat) -> TicketTriage | None:
messages = [{"role": "user", "content": f"<ticket>\n{ticket}\n</ticket>"}]
for attempt in range(1, MAX_ATTEMPTS + 1):
try:
reply = chat(SYSTEM, messages)
except GiveUp as err:
print(f" attempt {attempt} gave up: {err}")
return None
try:
return TicketTriage.model_validate_json(reply)
except ValidationError as err:
problems = describe(err)
print(f" attempt {attempt} failed: {problems}")
messages += [
{"role": "assistant", "content": reply},
{
"role": "user",
"content": f"Your reply failed validation: {problems}. "
"Send the corrected JSON object only.",
},
]
return None # every attempt failed: the caller decides what happens next
if __name__ == "__main__":
tickets = [
"I was charged twice for the March invoice.",
"Export to PDF gives error 500 since this morning.",
"My two-factor codes stopped working after I got a new phone.",
]
for ticket in tickets:
print(ticket)
result = triage(ticket)
if result is None:
print(" -> needs review: queued for a person, not routed")
else:
print(f" -> {result.category}, {result.urgency}: {result.summary}")python triage.pyI was charged twice for the March invoice.
-> billing, normal: Charged twice for the March invoice
Export to PDF gives error 500 since this morning.
attempt 1 failed: urgency: Input should be 'low', 'normal' or 'high'
-> bug, high: PDF export fails with error 500
My two-factor codes stopped working after I got a new phone.
attempt 1 failed: reply: Invalid JSON: expected value at line 1 column 1
attempt 2 failed: confidence: Extra inputs are not permitted
-> needs review: queued for a person, not routedHow the loop behaves:
MAX_ATTEMPTS = 2bounds the cost: at most one extra call per ticket, whatever the model does.- After a failure, the invalid reply goes back as an assistant turn, followed by a user turn that quotes the validation errors. A message that names the field and the problem gives the model something specific to fix; a bare "try again" often gets the same mistake back.
GiveUplets a model adapter stop early when another attempt cannot help. Step 4 uses it.triage()returnsNonerather than an invented answer, and the caller chooses the fallback. Here the ticket waits for a person. In a real system, store the last reply and its errors with the ticket and count fallbacks, because a rising fallback rate is an early warning.
Look at the third ticket: the retry fixed the code fence but added a confidence field nobody asked for. Retries fix many problems, not all of them, which is why the limit and the fallback matter.
05. Step 4: Switch on the provider's structured-output mode
Most hosted providers can constrain generation to a JSON Schema, so the model rarely produces a token that breaks it. Anthropic calls this structured outputs (output_config.format); OpenAI calls it Structured Outputs (text_format in responses.parse()); local runtimes such as Ollama and vLLM offer similar options. With the mode on, invalid JSON, unknown enum values and extra fields mostly disappear. Four gaps remain:
- Not every constraint is enforced. Providers support a subset of JSON Schema. Claude, for example, rejects a schema that contains
minLengthormaxLength. The SDK'stransform_schema()removes such constraints from the schema it sends and notes them in the field description, so your own validation still has to check them. - Some replies are not answers. A refusal (
stop_reasonisrefusal) or a reply cut off atmax_tokensmay not match the schema at all. - Enum casing can drift. Claude's structured outputs do not guarantee the capitalisation of
enumvalues, so a reply may sayBugwhere the schema saysbug, with no error and no special stop reason. The exactLiteralcheck inTicketTriagerejects it, and the loop asks again. - Valid is not correct. A schema-valid reply can still name the wrong category. Only an evaluation like the one in the previous lab catches that.
So the adapter below turns the mode on and keeps the same validation loop. It plugs into triage() through the chat parameter:
"""The same triage, with Claude's structured-output mode. Needs an API key."""
import os
import anthropic
from schema import TicketTriage
from triage import GiveUp, triage
client = anthropic.Anthropic() # reads ANTHROPIC_API_KEY from the environment
# transform_schema() drops what the API cannot enforce (such as maxLength) and
# notes it in the field description; Pydantic still checks it afterwards.
OUTPUT_FORMAT = {
"type": "json_schema",
"schema": anthropic.transform_schema(TicketTriage),
}
def claude_chat(system: str, messages: list[dict[str, str]]) -> str:
response = client.messages.create(
model=os.environ["ANTHROPIC_MODEL"], # for example claude-sonnet-5-5
max_tokens=16000, # one cap for thinking and answer text together
system=system,
messages=messages,
output_config={"format": OUTPUT_FORMAT},
)
if response.stop_reason == "refusal":
raise GiveUp("the model declined this ticket")
if response.stop_reason == "max_tokens":
raise GiveUp("the reply was cut off; raise max_tokens")
return "".join(block.text for block in response.content if block.type == "text")
if __name__ == "__main__":
ticket = "Export to PDF gives error 500 since this morning."
print(triage(ticket, chat=claude_chat))ANTHROPIC_MODEL=claude-sonnet-5-5 python claude_chat.pycategory='bug' urgency='high' summary='PDF export fails with error 500'A refusal or a cut-off reply raises GiveUp, which skips the retry. Asking the same question again would most likely be refused again, and the fix for truncation is a larger max_tokens, not another call. On models that think before answering, the thinking counts towards max_tokens too.
The SDK also offers client.messages.parse(..., output_format=TicketTriage), which sends the transformed schema, validates the reply against your model and returns it as parsed_output. The explicit version here keeps a single validation path for the fake and the real model. With OpenAI the equivalent call is client.responses.parse(..., text_format=TicketTriage), with the result in output_parsed.
06. Troubleshooting
07. Check your understanding
08. Apply it: stretch task
Finish the practice project for this skill:
- Replace the short system prompt in
triage.pywith your v2 prompt from the previous lab, changing its output-format part to ask for the JSON object. - Run both prompt versions on your 20 labelled tickets through
triage(), with a real model or by extending the fake script, so that every output is validated with at most one retry. - For each version, report accuracy (category correct), schema failures (tickets that needed the retry and tickets that fell back) and three failure cases with their raw replies. Write the per-ticket results to a CSV file.
- Add a rule that the schema cannot express, such as "tickets in the other category are never high urgency", as a Pydantic
model_validator. Check that its error appears in the retry message. - Commit both prompt versions, the code and the results together.
09. Review prompt
Without looking back:
- What three jobs does the Pydantic model do in this lab?
- What goes into the retry message, and why is the number of attempts bounded?
- Which failures does structured-output mode remove, and which gaps remain?
- What happens to a ticket whose reply never validates, and what should you record about it?
References
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.