Sub topic 5
Keeping templates in files, not code
This chapter moves prompt templates out of Python strings and into files that the application loads at startup. It assumes you can write basic Python, use Git, read YAML, and already know how string.Template fills $variables from the previous chapter.
Why hard-coded prompts stop scaling
A prompt written as a string literal works fine at first. Problems show up as the prompt grows and more people touch it:
- Every wording change is a code change. It goes through the same review, build, and deploy path as a bug fix, even though the logic did not change.
- Diffs are noisy. A multi-line prompt inside an indented function, with escaped quotes and
\nsequences, is hard to read in a pull request. - Non-programmers cannot review it. A domain expert or editor who should approve the wording has to read Python.
- Copies drift. The same instructions get pasted into three modules, and one of them gets fixed.
- There is nowhere to put metadata. A bare string has no room for a version, a change note, or the list of variables it expects.
Keeping each template in its own file fixes these. The file becomes the unit you review, version, test, and roll back. The code becomes a loader that reads the file and renders it.
The working model
The application holds no prompt text. It holds a name and a version, and it asks a loader for the matching file.
Two points follow from this design:
- Validation happens when the file is loaded, not when a user request arrives. A broken template should stop a deploy or a test run, not produce a half-filled prompt in production.
- Rendering is separate from loading. You load a template once and render it many times with different values.
A file layout that scales
Use one directory per prompt name and one file per version:
prompts/
summarize/
1.0.0.yaml
1.1.0.yaml
1.2.0.yaml
classify_ticket/
0.3.0.yamlOld versions stay in the directory. That is what makes rollback a one-line change later, because the previous file still exists. Git history would also let you recover it, but a file on disk can be loaded by a test that compares two versions side by side.
The template file itself carries the prompt and its metadata:
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.
$textSave this as prompts/summarize/1.2.0.yaml.
Why the version is quoted
version: 1.2.0 happens to parse as a string, because 1.2.0 is not a valid number. But version: 1.2 parses as the float 1.2, and version: 1.10 becomes 1.1. Quoting the value always gives you a string. Make it a habit so a future two-part version does not silently change.
Block scalars and trailing newlines
The | after template: starts a literal block. Line breaks are kept exactly as written. The block ends with one trailing newline, which then becomes part of the prompt. If you do not want it, write |- to strip it. Pick one style and use it in every file, because a stray newline changes the text the model sees.
Writing a loader that fails early
The loader below does four jobs: it validates the name and version, reads the file, checks that the file agrees with its own path, and checks that the declared variables match the placeholders in the text. It needs Python 3.11 or later for Template.get_identifiers(), and the PyYAML package.
import os
import re
from dataclasses import dataclass
from pathlib import Path
from string import Template
import yaml
PROMPT_ROOT = Path(os.environ.get("PROMPT_ROOT", "prompts"))
NAME_RE = re.compile(r"^[a-z][a-z0-9_-]*$")
VERSION_RE = re.compile(r"^\d+\.\d+\.\d+$")
@dataclass(frozen=True)
class PromptTemplate:
name: str
version: str
variables: frozenset
text: str
def render(self, **values):
provided = set(values)
missing = self.variables - provided
extra = provided - self.variables
if missing or extra:
raise ValueError(
f"{self.name}@{self.version}: "
f"missing={sorted(missing)} extra={sorted(extra)}"
)
return Template(self.text).substitute(values)
def load_prompt(name, version):
if not NAME_RE.match(name) or not VERSION_RE.match(version):
raise ValueError(f"invalid prompt reference: {name!r} {version!r}")
path = PROMPT_ROOT / name / f"{version}.yaml"
data = yaml.safe_load(path.read_text(encoding="utf-8"))
if data.get("name") != name or data.get("version") != version:
raise ValueError(f"{path}: name/version fields do not match the path")
template = Template(data["template"])
if not template.is_valid():
raise ValueError(f"{path}: template contains an invalid placeholder")
declared = set(data["variables"])
used = set(template.get_identifiers())
if declared != used:
raise ValueError(
f"{path}: declared={sorted(declared)} used={sorted(used)}"
)
return PromptTemplate(name, version, frozenset(declared), data["template"])
if __name__ == "__main__":
prompt = load_prompt("summarize", "1.2.0")
print(prompt.render(style="concise", text="Cats sleep a lot."))Running it from the directory that contains prompts/ prints:
Summarize the following text in concise style.
If the text is under 50 words, answer in one sentence.
Cats sleep a lot.What each check protects against
| Check | Failure it catches |
|---|---|
| `NAME_RE` and `VERSION_RE` | Path traversal such as `../../etc/passwd` passed as a name, and typos like `v1.2` |
| `yaml.safe_load` | Arbitrary object construction from a malicious or damaged file. Never use `yaml.load` on files you did not write |
| Name and version match the path | A file copied to a new version number without updating its contents |
| `is_valid()` | A stray `$` in the prompt text, which would raise an error only at render time |
| Declared equals used variables | A variable added to the text but not declared, or declared but no longer used |
The declared list may look redundant, since the loader can already discover the placeholders. It is still worth keeping. A reviewer sees the interface of the prompt at the top of the file, and any change to it shows up as a separate line in the diff.
Literal dollar signs
string.Template treats $name as a placeholder. A prompt that mentions a price, such as "costs $5", would be read as a placeholder or rejected as invalid. Write $$ for a literal dollar sign:
name: price_check
version: "0.1.0"
changelog: Initial version.
variables: [product]
template: |
State whether $product costs more than $$20.The is_valid() check in the loader catches the unescaped form at load time instead of during a request.
Locating files reliably
A relative path like Path("prompts") depends on the directory the process starts in. It works in your terminal and breaks under a test runner, a scheduler, or a container with a different working directory. There are three common fixes:
- Read the root from an environment variable, as the loader above does with
PROMPT_ROOT. - Resolve the path from the code's own location, for example
Path(__file__).parent / "prompts". - If you ship the application as a package, include the prompt files in the package data and read them with
importlib.resources.
The third option matters more than it looks. A common production failure is that prompts exist in the repository but were never copied into the built container image or wheel. Test the built artifact, not only the source tree.
Caching and reloading
Reading and parsing a file on every request wastes time and makes failures show up late. Two simple policies cover most cases:
- Load once at startup and keep the templates in memory. This is the safest default. The running process always uses the version it started with.
- Reload on demand, for example through an admin endpoint. This lets you change prompts without a restart, but then two instances can briefly serve different versions, which makes behavior harder to explain.
If you use functools.lru_cache on load_prompt, remember that it never notices file edits. That is acceptable for versioned, immutable files, and one more reason never to edit a released version in place.
Common errors
- Editing a released file. If
1.2.0.yamlchanges after it shipped, the label no longer identifies one text. Create1.2.1.yamlinstead. - Version number and content out of sync. The check that the fields match the file path catches the copy-and-forget case.
- Unquoted versions.
1.10becomes1.1. Quote them. - Prompts in the repository but not in the build. Verify the packaged artifact contains the files.
- Putting secrets in prompt files. Template files are committed and reviewed widely. Keep API keys and customer data out of them.
- Encoding surprises. Always pass
encoding="utf-8"when reading. The default depends on the operating system and can garble non-ASCII text. - Loading lazily. If a bad file is only discovered on the first user request, you find out in production. Load every pinned prompt at startup, and add a test that loads every file in
prompts/.
What stays in code
Moving templates to files does not mean moving everything. Keep these in code:
- The logic that chooses which prompt to use.
- The values passed into the template, and the checks on them.
- Model settings such as the model name and temperature, unless you deliberately decide to version them with the prompt.
If model settings do change output meaningfully, as temperature does, you will want to record them alongside the prompt version. Later chapters cover that when we trace outputs back to the prompt that produced them.
Exercises
Exercise
A teammate copies prompts/summarize/1.2.0.yaml to 1.3.0.yaml, rewrites the instructions, and commits it without touching the version: line inside the file. What does the loader in this chapter do when the application calls load_prompt("summarize", "1.3.0"), and why is that the right behavior?
Show answer
It raises a ValueError. The loader compares the name and version fields in the file with the name and version in the path, and "1.2.0" does not equal "1.3.0". Failing at load time stops a prompt from running under a version label that does not describe it, which would make logs and test results misleading.
Exercise
A template file contains the line Refund anything under $10. and declares variables: [text]. What happens at load time, and how do you fix the file?
Show answer
Template.is_valid() returns False because $10 is not a valid placeholder, so the loader raises a ValueError naming the file. Fix it by writing $$10 so the dollar sign is literal.
Exercise
Your tests pass locally, but the deployed service crashes with FileNotFoundError for prompts/summarize/1.2.0.yaml. Name two likely causes and one fix for each.
Show answer
First, the process runs in a different working directory, so the relative path prompts does not resolve. Fix it by setting PROMPT_ROOT or resolving the path from the module's location. Second, the prompt files were not included in the built image or package. Fix it by adding the prompts/ directory to the package data or the image's copy step, and by running the loader test against the built artifact.