Skip to content
Streak:0Loading your progress…Sign in

Module 9 · Lesson 2 of 3

Structured output

Turn free text into validated data you can safely act on. ~25 min

Lesson notes

Treat model output as untrusted input. Modern APIs support constrained structured outputs (output_config.format with a JSON schema, or client.messages.parse() with a Pydantic model). Either way: validate with Pydantic, and on failure either retry with the validation error in the prompt or fail safely.

Pydantic model → schema → validated result
from pydantic import BaseModel

class Ticket(BaseModel):
    category: Literal["billing", "bug", "other"]
    urgency: int  # 1-5
    summary: str

response = client.messages.parse(
    model="claude-opus-5-5", max_tokens=1024,
    messages=[{"role": "user", "content": f"Triage this email:\n{email}"}],
    output_format=Ticket,
)
ticket: Ticket = response.parsed_output

Practice

  1. 1. Robust JSON extraction

    medium25 XP

    Models sometimes wrap JSON in prose or ``json fences. Write extract_ticket(text) -> Ticket | None: find the first {...} JSON object in text (fenced or not), validate it against the given Ticket` model, return None if nothing valid is found. Never raise.

    Ctrl/⌘ + Enter runs the tests · Esc then Tab leaves the editor