Skip to content
IT Vizag
← Python Meets AI

▶ 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

Lesson 6 of 10 · 2 min read

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:

🔒 Code example: sign up free (above) to unlock it.

Ask for that shape

🔒 Code example: sign up free (above) to unlock it.

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:

🔒 Code example: sign up free (above) to unlock it.

Designing good shapes

  • Use clear field names. The model reads them as instructions: fresher_friendly is clearer than flag.
  • 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.

Tip: Structured output turns AI into a function: text goes in, typed data comes out. Most real AI features in companies are exactly this.

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.

Saved on this device. Sign in to keep progress everywhere.

Share with a friend