Start learning free

LESSON 28 OF 129 · AI ENGINEERING: STRUCTURED OUTPUT

Validate the Fields

Practice

Valid JSON only means the text can be parsed. It doesn't mean the model put in it what you asked for: a key can be missing, a word can be one you never allowed, a number can come as text or be out of range. So your code has to validate the object before it uses it.

Three kinds of check: is the key there (not in), is the value an allowed one and of the right type (isinstance), and is a number inside its range. Here are the first two on a product instead of a reply:

product = {"name": "Teapot", "stock": "ten"}
print("price" not in product)             # True: the key is missing
print(isinstance(product["stock"], int))  # False: "ten" is text
print(isinstance(12, int))                # True: a whole number

A good validator doesn't stop at the first bad value. It collects every problem as a short text in a list, and an empty list means the object is safe to use. One exception: when a key is missing it returns at once, because reading a key that isn't there stops the program with a KeyError.

The model answers four messages, and then the check tries three objects of its own. Your finished program must print:

Reply: {"sentiment": "negative", "topic": "damaged item", "priority": 1}
Problems: []
Reply: {"sentiment": "angry", "topic": "late delivery", "priority": "high"}
Problems: ['sentiment must be positive, neutral or negative', 'priority must be a whole number']
Reply: {"sentiment": "positive", "topic": "thanks"}
Problems: ['missing key: priority']
Reply: {"sentiment": "neutral", "topic": "gift cards", "priority": 5}
Problems: ['priority must be from 1 to 3']
The check tries an empty object: ['missing key: sentiment', 'missing key: topic', 'missing key: priority']
The check tries priority 0: ['priority must be from 1 to 3']
The check tries priority 2.5: ['priority must be a whole number']

Your task: fill in find_problems(data). Add one problem for each key of REQUIRED that is missing, and return early if there is any. Then check that the sentiment is in SENTIMENTS, that the priority is an int, and, only when it is one, that it is from 1 to 3.


Assignment
Follow the Coding Tutorial to make find_problems check the keys, the sentiment, and the type and range of the priority.


Hint
Check the type before the range: comparing the text "high" with 1 is an error, so the range check is an elif of the type check. The problem texts must match exactly, for example "missing key: priority".


STEP 1 OF 11
    Ctrl + Enter to check