▶ Sign up free for the video, slides & prompts
The lesson below is open to all. Enter your email once to unlock every video, slide deck, prompt and code example on this device.
Checking…
Structured output with JSON
Get answers your code can use, not just paragraphs.
🎬 Video version coming soon — read it now
Paragraphs are great for people, but your code needs data: a category, a score, a list of skills. Asking "please reply in JSON" works most of the time, and "most of the time" breaks programs. Structured output guarantees a valid, predictable shape.
Describe the shape with Pydantic
Pydantic is a popular package for describing data shapes as classes. It's similar to the dataclasses you used in Objects & Classes:
Ask for that shape
messages.parse sends your shape to the API, the model's reply is constrained to match it, and the SDK hands you a validated JobPost object. No string cleaning, no hoping.
Why it matters
Now you can treat AI output like any other data:
Designing good shapes
- Use clear field names. The model reads them as instructions:
fresher_friendlyis clearer thanflag. - Use fixed choices where you can, with Python's
Literal:sentiment: Literal["positive", "neutral", "negative"]. - Allow "unknown". If the post doesn't mention a salary, the model shouldn't invent one. Make the field optional (
salary: str | None = None) and say in the prompt "use null if not stated".
The shape is guaranteed, the facts aren't
Structured output guarantees valid JSON in your shape. It does not guarantee the values are true. The model can still misread the post. For anything important, spot-check results against the source.
In one line
Describe the shape you need with a Pydantic class and use messages.parse to get back a validated object instead of free text.
Share with a friend