Session 5· 17· 10 min

Parse Calendar Event (Pydantic)

What you'll learn
  • Define a Pydantic BaseModel for the expected output
  • Use responses.parse() with text_format=YourModel
  • Get a typed Python object back instead of raw JSON

The cleaner way to do structured output

In Phase 1 you wrote JSON Schema by hand as a Python dict. That works — but Pydantic does the same thing in much cleaner code. Define a class, pass it as text_format, get a typed Python object back. No json.loads(). No dict key checks.

Phase 1 — by hand
  • schema = {"type": "object", ...} dict
  • response_format={"type": "json_schema", ...}
  • json.loads(response.choices[0].message.content)
  • Dict access: data["name"]
Phase 3 — with Pydantic
  • class CalendarEvent(BaseModel): ...
  • client.responses.parse(..., text_format=CalendarEvent)
  • response.output_parsed → CalendarEvent instance
  • Attribute access: event.name
17_responses_parse_calendar_event.py
from pydantic import BaseModel                               ①

class CalendarEvent(BaseModel):                                 ②
    name: str
    date: str
    participants: list[str]

response = client.responses.parse(                              ③
    model="gpt-4o-2024-08-06",
    input=[
        {"role": "system", "content": "Extract the event information."},
        {"role": "user",   "content": "Alice and Bob are going to a science fair on Friday."},
    ],
    text_format=CalendarEvent,                                   ④
)

event = response.output_parsed                                   ⑤
print(event.name, event.date, event.participants)                ⑥
Pydantic is the standard Python data-validation library.
Fields with type hints define the schema — SDK translates this to a JSON schema for you.
Back to responses.parse() — this is the newer endpoint (Session 1 used responses.create).
text_format takes your Pydantic class, not a dict schema.
output_parsed is a real CalendarEvent instance, not a dict.
Attribute access with typed autocomplete — VS Code knows event.name is a string.
$ python 17_responses_parse_calendar_event.py
Why this is better
Pydantic models give you IDE autocomplete, type checking with mypy/pylance, field validators, automatic conversion to dicts (event.model_dump()), and they live in one clean class instead of a sprawling schema dict.
Knowledge Check
What does output_parsed give you?
Recap — what you just learned
  • Pydantic + responses.parse() = structured output with zero boilerplate
  • Define a BaseModel with type hints — the SDK builds the schema for you
  • Get a typed instance back via output_parsed
  • Same structured-output power, cleaner code
Next up: 18 — Parse Math Reasoning