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.
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.
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.
Without Pydantic, write validate_ticket(data) that returns a list of problem strings (empty means valid).
Explain it without notes
Why must you validate a model's JSON even if you asked for a specific schema?
Describe a retry-on-invalid loop and its safety limits.
How does Pydantic help with both prompting and validating?
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.
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'}