Careeroza
Prompt Templates with Variables
Templates Keep Prompts Consistent
Production prompts are templates: fixed instructions plus slots for variables (customer name, order data, retrieved documents). Treat a template like code: one definition, many uses, tested and reviewed. Python's string.Template uses $name slots and does not clash with the curly braces in JSON examples, which is why it is popular for prompts.
Safe Filling and Missing Variables
Example
A wrapper that fails loudly when a variable is missing (a silent empty slot gives the model a broken prompt):
from string import Template
REPLY = Template("""You are ShopEase support.
Customer name: $name
Order: $order_id ($status)
<policy>
$policy
</policy>
Reply in JSON like {"reply": "...", "escalate": false}.
Customer message: $message""")
def render(template, **values):
needed = {m.group("named") or m.group("braced")
for m in template.pattern.finditer(template.template)
if m.group("named") or m.group("braced")}
missing = sorted(needed - values.keys())
if missing:
raise KeyError(f"missing template variables: {missing}")
return template.substitute(**values)
print(render(REPLY, name="Ravi", order_id="SE-30112", status="shipped",
policy="Orders can be cancelled until they are shipped.",
message="Cancel my order please"))
try:
render(REPLY, name="Ravi", message="hi")
except KeyError as e:
print("\nerror:", e)Output
You are ShopEase support.
Customer name: Ravi
Order: SE-30112 (shipped)
<policy>
Orders can be cancelled until they are shipped.
</policy>
Reply in JSON like {"reply": "...", "escalate": false}.
Customer message: Cancel my order please
error: "missing template variables: ['order_id', 'policy', 'status']"Note: Frameworks such as LangChain (ChatPromptTemplate) and Jinja2 templates do the same thing with more features (loops, conditions). Start with the standard library; switch when you need them.