Command Palette

Search for a command to run...

Hectal
Phase 16: Python in the AI Era
Python · Exercise 2 of 6 PreviousNext
Advanced

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

  1. Returns the dict for a valid first reply
  2. Retries after invalid JSON and succeeds
  3. Rejects a wrong type for age
  4. Rejects a boolean age and a JSON array
  5. Gives the model feedback in the retry prompt
  6. 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.

main.py
Sign in to run your code.

Output

Press Run to see what your program prints.