Structured output: JSON, schemas and checking it with Pydantic
LLM Fundamentals & Prompting · 10 questions
Short notes
Key idea
When code reads a model's reply, ask for JSON matching a schema, then validate it. Many APIs can enforce a schema; validation with Pydantic catches whatever still goes wrong.
Syntax
from pydantic import BaseModel
from google.genai import types
class Ticket(BaseModel):
order_id: int
issue: str
urgent: bool
config = types.GenerateContentConfig(
response_mime_type="application/json",
response_schema=Ticket,
)
r = client.models.generate_content(model=MODEL, contents=email, config=config)
ticket = Ticket.model_validate_json(r.text)
Example
An email says "Order 4471 arrived broken, I need it before Friday!" The reply parses to Ticket(order_id=4471, issue="arrived broken", urgent=True), which code can route straight to the right queue.
Traps
- "Reply in JSON" in the prompt alone sometimes returns text around the JSON or broken JSON; use the API's JSON mode and validate.
- Valid JSON can still be wrong (an invented order ID); check values against your data.
- Keep schemas small and fields clearly named; add descriptions for anything unclear.
- Decide what happens on failure: retry once with the error message, then fall back.
Want the full lesson with step-by-step examples, a project and a certificate? LLM Fundamentals & Prompting course, ₹180 →
- Question 1easy
When should you ask the model for JSON instead of free text?
- Question 2easy
What does this print?
import json data = json.loads('{"category": "delivery", "order_id": 12}') print(data["order_id"] * 2) - Question 3medium
What does this print?
from typing import Literal from pydantic import BaseModel, ValidationError class T(BaseModel): urgency: Literal["low", "normal", "high"] try: T.model_validate_json('{"urgency": "urgent"}') print("valid") except ValidationError: print("invalid") - Question 4medium
How many problems does Pydantic report?
from typing import Literal from pydantic import BaseModel, ValidationError class Triage(BaseModel): category: Literal["refund", "delivery"] urgency: Literal["low", "high"] reply: str try: Triage.model_validate_json('{"category": "refunds", "urgency": "high"}') except ValidationError as e: print(e.error_count()) - Question 5hard
What does this print?
from typing import Literal from pydantic import BaseModel, ValidationError class T(BaseModel): urgency: Literal["low", "normal", "high"] answers = ['{"urgency": "low"}', '{"urgency": "medium"}', 'urgent!', '{"urgency": "high"}'] good = 0 for a in answers: try: T.model_validate_json(a) good += 1 except ValidationError: pass print(good)
Structured output: JSON, schemas and checking it with Pydantic
Structured output: JSON, schemas and checking it with Pydantic
Structured output: JSON, schemas and checking it with Pydantic
Structured output: JSON, schemas and checking it with Pydantic
Structured output: JSON, schemas and checking it with Pydantic
5 more questions on this topic, with hints, and tests
Sign up free for 21 days of every question and test.