Parse and validate model JSON, with retries
Write parse_with_retry(model, prompt, max_attempts=3). model is a function that takes a prompt string and returns the model's reply text.
A reply is valid if it is JSON text for an object (it looks like a Python dictionary) with name (a string) and age (an integer; true and false do not count as integers here). Return the parsed dict for the first valid reply. If a reply is invalid, call the model again. The new prompt is the original prompt plus a line saying what was wrong. After max_attempts invalid replies, raise ValueError. (Topic 16.6.)
What Check tests
- Returns the dict for a valid first reply
- Retries after invalid JSON and succeeds
- Rejects a wrong type for age
- Rejects a boolean age and a JSON array
- Gives the model feedback in the retry prompt
- Raises ValueError after max_attempts and stops calling the model
Stuck? One hint at a time
The solution unlocks after your first Check. Try first: that is where the learning happens.
Output
Press Run to see what your program prints.