A model answers in sentences, worded the way it likes. A person can read that, but your code can't pick one fact out of it. Code needs the answer in a format it can read, and you already know one from every API you built: JSON.
Ask for it in the system prompt: tell the model to answer with only a JSON object, name every key, and say what may go in each one. A shop that reads product reviews could write: Answer with only a JSON object. It has one key: stars (a whole number from 1 to 5). The reply is then text like {"stars": 4}.
Turn the text into a dictionary: the reply only looks like a dictionary. It is still a string. json.loads reads a string that holds JSON and builds the Python value it describes.
review = json.loads('{"stars": 4}')
print(review["stars"] + 1) # 5
In this lesson a customer wrote: My teapot arrived with a cracked lid. I'm very disappointed. Your finished program must print:
Reply: {"sentiment": "negative", "topic": "damaged item"}
Sentiment: negative
Topic: damaged item
A person should answer this one first.
Your task: the call to the model is already written, and it prints the reply. Add two sentences to SYSTEM: one that asks for only a JSON object, and one that names the keys sentiment (positive, neutral or negative) and topic (one or two words). Then parse the reply with json.loads, print the two fields, and print one more line when the sentiment is "negative".
Assignment
Follow the Coding Tutorial to ask the model for a JSON object, parse its reply and act on the sentiment.
Hint
The reply's text is a string until json.loads has read it. Each piece of SYSTEM ends with a space, because Python glues the pieces into one long string.
Free plan: 30 tutor messages. PRO is unlimited.
