Start learning free

LESSON 27 OF 129 · AI ENGINEERING: STRUCTURED OUTPUT

Parse It Safely

Practice

You asked for only a JSON object, and a model doesn't always obey. Sometimes it wraps the JSON in ```json fences and adds a sentence, sometimes it sends no JSON at all, and sometimes the JSON is broken. json.loads can't read such text: it raises json.JSONDecodeError, and an error nobody catches stops the whole program.

Catch the error: put the risky line inside a try and say what to do in an except. Here the same idea guards int, which raises ValueError for text that isn't a number:

try:
    count = int("ten")
    print("Count:", count)
except ValueError:
    print("Not a number.")
print("Still running.")

This prints Not a number. and then Still running. After the error, Python jumps straight to the except, so the line below int is skipped, and the program goes on.

Cut out the good part: find gives the position of the first match in a string and rfind the position of the last one (both answer -1 when there is none). A slice stops just before its end, so go one past it:

label = "Teapot (blue) x2"
first = label.find("(")       # 7
last = label.rfind(")")       # 12
print(label[first:last + 1])  # (blue)

The inbox has four messages. Your finished program must print:

Reply: {"sentiment": "negative", "topic": "damaged item"}
Parsed: negative | damaged item
Reply: Here is the JSON you asked for:
```json
{"sentiment": "neutral", "topic": "gift cards"}
```
Let me know if you need anything else!
Parsed: neutral | gift cards
Reply: This message has no real content, so I can't describe it.
Not JSON. A person will read this message.
Reply: {"sentiment": "positive", "topic": "the "Sunny" lamp"}
Not JSON. A person will read this message.
Model calls: 4

Your task: the loop already asks the model about each message and prints the reply. Parse each reply inside a try, print its two fields when that works, and catch json.JSONDecodeError when it doesn't. Then, before the parsing, keep only the part of the text from the first { to the last }.


Assignment
Follow the Coding Tutorial to parse each reply inside a try, catch the error, and cut the JSON object out of the text around it.


Hint
except lines up with try. The print of the parsed fields goes inside the try, because data exists only when the parsing worked. The slice ends at end + 1, so the last } stays in.


STEP 1 OF 8
    Ctrl + Enter to check