Command Palette

Search for a command to run...

Hectal
Back to the lesson: Topic 16.6 — Structured Output: JSON, Schemas and Pydantic
Python · Example 1 of 3

Four replies, one parser

Only the first reply is acceptable JSON. The last line shows rescuing a chatty reply.

Programs need data, not prose, so you ask a model for JSON and then treat its answer as untrusted input: parse it, validate it against a schema with Pydantic, and if it is invalid send the error back and retry a limited number of times.

Change the code and press Run (Ctrl+Enter). Predict what will happen first, then break it on purpose and read what changes. Your edits are saved and match the lesson page.

Ready for more? This phase has 6 hands-on exercises with automatic checks.

Practice questions

Write the code in the editor, run it, then open the model answer to compare.

01

Write safe_parse(text) that removes code fences, parses JSON and returns a dict, or None if parsing fails or the value is not a dict.

02

Write a Pydantic model Review with rating (an integer from 1 to 5) and sentiment (positive, neutral or negative). Validate one good and one bad reply.

03

Without Pydantic, write validate_ticket(data) that returns a list of problem strings (empty means valid).

Explain it without notes

01

Why must you validate a model's JSON even if you asked for a specific schema?

02

Describe a retry-on-invalid loop and its safety limits.

03

How does Pydantic help with both prompting and validating?

04

Your service must extract an invoice into a typed object from a model. Walk through the design from the request to a trusted object, including what you do when it keeps failing.

Four replies, one parser
Sign in to run this example in your browser.

Expected output

good -> {'title': 'Fix login', 'priority': 'high'}
trailing comma -> JSONDecodeError: Illegal trailing comma before end of object
single quotes -> JSONDecodeError: Expecting property name enclosed in double quotes
chatty -> JSONDecodeError: Expecting value
extracted: {'title': 'Fix login'}