Syllabus Lesson 124 of 239 · Prompt Engineering for AI Engineers
Prompt Engineering for AI Engineers

Reusable Prompt Templates with Variables

You rarely write a prompt once. You write a template with holes in it and fill the holes per request: a summarizer that takes {document}, a classifier that takes {text} and {labels}. Templating keeps prompts consistent, reviewable, and version-controlled instead of f-strings scattered across a codebase.

A template here is a plain string with {slot} placeholders. You will build the two functions a tiny templating engine needs:

  • find_slots(template) returns the unique slot names, sorted. Find them with the regex \{(\w+)\}, then dedupe and sort.
  • render(template, variables) substitutes every slot with its value from the variables dict, stringifying non-string values (so 7 becomes "7"). If a slot has no matching variable, raise KeyError naming what is missing.

So:

find_slots("Hi {name}, you are {age}. Bye {name}.")
# ['age', 'name']            # unique and sorted

render("Total is {count}", {"count": 7})
# 'Total is 7'               # the int was stringified

The missing-variable KeyError is the important habit. Silently rendering a prompt with a literal {document} still in it ships a broken prompt to the model and wastes a call. Failing fast at render time catches the bug in your code, not in production. Press Run to grade.

Your turn

Write find_slots(template) returning the unique {slot} names (matched by \{(\w+)\}), sorted. Write render(template, variables) that replaces every slot with str(value) from variables, and raises KeyError (naming the missing slots) if any slot has no variable. A template with no slots renders unchanged.

Spotted a problem in this lesson? Report it

Code · runs in your browser
Output