Lesson 21 — Error handling and retries
When things go wrong
Two things fail all the time in agents:
- The model returns bad output — prose instead of JSON. Fix: catch the error, add a message like "Reply with valid JSON only", and retry (ask again), up to a limit.
- A tool raises an exception — dividing by zero, a missing file, a site that is down. Fix: catch it and turn it into an observation, such as
"error: ZeroDivisionError: division by zero". The model reads the error and can try something else.
try:
return risky()
except Exception as err:
return "failed: " + str(err)
type(e).__name__ is the error's class name; str(e) is its message.
Why it matters: a crash ends the whole run. An error the model can see is just one more step.
Run it first: it crashes with ZeroDivisionError. Make safe_call catch any exception and return "error: <ErrorName>: <message>".
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.
Ready for more? Optional paid resources that pick up where this lesson leaves off.
Some links on this page are affiliate links: we may earn a commission at no extra cost to you. As an Amazon Associate I earn from qualifying purchases.
Project-based AI Agents Foundations courses if you want a structured paid path after the free lessons. Wait for a sale — prices drop often.
Browse on Udemy →Search Amazon for AI Agents Foundations books — check the publication year so the examples match current versions.
Search Amazon →