TECHNOLOGIESTieInn Technologies

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 →

Questions

Open in Code Lab5 free questions
5 questions

    Structured output: JSON, schemas and checking it with Pydantic

  1. Question 1easy

    When should you ask the model for JSON instead of free text?

  2. Structured output: JSON, schemas and checking it with Pydantic

  3. Question 2easy

    What does this print?

    import json
    data = json.loads('{"category": "delivery", "order_id": 12}')
    print(data["order_id"] * 2)
  4. Structured output: JSON, schemas and checking it with Pydantic

  5. 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")
  6. Structured output: JSON, schemas and checking it with Pydantic

  7. 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())
  8. Structured output: JSON, schemas and checking it with Pydantic

  9. 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)

5 more questions on this topic, with hints, and tests

Sign up free for 21 days of every question and test.