← Building with AI

Retrying on bad output

If the reply is unusable, ask again (a limited number of times).

Start this lesson

Models are not perfectly consistent. If a reply can't be parsed, often just asking again works. A retry loop tries up to N times and returns as soon as it gets good data. Always set a limit, or a stubborn failure could loop forever and run up a bill. It also helps to tell the model what went wrong in the next attempt.

import json

def get_json(prompt, tries=3):
    for attempt in range(tries):
        reply = ask_model(prompt)
        try:
            return json.loads(reply)
        except json.JSONDecodeError:
            print("Attempt", attempt + 1, "was not JSON, trying again...")
    return None   # gave up after all tries

return inside the loop ends the function as soon as one attempt works. If every attempt fails, the loop finishes and we return None.

Each retry is another paid request, so keep the number small (2 or 3) and log failures so you can improve the prompt.

A stronger retry adds feedback: 'Your last reply was not valid JSON. Reply with only JSON.'