Start learning free

LESSON 35 OF 129 · AI ENGINEERING: STRUCTURED OUTPUT

Fall Back Gracefully in Python

Practice

A program that works through an inbox with a model must expect bad answers. A second try fixes many of them, but not all. And if one message can crash the program, the messages after it are never handled.

The cure is a fallback: a safe answer to give back when nothing worked. Here is the idea on another job, turning text into a number:

def to_number(text):
    try:
        return int(text)
    except ValueError:
        return 0

to_number("12") gives 12, and to_number("twelve") gives 0 instead of crashing. But that 0 hides the problem: nobody can tell it from a real zero. A good fallback says that it is a fallback, and the program records why it was needed.

In this lesson's inbox three things go wrong: an answer that is not JSON, a category the shop doesn't have, and an overloaded API. For the last one the SDK raises anthropic.APIStatusError, and the error's status_code is 529. When your program is done, it handles all six messages and prints:

refund: I want my money back for the lamp. It arrived broken.
shipping: Where is my package? I ordered ten days ago.
other (needs a human): No codes please, just tell me in plain words: is the mug dishwasher safe?
other (needs a human): Your courier was rude to my neighbour.
other (needs a human): Can I change the delivery address of order 5?
product: Does the lamp come with a bulb?
For a human: 3
- the answer was not JSON | No codes please, just tell me in plain words: is the mug dishwasher safe?
- unknown category: complaint | Your courier was rude to my neighbour.
- the API answered 529 | Can I change the delivery address of order 5?

Your task: the program in the editor classifies two messages, then crashes. Make classify give back the fallback {"category": "other", "needs_human": True} when all three tries have failed, mark those answers with (needs a human), treat the API's error as one more failed try, record each failure with its reason in failures, and print the report at the end.


Assignment
Follow the Coding Tutorial to add the fallback, catch the API's error, and report every message that needs a human.


Hint
The fallback return goes after the for loop, at the level of the for line, not inside it: it runs only when all three tries have failed. The new except sits at the level of the first one.


STEP 1 OF 9
    Ctrl + Enter to check

    Ai Fallback Gracefully in Python

    Keep going with Python1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free