Start learning free

LESSON 22 OF 129 · AI ENGINEERING: PROMPTS THAT HOLD UP

Prompt Templates in Python

Practice

When you need the same kind of prompt for many things, don't write each one by hand. Write the instruction once, as a template: a string with a named gap in curly braces where each changing part goes.

Filling the gaps: a string's .format method returns a copy of the string with each gap replaced by the argument of the same name. The template itself never changes, so it can be filled again and again.

GREETING = "Hello {name}, your order ships on {day}."

print(GREETING.format(name="Ana", day="Monday"))
# Hello Ana, your order ships on Monday.
print(GREETING.format(name="Ben", day="Friday"))
# Hello Ben, your order ships on Friday.

A small function that fills the template keeps the rest of the program away from the wording. To change how every prompt is written, you change one string. To cover one more product, you add one item to a list.

In this lesson the Corner Shop wants a selling line for each of its three products, each for its own audience. Your program must print every prompt and the model's answer to it:

Prompt: Write one sentence that sells the Teapot to tea lovers. No emojis.
Answer: Brew every cup just the way you like it with a teapot made for people who take their tea seriously.
Prompt: Write one sentence that sells the Lamp to students. No emojis.
Answer: Study late without tired eyes under a lamp that fits on the smallest desk.
Prompt: Write one sentence that sells the Plant to people who work from home. No emojis.
Answer: Give your home office a quiet green corner with a plant that asks for water only once a week.

Your task: client, MODEL and the list products are already there. Make TEMPLATE, the instruction with a {product} gap and an {audience} gap. Write build_prompt(product, audience), which returns the filled template. Then loop over products: build the prompt, print it after "Prompt:", send it to the model as one user message, and print the reply's text after "Answer:".


Assignment
Follow the Coding Tutorial to write the template, the build_prompt function and the loop that builds, prints and sends a prompt for each product.


Hint
The template is "Write one sentence that sells the {product} to {audience}. No emojis.": the braces are typed as they are. Give .format two named arguments, one for each gap. Each item of products is a dict with the keys "name" and "audience".


STEP 1 OF 8
    Ctrl + Enter to check

    Ai Prompt Templates 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