▶ Sign up free for the video, slides & prompts
The lesson below is open to all. Enter your email once to unlock every video, slide deck, prompt and code example on this device.
Checking…
Checking AI output in code
Validate answers and handle failures and retries.
🎬 Video version coming soon — read it now
AI is powerful but not reliable in the way 2 + 2 is reliable. Production-quality AI code expects failures: network errors, rate limits, odd answers. It checks, and it recovers.
Network and API errors
The SDK already retries temporary problems such as dropped connections, rate limits (HTTP 429) and server errors (5xx), with increasing waits between tries, twice by default. You can raise that:
Then catch what's left, most specific first:
These are the try/except skills from Functions & Clean Code, applied to real-world failures. Use the SDK's exception classes; don't match on error message text.
Check why it stopped
Validate the content
Even a well-formed answer can be wrong for your purpose. Add checks in code:
For extracted facts, compare against the source where you can. If the model says the job is in "Vizag", does the post actually mention Vizag?
Humans in the loop
For anything that affects people, such as grades, hiring, medical or money decisions, AI output should be reviewed by a person. Code can route the uncertain cases: anything flagged goes to a "check" list instead of being acted on automatically.
Keep a log
When a user says "the bot told me something wrong", the log lets you find out exactly what happened.
In one line
Let the SDK retry temporary errors, catch the rest by type, check stop_reason, validate answers in code, and route uncertain cases to a human.
Share with a friend