Sub topic 5
Keeping Templates in Files, Not Code
This chapter assumes you can write basic Python, read YAML, use Git, and have already rendered a template with string.Template. It covers how to move prompt text out of your source files and load it back safely.
Why hard-coded prompts become a problem
A prompt written as a string inside a function works at first. Over time it causes trouble:
- A wording change needs a code change, a code review, and a deploy.
- Reviewers see a prompt edit buried among logic changes.
- The same prompt gets copied into several files and the copies drift apart.
- Nothing records which wording was live last month.
Moving templates into their own files fixes these. The prompt becomes a reviewable text artifact, and the code only loads and renders it.
One template, one file
A template file holds the prompt text plus the data that describes it. YAML suits this because it handles multi-line text well.
name: summarize
version: 1.2.0
changelog: Ask for a one-sentence answer when the text is short.
variables: [style, text]
template: |
Summarize the following text in $style style.
If the text is under 50 words, answer in one sentence.
$textThe | after template: starts a block scalar. YAML keeps the line breaks inside it exactly, which matters because newlines are part of the prompt.
The variables list declares which names the template expects. The next section uses it to check inputs.
A directory layout
Give each prompt its own folder, and give each version its own file:
prompts/
summarize/
1.1.0.yaml
1.2.0.yaml
classify/
1.0.0.yamlOld versions stay in place. Adding a version means adding a file, not overwriting one. Git still tracks every change, and the folder shows the full history at a glance.
Loading a template
import yaml
from pathlib import Path
def load_prompt(name, version):
path = Path("prompts") / name / f"{version}.yaml"
return yaml.safe_load(path.read_text())
PINNED = {"summarize": "1.2.0"}
prompt = load_prompt("summarize", PINNED["summarize"])Two details matter here.
yaml.safe_loadparses plain data only.yaml.loadwith an unsafe loader can construct arbitrary Python objects, so avoid it for files that anyone else can edit.PINNEDis the single place that decides which version the application uses. Changing a version is then a one-line edit. A later chapter covers pinning in detail.
Connecting loading to rendering
Loading and rendering fit together in a short function. It reuses the declared variables list for validation, so the file itself defines what inputs are legal.
import yaml
from pathlib import Path
from string import Template
def load_prompt(name, version):
path = Path("prompts") / name / f"{version}.yaml"
return yaml.safe_load(path.read_text())
def render_prompt(name, version, values):
prompt = load_prompt(name, version)
declared = set(prompt["variables"])
missing = declared - values.keys()
extra = values.keys() - declared
if missing or extra:
raise ValueError(f"missing={sorted(missing)} extra={sorted(extra)}")
return Template(prompt["template"]).substitute(values)
print(render_prompt("summarize", "1.2.0", {"style": "concise", "text": "Cats sleep a lot."}))This runs as shown once prompts/summarize/1.2.0.yaml exists with the content above.
Common errors
- File not found. The version string in
PINNEDdoes not match a filename.1.2and1.2.0are different files. Pick one format and keep it. - Declared and used variables disagree. The
variableslist says[style, text]but the template also uses$tone. Rendering then raisesKeyError. Update both together, and review them together. - Edited in place. Someone changes
1.2.0.yamlwithout making a new file. Any application pinned to that version silently changes behavior. Treat published version files as read-only. - Stray dollar signs.
Templatetreats$as a placeholder marker. A literal price such as$5fails. Write$$5to produce a single$.
Where to put the files
Keep the prompts/ folder in the same repository as the application at first. Prompt changes then go through the same pull requests as code, and a single commit can change a prompt and the code that depends on it. Separate repositories or a registry become worth it when several services share prompts. A later chapter covers those options.
Exercise
A teammate fixes a typo directly in prompts/summarize/1.2.0.yaml, which production has pinned. What goes wrong, and what should they have done?
Show answer
Production behavior changes without any version change, so logs that say "1.2.0" no longer identify one exact prompt, and the change skips the pin-and-release step. They should have copied the file to a new version such as 1.2.1.yaml, edited that copy, updated its changelog, and updated PINNED after review.
Exercise
Why does render_prompt read the variable list from the YAML file instead of keeping a REQUIRED set in Python?
Show answer
The file then states its own contract. Changing the template and its variables happens in one place and one review, and the Python code does not need an edit for each new prompt.