Sub topic 12
Turn good prompts into reusable templates
This chapter assumes you have read the earlier chapters on goals, context, constraints, examples, output format, iteration, and verification. You should be comfortable with basic Python and with running pytest. The chapter shows how to turn a prompt that worked into a template you can reuse, share, and improve.
Why templates are worth the effort
Over a few weeks you will write many prompts that look alike: "write a function that...", "fix this error...", "add tests for...". Each time you rebuild the same structure from memory, and each time you may forget a part. Forgotten parts are the usual cause of weak output. The assistant guesses the language version, the allowed libraries, or the output shape, and the guess is wrong.
A template fixes the structure and leaves only the task-specific details blank. It gives you three things:
- Consistency. Every prompt includes goal, context, constraints, examples, and output format, in the same order.
- Speed. You fill in blanks instead of composing from scratch.
- A place to keep lessons. When you learn that the assistant keeps adding a third-party library, you add one line to the template. Every later prompt benefits.
A template does not replace thinking. A template with vague blanks produces vague prompts. It only makes it harder to skip a part by accident.
Anatomy of a code-prompt template
The template below uses five labeled fields, each matching a technique from earlier chapters.
Task: <one-sentence goal>
Context: <language and version, framework, relevant existing code, error message>
Constraints: <allowed libraries, style rules, performance limits, what not to change>
Examples: <input -> expected output pairs>
Output format: <for example, only a unified diff, or only the function>Each field has a job:
| Field | What it answers | Typical mistake when left out |
|---|---|---|
| Task | What should exist or change when this is done? | The assistant solves a nearby, easier problem. |
| Context | What can the assistant not see? | Wrong language version, invented helper functions. |
| Constraints | What is allowed, and what is off limits? | Extra dependencies, unrequested refactors. |
| Examples | What does correct behavior look like on edge cases? | Edge cases handled differently from what you expect. |
| Output format | What shape should the reply take? | Long explanations around the code you wanted. |
Keep the labels as plain words followed by a colon. Labels like these are easy for you to scan and easy for the assistant to follow. You do not need special markup.
Filling the template: the slugify prompt
Here is the earlier slugify prompt expressed in the template. Compare it with the weak original, "Write a function to clean up titles."
Task: Write a Python function slugify(text: str) -> str that converts an article title into a URL slug.
Context: Python 3.10, used in a small blog tool. Titles are plain ASCII.
Constraints: Use only the standard library. Lowercase the result. Replace each run of non-alphanumeric characters with a single hyphen. No leading or trailing hyphens.
Examples:
slugify("Hello, World!") -> "hello-world"
slugify(" Multiple spaces ") -> "multiple-spaces"
slugify("C++ & Rust") -> "c-rust"
slugify("Already-slugged") -> "already-slugged"
Output format: Return only the function, with no explanation.Nothing in this prompt is specific to slugs except the content of the fields. The same skeleton works for a date parser, a retry decorator, or a CSV cleaner. That separation between structure and content is what makes it a template.
Deciding what to make fixed and what to make variable
A good template has some text that never changes and some that you fill in each time. Sorting the parts correctly is the main design decision.
Fix these in the template (they rarely change within a project):
- The language and version, such as "Python 3.10".
- Standing constraints, such as "standard library only" or "follow PEP 8 and type-hint all signatures".
- Standing exclusions, such as "do not change public function names" or "do not add dependencies".
- The default output format, such as "return only the code".
Leave these as blanks (they change with every task):
- The one-sentence goal.
- The existing code or error message.
- The input and output examples.
- Constraints that apply only to this task, such as a performance limit.
A practical test: if you have typed the same sentence into three prompts, move it into the template. If a sentence appears in only one prompt, keep it as a blank.
Three templates for common situations
New function
This is the template from the spine. Use it when you can state the behavior but have no existing code.
Bug fix
A bug-fix prompt must contain the failing input, the observed result, and the expected result. Without all three, the assistant has to guess what "wrong" means.
Task: Fix the bug described below with the smallest possible change.
Context: Python 3.10. The function below returns the wrong result.
Code:
<paste the function>
Observed: <what happens, including the full error message or wrong output>
Expected: <what should happen>
Constraints: Do not rename functions or change their signatures. Do not touch code unrelated to the bug.
Output format: A unified diff only, followed by one sentence naming the root cause.The constraint "smallest possible change" and the diff output format work together. A diff makes any unrequested rewrite visible when you review it.
Write tests
Use this when you already have code and want tests for it.
Task: Write pytest tests for the function below.
Context: Python 3.10, pytest. The function is in module <module_name>.
Code:
<paste the function>
Constraints: Use pytest.mark.parametrize. Cover empty input, a single character, and repeated separators. Do not modify the function.
Examples: <input -> expected output pairs you already trust>
Output format: A single test file, no explanation.One caution applies here. If the assistant wrote the function and the tests from the same misunderstanding, the tests will pass while both are wrong. Supply expected values you trust from the specification, not values copied from the code's current output.
Automating the fill-in step
Copy and paste works for a handful of prompts. If you reuse templates often, a small script can enforce the rules for you. This script refuses to build a prompt when a required field is empty, and it rejects field names that do not exist in the template. That catches typos such as constraint instead of constraints.
TEMPLATE = """Task: {task}
Context: {context}
Constraints: {constraints}
Examples: {examples}
Output format: {output_format}
"""
REQUIRED = ("task", "context", "constraints", "output_format")
ALLOWED = REQUIRED + ("examples",)
def render_prompt(**fields: str) -> str:
unknown = sorted(set(fields) - set(ALLOWED))
if unknown:
raise ValueError(f"Unknown fields: {', '.join(unknown)}")
missing = [name for name in REQUIRED if not fields.get(name, "").strip()]
if missing:
raise ValueError(f"Missing required fields: {', '.join(missing)}")
values = {name: fields.get(name, "").strip() for name in ALLOWED}
if not values["examples"]:
values["examples"] = "None provided."
return TEMPLATE.format(**values)
if __name__ == "__main__":
prompt = render_prompt(
task="Write a Python function slugify(text: str) -> str that converts a title into a URL slug.",
context="Python 3.10, small blog tool, plain ASCII titles.",
constraints="Standard library only. Lowercase. One hyphen per run of non-alphanumeric characters. No leading or trailing hyphens.",
examples='slugify("Hello, World!") -> "hello-world"',
output_format="Return only the function, with no explanation.",
)
print(prompt)Running the script prints the filled-in prompt, which you paste into your assistant. Passing examples="" produces "None provided." instead of an empty line, and leaving out constraints raises a ValueError. Because str.format only parses the template string, braces inside your pasted code or examples are safe.
Keep this tool small. If it grows into a framework, you are maintaining software instead of writing prompts.
The template life cycle
A template improves through use. The loop is the same iteration you practice on single prompts, applied to the template itself.
The decision in the middle matters. Not every failure is a template problem. If the assistant misread one unusual task, fix that prompt only. If the same kind of failure happens twice, the template is missing something. Examples of template-level fixes:
- The assistant keeps importing
requests: add "standard library only" to the fixed constraints. - The assistant keeps explaining its code at length: change the default output format to "code only".
- The assistant keeps changing function signatures during bug fixes: add "do not change signatures".
Storing and organizing templates
Where you keep templates affects whether you use them.
- Keep them in the repository for project-specific templates, for example in a
prompts/directory. The language version and standing constraints then travel with the code, and teammates share them. - Keep general ones in a personal notes folder if they apply across projects.
- Use descriptive file names, such as
new-function.txtorbug-fix.txt, so you can find them in seconds. - Put a one-line note at the top saying when to use the template, and review it when you notice repeated failures.
Some assistants support saved instructions or rules files that apply to every conversation. Those suit the fixed parts of a template, such as language version and style rules, so you do not repeat them. Keep the task-specific fields in your own template.
Common template mistakes
- Too many fixed rules. A template with thirty constraints buries the important ones. Keep standing rules to the few that you have seen matter.
- Stale facts. A template that says "Python 3.8" after you upgraded to 3.12 quietly produces outdated code. Check version lines when you start work on a project.
- Blanks filled with vague text. Writing "make it good" in the Constraints field defeats the template. Each field should hold something you could check.
- Skipping verification because the prompt is polished. A strong template raises the odds of correct output but never guarantees it. Run the tests every time.
- Copying examples between tasks. Leftover examples from the last task can steer the assistant toward the wrong behavior. Clear the Examples field before each use.
Putting it together
When a prompt works, do four things:
- Save the prompt as it was sent.
- Replace the task-specific parts with labeled blanks.
- Move repeated sentences into the fixed parts.
- Add a short note on when to use it.
Then use it, verify the result, and revise the template only when the same failure repeats.
Exercise
You use a "new function" template for a project. Three times in a row, the assistant adds a third-party library such as requests even though you only wanted standard-library code. What is the best change, and why?
Show answer
Add "Use only the standard library; do not add dependencies" to the fixed Constraints text of the template. The failure repeated, so it points to something the template lacks instead of a one-off misreading. Changing the template fixes every later prompt, while editing only the current prompt would leave the next one exposed to the same problem. After the change, still verify the output, because the constraint lowers the chance of the problem but does not guarantee it.
Exercise
Write a bug-fix prompt using the structure from this chapter for this situation: average(numbers) raises ZeroDivisionError when given an empty list, and you want it to return 0.0 instead. List the fields you would fill in and say what the output format should be.
Show answer
Task: fix average so an empty list returns 0.0, with the smallest possible change. Context: Python 3.10, plus the pasted function. Observed: average([]) raises ZeroDivisionError: division by zero. Expected: average([]) returns 0.0, and average([2, 4]) still returns 3.0. Constraints: do not rename the function or change its signature, and do not change other behavior. Output format: a unified diff only, followed by one sentence naming the root cause. The diff format makes any unrequested change easy to spot during review.
Exercise
Why does the render_prompt script reject unknown field names instead of ignoring them?
Show answer
Without that check, a typo such as constraint="..." would be dropped silently, and the prompt would be built with the constraints field missing or empty. The script would either fail for the wrong reason or, if the field were optional, produce a prompt that lacks the constraints you meant to send. Rejecting unknown names turns a silent loss of information into an immediate, readable error.