Start learning free

LESSON 32 OF 129 · AI ENGINEERING: STRUCTURED OUTPUT

Extract the Order Number in Python

Practice

Customers write their order number in every possible way: #3, order number 42, or not at all. Extraction is asking the model to pull such values out of free text into fields your code can use.

Some messages don't have the value. A field that can only be an integer would push the model to make a number up, so the schema lets the field be null. Here is the same idea on another field, a coupon code that may be missing:

"coupon": {"anyOf": [{"type": "string"}, {"type": "null"}]}

anyOf means any of the listed types. When the field is also in the schema's "required" list, the key is always in the answer, and its value is null when the message doesn't have it. json.loads turns null into Python's None.

The model only reports what the message says. Whether the order exists, and whose it is, only the shop's database knows. A schema can make sure a value is an integer. It can't make it the number of a real order: that check is always yours. Your finished program must print:

{'order_id': 3, 'email': 'ana@example.com'}
-> the order belongs to this customer
{'order_id': 5, 'email': 'ben@example.com'}
-> the order belongs to another customer
{'order_id': 42, 'email': 'chloe@example.com'}
-> no such order
{'order_id': None, 'email': 'dan@example.com'}
-> no order number: ask the customer for it

Your task: the program already extracts the email from four messages. Add order_id to the schema as an integer or null, and make both fields required. Then write check_order(data): it looks the order up in shop.db with the ready-made QUERY and says whether the order exists and belongs to that email. Print its answer below each dictionary.


Assignment
Follow the Coding Tutorial to extract the order number and the email with a schema, and to check each order in the shop's database.


Hint
QUERY gives the email of the customer who placed the order, and fetchone() gives None when no row matches. In check_order, test for a missing number first, then for a missing row, then compare the two emails.


STEP 1 OF 12
    Ctrl + Enter to check

    Ai Extract Order 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