Prompting, lesson 4
JSON that always parses
Schemas, JSON mode, and how to recover from bad output.
You know how a chat request is put together ("How a chat request is built"). It helps to have seen JSON, text like {"qty": 2}.
Part 1. Asking nicely for JSON
A shop reads order emails with a model. The email says: "Hi, please send 2 blue mugs to Pune." The prompt ends with: "Reply with JSON with the keys item, qty and city." Your code hands whatever comes back to json.loads.
Your turn
Five replies come back: the bare JSON; the same JSON after "Sure! Here it is:"; the JSON inside a markdown code fence; the JSON with a comma after the last value; and the JSON with "qty": "two". How many does json.loads accept?
import json
good = '{"item": "blue mug", "qty": 2, "city": "Pune"}'
replies = [
good,
"Sure! Here it is:\n" + good,
"```json\n" + good + "\n```",
good[:-1] + ",}",
good.replace("2", '"two"'),
]
for r in replies:
try:
json.loads(r)
print("parses")
except json.JSONDecodeError:
print("fails")
# parses
# fails
# fails
# fails
# parsesA prompt can only ask. Most replies will be fine, but code that runs thousands of times a day meets the odd one out every day.
Part 2. A schema says what shape
Keep going with Pro
You've done the first part. Pro opens the rest of this lesson, and every other one.
- A schema says what shape
- Three ways to get structure
- Schemas that help the model
Prompting overviewSpotted a mistake? Tell us.