Lesson 6 — Parsing and validating model output
Never trust the shape
Models make mistakes. Even when you ask for JSON, you may get chatty text, a list instead of a dict, or a dict with a key missing. Parsing means turning the text into data; validating means checking the data has the shape you need before using it.
A good parser answers with a clear error instead of crashing:
- Is it JSON at all? (
json.loadsraisesjson.JSONDecodeErrorif not) - Is it a dict? (
isinstance(data, dict)) - Are all required keys there?
Why it matters: an agent that crashes on one bad reply is useless. An agent that says "error: missing args" can tell the model and ask again — you will do exactly that in Lesson 21.
Add the required-keys check: if any key from REQUIRED is missing in data, return "error: missing " followed by that key.
Run your code — when the output matches the task, you will see a green check. Then mark the lesson complete.
A quick 3-question quiz on this lesson — instant feedback.