Validate with Pydantic and retry on invalid
The fake model is passed in as a parameter, so the same function works with a real client later.
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
attempt 1 rejected -> JSON: Invalid JSON: expected value at line 1 column 1
attempt 2 rejected -> priority: Input should be 'low', 'medium' or 'high'
accepted on attempt 3 -> title='Fix login' priority='high' estimate_hours=2.0
{'title': 'Fix login', 'priority': 'high', 'estimate_hours': 2.0}