Sub topic 3
Rendering Templates and Validating Inputs
This chapter assumes you can write basic Python, have sent prompts to a large language model, and know what a template with named variables looks like. It covers how to render a template and how to make bad inputs fail before they reach the model.
What rendering means
Rendering is the step that replaces each variable in a template with a real value and produces the final prompt text. The template holds the fixed instructions. The values hold the parts that change on each call.
Python's standard library has string.Template for this. It marks variables with a $ prefix.
from string import Template
template = Template("Summarize the following text in $style style:\n\n$text")
prompt = template.substitute(
style="concise",
text="Prompt templates separate fixed instructions from variable input.",
)
print(prompt)The substitute method raises KeyError if a variable has no value. That is useful. A missing value stops the program instead of sending a prompt that still contains the literal text $style.
The render flow
Common errors in rendering
Three mistakes account for most rendering bugs.
| Mistake | What happens | Result |
|---|---|---|
| Missing variable | `substitute` raises `KeyError` | Fails early, but the message names only the first missing key |
| Extra variable | `substitute` ignores it | Silent. Usually a typo or a stale caller |
| Misspelled variable | Looks like a missing variable plus an extra one | Silent if you use `safe_substitute` |
The method safe_substitute leaves unknown placeholders in the output instead of raising an error. Avoid it for prompts. A prompt that contains a raw $style reaches the model and produces a poor answer that nobody can explain.
Extra values are the quiet problem. If a caller passes stlye="concise" along with the correct keys, nothing fails. The typo goes unnoticed until someone reads the output.
Validate before you render
Declare the variables a template needs, then compare them with the values you received. Report both problems in one message.
from string import Template
REQUIRED = {"style", "text"}
def render(template_text, values):
missing = REQUIRED - values.keys()
extra = values.keys() - REQUIRED
if missing or extra:
raise ValueError(f"missing={sorted(missing)} extra={sorted(extra)}")
return Template(template_text).substitute(values)Here is how it behaves with a misspelled key.
template_text = "Summarize the following text in $style style:\n\n$text"
try:
render(template_text, {"stlye": "concise", "text": "Hello"})
except ValueError as error:
print(error)The output is missing=['style'] extra=['stlye']. The message shows the typo directly, so the fix takes seconds.
The REQUIRED set is written by hand here, which means it can drift from the template. A later chapter stores the declared variables next to the template in a file, so they are reviewed together.
Check values, not only names
Names can match while the values are still wrong. Consider a few cheap checks that catch real failures:
- Reject empty strings. An empty
textproduces a prompt that asks the model to summarize nothing. - Limit length. A very long value can push the prompt past the model's context window or raise cost.
- Check allowed choices. If
stylemust beconciseordetailed, test for those values.
ALLOWED_STYLES = {"concise", "detailed"}
MAX_TEXT_CHARS = 20000
def check_values(values):
if values["style"] not in ALLOWED_STYLES:
raise ValueError(f"unknown style: {values['style']!r}")
text = values["text"].strip()
if not text:
raise ValueError("text is empty")
if len(text) > MAX_TEXT_CHARS:
raise ValueError(f"text is {len(text)} characters, limit is {MAX_TEXT_CHARS}")Call check_values after the name check and before substitute. Keep the limits in constants so they are easy to find and change.
Values inserted by substitute are not re-scanned, so a $ inside a value is safe. Only the template text is parsed for placeholders.
Summary of the approach
- Declare the variables each template needs.
- Compare supplied names against the declaration and fail on missing or extra ones.
- Check values for emptiness, length, and allowed choices.
- Render with
substitute, neversafe_substitute.
Exercise
A caller renders the template "Translate $text into $language" with the values text="Good morning" and lang="French". Using the render function from this chapter with REQUIRED = {"text", "language"}, what error message is raised, and why is it better than the error from calling substitute directly?
Show answer
The message is missing=['language'] extra=['lang']. It names both the absent variable and the misspelled key, so the typo is clear at once. Calling substitute directly would raise only KeyError: 'language', which does not show the stray lang key.