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 thevariablesdict, stringifying non-string values (so7becomes"7"). If a slot has no matching variable, raiseKeyErrornaming 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 stringifiedThe 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.
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.
This lesson is locked
Lessons open one at a time. Finish the previous lesson to unlock this one.