Start learning free

LESSON 15 OF 129 · AI ENGINEERING: CALLING A MODEL

Project: Product Descriptions

Practice

The shop's website needs a one-line description for every product, and nobody wants to write them by hand. This project puts the module together: a loop over the database, one model call per product, a check on every answer, and the bill at the end.

Count first, then skip: inside a loop, continue jumps straight to the next turn. Lines above it still run, lines below it don't. Here is the idea on a small list of words:

total = 0
for word in ["tea", "coffee", "milk"]:
    total += len(word)
    if len(word) > 4:
        print(word + ": skipped, too long")
        continue
    print(word + ": ok")
print("Letters:", total)

This prints tea: ok, coffee: skipped, too long, milk: ok and Letters: 13. The word "coffee" is skipped, but its 6 letters are counted, because the counting line sits before the if.

Your script does the same with model answers. Each call gets max_tokens=40, so a chatty answer is cut and its stop_reason is "max_tokens". A cut answer must not reach the website, but it is still paid for. Prices are per million tokens: the lesson's example prices are $1.00 for input and $5.00 for output.

Your program must print this (the last line is added by the check):

Mug: A sturdy ceramic mug that keeps your coffee warm and your mornings bright.
Notebook: A pocket-sized notebook with smooth pages for your lists, sketches and big ideas.
Lamp: skipped, the answer was cut
Pen: A smooth-writing pen that never skips, ready for notes, lists and signatures.
Plant: An easy-care green plant that brings a breath of fresh air to any room.
Teapot: A classic ceramic teapot that pours four warm cups without spilling a drop.
Stapler: A solid desk stapler that holds your papers together, page after page.
Gift card: skipped, the answer was cut
Total cost in dollars: 0.001181
Model calls: 8

Your task: the client, the prices, SYSTEM, PROMPT and the database connection db are already there. Read the product names from shop.db, ask the model for one line about each product, print each name with its description, report the answers that were cut instead of printing them, and print the total cost of the run, rounded to 6 decimals.


Assignment
Follow the Coding Tutorial to build the loop over the products, the model call, the check for cut answers and the total cost.


Hint
The two token counters start at 0 before the loop and grow right after the call, before the if that skips cut answers. The cost is computed once, after the loop, and divided by 1000000 because the prices are per million tokens.


STEP 1 OF 12
    Ctrl + Enter to check