Sub topic 3
Turning a good prompt into a reusable template
A prompt that worked once is an asset, but you can't hand it to a teammate or run it next week without changes. This chapter shows how to turn it into a template: fixed instructions with named slots, filled in by a small piece of code. It assumes you have written prompts for a generative AI assistant and can read short Python snippets. You also need to know what the inputs, steps, and outputs of a workflow are, from the previous chapter.
Why copy-and-edit prompts fail
Most teams start by keeping a good prompt in a document and editing it by hand each time. This causes three problems:
- Silent drift. Someone trims a constraint to save time, and a month later the posts no longer match the brand.
- Missed edits. The prompt still says "spring discount" in the summer, because nobody changed one sentence.
- No testing. If every run uses a slightly different prompt, you can't tell whether a bad output came from the model or from the edit.
A template separates what never changes (the instructions) from what changes every run (the inputs). The instructions can then be reviewed, tested, and versioned once.
Find the parts that change
Take a prompt that has already produced a good result and mark every piece of text that would differ next time. Here is a working prompt for a social post:
You are writing for Acme Cycles. Voice: friendly, plain, no hype.
Write a LinkedIn post announcing: our spring service discount
Audience: commuter cyclists
Constraints: at most 90 words; end with one call to action.Sort each piece into one of three groups:
| Piece of text | Group | Becomes |
|---|---|---|
| "Acme Cycles" | Changes rarely (brand context) | `$brand_name` |
| "friendly, plain, no hype" | Changes rarely (brand context) | `$voice` |
| "LinkedIn" | Changes per run | `$channel` |
| "our spring service discount" | Changes per run | `$announcement` |
| "commuter cyclists" | Changes per run | `$audience` |
| "90" | Changes per run, with a sensible default | `$max_words` |
| "end with one call to action" | Never changes | stays as fixed text |
The "never changes" group is the template's real value. It holds the rules you worked out through trial and error. Leave them as plain text, not as inputs. If you make everything an input, the template turns into an empty form and the person filling it in has to remember the rules again.
Build the template with named placeholders
Python's standard library has string.Template. It uses $name placeholders, and its substitute() method raises an error if an input is missing.
from string import Template
TEMPLATE = Template(
"You are writing for $brand_name. Voice: $voice.\n"
"Write a $channel post announcing: $announcement\n"
"Audience: $audience\n"
"Constraints: at most $max_words words; end with one call to action."
)
prompt = TEMPLATE.substitute(
brand_name="Acme Cycles",
voice="friendly, plain, no hype",
channel="LinkedIn",
announcement="our spring service discount",
audience="commuter cyclists",
max_words=90,
)
print(prompt)Run it and you get the original prompt back. Change channel to "Instagram" and max_words to 40, and the same template gives you a different post brief with no other edits.
Name placeholders for meaning
Name each placeholder for what it holds, not for where it sits. $announcement tells the next person what to supply. $text1 does not. Names also become the keys in any later step that fills the template, so they need to stay stable. Renaming a placeholder later breaks every caller.
Fail loudly on missing inputs
substitute() raises a KeyError if a placeholder has no value. This is the behavior you want. A missing audience should stop the run, not send the model a prompt that says "Audience: " and let it guess.
Template also has safe_substitute(), which leaves unfilled placeholders in the text as literal $audience. That version hides mistakes, because the model receives the raw placeholder and often writes around it. Use substitute() for any workflow that runs without someone watching.
Add defaults, checks, and a wrapper function
A bare substitute() call catches missing keys but not empty values, typos in extra keys, or inputs that should have a default. A small wrapper function handles these cases in one place.
from string import Template
TEMPLATE = Template(
"You are writing for $brand_name. Voice: $voice.\n"
"Write a $channel post announcing: $announcement\n"
"Audience: $audience\n"
"Constraints: at most $max_words words; end with one call to action."
)
DEFAULTS = {"voice": "friendly, plain, no hype", "max_words": 90}
def render(template, **inputs):
values = {**DEFAULTS, **inputs}
# Reject empty or whitespace-only values.
for name, value in values.items():
if str(value).strip() == "":
raise ValueError(f"Input '{name}' is empty")
# Reject inputs the template does not use (for example, a typo).
# Template.get_identifiers() needs Python 3.11 or newer.
unknown = set(values) - set(template.get_identifiers())
if unknown:
raise ValueError(f"Unknown inputs: {sorted(unknown)}")
return template.substitute(values)
print(
render(
TEMPLATE,
brand_name="Acme Cycles",
channel="LinkedIn",
announcement="$50 off any spring tune-up",
audience="commuter cyclists",
)
)This run relies on the defaults for voice and max_words. If you write audiance="..." by mistake, the call fails with a clear message instead of a vague KeyError.
Note that announcement contains a dollar sign. That is safe here, because substitute() does not scan the values it inserts. Dollar signs cause trouble only in the template text itself.
Edge cases to know about
Each of these has caught real teams, so check for them before you share a template.
- A literal dollar sign in the template. Writing
"Save $50"in the template text raises aValueError, because$5is not a valid placeholder name. Write$$50to get a single$. - Placeholder next to text. In
"$channelposts"Python reads the name aschannelposts. Use braces to mark the end:"${channel}posts". - Braces in the template.
string.Templateignores{}unless they follow a$. This matters when your prompt includes a JSON example. Withstr.format(), which uses{name}, every literal brace must be doubled ({{and}}), and a forgotten one raises an error. For prompts that contain JSON,Templateis the easier choice. - Numbers and other non-text values.
substitute()converts values to text, somax_words=90works. A list would appear as Python's['a', 'b']text. Convert lists yourself, for example with", ".join(items), so the model sees clean text. - Multi-line inputs. A pasted campaign brief with blank lines and headings can blur into your instructions. Fence long inputs with clear delimiters in the template, such as a line reading
Brief (between the markers):followed by---before and after the slot. - Untrusted input. Text from a web form, an email, or a customer review may contain instructions such as "ignore the rules above". Placing it in a slot does not make it safe. Label it as material to work on, keep the rules outside the slot, and put a human review step after the model call. Chapter 7 covers review placement.
Decide what belongs in the template
A reusable template needs a deliberate boundary. Use these rules:
- Make something an input if it differs between runs and the person running the workflow knows the value (channel, audience, announcement).
- Give it a default if one value is right most of the time (word limit, tone). People can override it without having to remember it.
- Move it into shared brand context if it is the same across many templates (voice, banned phrases, legal wording). The next chapter covers this.
- Keep it as fixed text if it encodes a rule you never want edited casually (the call-to-action rule, the output format).
A common mistake is putting a whole prior output into a slot named $example and then forgetting it. Examples inside a template are fine, but they are fixed instructions, so version them like the rest of the text.
Test the template before you trust it
Before you share a template, check four things:
- It renders with only the required inputs and the defaults.
- It fails with a clear error when a required input is removed.
- The rendered prompt, read top to bottom, matches the original working prompt for the same inputs. Comparing the two texts is a quick regression check.
- The model's output with the new template is as good as the output with the hand-written prompt on at least three different input sets.
Check 3 is a plain string comparison. Check 4 is a judgment call, and a later chapter on testing with fixed inputs and a checklist makes it systematic.
Summary
- A template holds fixed instructions and named slots. Inputs change per run, and the rules stay put.
- Use
Template.substitute()so a missing input stops the run. - Wrap rendering in one function that applies defaults, rejects empty values, and flags unknown inputs.
- Watch for
$in template text, placeholders touching other text, and braces in JSON examples. - Treat text from outside your team as material to process, not as part of your instructions.
Exercise
A teammate adds the line "Offer: save $20 on your first order" directly into the template text of a Template-based prompt. What happens when render() runs, and how do you fix it in two different ways?
Show answer
substitute() raises a ValueError, because "$20" is not a valid placeholder name. Fix 1: escape the dollar sign in the template text as "$$20". Fix 2: replace the fixed amount with a placeholder such as "$offer" and pass offer="save $20 on your first order" as an input. A dollar sign in an input value is safe because substitute() does not rescan inserted values.
Exercise
Take this working prompt and name the placeholders, defaults, and fixed text you would use: "Write a 120-word email to returning customers of Northwind Coffee about our new decaf blend. Keep the tone warm and casual. Never mention price. End with a link to the shop page."
Show answer
Placeholders: $brandname (Northwind Coffee), $audience (returning customers), $topic (our new decaf blend), and $maxwords with a default of 120. Defaults or brand context: the tone ("warm and casual") can be a $voice default. Fixed text: "Never mention price" and "End with a link to the shop page", because both are rules that should not be edited casually. The channel (email) could also become a $channel input if the template will serve other channels.
Exercise
Why is substitute() safer than safe_substitute() for a workflow that runs on a schedule with no one watching?
Show answer
substitute() raises an error when an input is missing, so the run stops and someone is told. safe_substitute() leaves the raw placeholder (for example "$audience") in the prompt text, so the model receives it as ordinary text and may produce a plausible draft that ignores the missing input. With no one watching, that bad draft can move on to later steps.