Sub topic 3
Rendering Templates and Validating Inputs
This chapter covers how a template becomes a final prompt string, and how to stop bad inputs from reaching the model. It assumes you can write basic Python (functions, classes, dictionaries, exceptions), that you have sent prompts to a language model, and that you know what a template with named variables is. The examples use string.Template from the standard library. The get_identifiers method needs Python 3.11 or later.
What rendering means
Rendering is the step that takes a template and a set of values and produces the exact text sent to the model. A template such as Summarize the following text in $style style:\n\n$text has two placeholders, $style and $text. Rendering replaces each placeholder with the matching value.
Rendering is plain string work, so it is easy to treat it as unimportant. It matters for two reasons:
- The model never sees your template, only the rendered result. A leftover
$textor a strayNonein that result is a prompt bug, and the model will try to answer anyway. You may see nothing wrong except a worse answer. - Rendering sits at the boundary between your fixed instructions and data from elsewhere: users, databases, other services. Mistakes at this boundary are the most common source of broken prompts in production.
The diagram shows the pipeline this chapter builds.
Rendering with string.Template
string.Template uses $name or ${name} placeholders. It has two rendering methods with different failure behavior, shown here.
from string import Template
t = Template("Hello $name, you owe $$5 for ${item}s.")
print(t.substitute(name="Ana", item="apple"))
# Hello Ana, you owe $5 for apples.
try:
t.substitute(name="Ana")
except KeyError as err:
print("KeyError:", err)
# KeyError: 'item'
print(t.safe_substitute(name="Ana"))
# Hello Ana, you owe $5 for ${item}s.
print(t.substitute(name="Ana", item="apple", unused="x"))
# Hello Ana, you owe $5 for apples.Four rules follow from this example:
substituteraisesKeyErrorwhen a placeholder has no value. This is the behavior you want for prompts.safe_substituteleaves unfilled placeholders in the output as literal text. It never raises for missing keys. For prompts, that means the model receives the text${item}with no warning to you. Avoid it unless you have a specific reason.- Extra keys are ignored silently by both methods. A misspelled variable name therefore produces two problems: a missing key, and an extra key that nothing reports. Only the first one raises.
$$produces a literal dollar sign. Any$in your template that is not meant as a placeholder must be doubled. A$followed by something that cannot be a name, such as a space, makessubstituteraiseValueError.
Rule 3 is why the standard library alone is not enough. You need your own check for extra values.
Why Template and not str.format
Prompts often contain curly braces, for example when you show the model a JSON format. str.format treats every brace as a placeholder, so this breaks:
json_template = 'Return JSON like {"label": "..."} for: {text}'
# json_template.format(text="hi") raises KeyError,
# because Python reads {"label": "..."} as a placeholder.Template only reacts to $, so braces pass through untouched:
from string import Template
t = Template('Return JSON like {"label": "..."} for: $text')
print(t.substitute(text="hi"))
# Return JSON like {"label": "..."} for: hiThe cost is that dollar amounts in your instructions need $$. Pick the engine whose special character appears least in your prompts. Jinja2 is a third option that adds loops and conditionals. It is more powerful, and also easier to misuse, because template logic can hide behavior that is hard to review.
Values are inserted once
Template does a single pass. A value that contains $ is not scanned for placeholders:
from string import Template
print(Template("Say: $text").substitute(text="$style"))
# Say: $styleThis prevents one accidental problem: a value cannot trigger substitution of another variable. It does not protect the prompt from the content of the value. A user can still write "ignore the instructions above" in text. That is a separate problem, covered in the next chapter.
Declaring variables
The first validation step is to say, in one place, which variables a template takes. In the spine's example, a REQUIRED set does this. Checking supplied values against the declared set catches both kinds of mistake in one step:
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)Sorting the names makes the error message stable, which helps in tests and logs. The message names both lists, so a typo such as txt instead of text shows up as missing=['text'] extra=['txt'].
This function has a weakness: the declared set and the template text are separate, so they can drift apart. If someone adds $audience to the template and forgets to update REQUIRED, substitute still raises KeyError at render time, but the error message is less clear. If someone removes a variable from the template and leaves it in REQUIRED, callers keep supplying a value that is ignored.
Checking the declaration against the template
Template.get_identifiers() returns the placeholder names a template actually uses. You can compare that list with the declared variables when the template is loaded, before any request arrives.
from string import Template
class PromptTemplate:
def __init__(self, name, text, variables, max_chars=20_000):
self.name = name
self.text = text
self.variables = frozenset(variables)
self.max_chars = max_chars
used = frozenset(Template(text).get_identifiers())
if used != self.variables:
raise ValueError(
f"{name}: declared={sorted(self.variables)} used={sorted(used)}"
)
def render(self, **values):
missing = self.variables - values.keys()
extra = values.keys() - self.variables
if missing or extra:
raise ValueError(
f"{self.name}: missing={sorted(missing)} extra={sorted(extra)}"
)
for key, value in values.items():
if not isinstance(value, str):
raise TypeError(
f"{self.name}: {key} must be str, got {type(value).__name__}"
)
if not value.strip():
raise ValueError(f"{self.name}: {key} is empty")
if len(value) > self.max_chars:
raise ValueError(
f"{self.name}: {key} has {len(value)} chars, limit {self.max_chars}"
)
return Template(self.text).substitute(values)This class fails at two points. The constructor fails when the declaration and the template disagree. That is a developer error, so it should surface at startup or in a test run. The render method fails when a caller supplies the wrong values. That is a runtime error, and it should stop the call before it reaches the model.
Using it:
summarize = PromptTemplate(
name="summarize",
text="Summarize the following text in $style style.\n\n$text",
variables=["style", "text"],
)
print(summarize.render(style="concise", text="Prompt templates separate fixed instructions from input."))
try:
summarize.render(style="concise")
except ValueError as err:
print(err)
# summarize: missing=['text'] extra=[]The class accepts keyword arguments only, which stops callers from passing values by position and mixing up the order.
What to validate in values
Name checks are the minimum. Each of these value checks catches a real failure:
- Type. Passing
Noneor a number into$textrenders the stringsNoneor42in the prompt.Template.substitutecallsstr()on non-string values, so nothing fails. Theisinstancecheck turns this into a clear error. If you do accept numbers, convert them explicitly at the call site. - Empty values. An empty or whitespace-only
textusually means an upstream bug, such as a failed file read. The model will respond to the empty input with a plausible but meaningless answer, so refuse it. - Length. A value much larger than expected can push the prompt over the model's context window, or raise cost without warning. A character limit is a rough guard. It is cheap and needs no tokenizer. A token count is more accurate if you need it.
- Allowed choices. If
stylemust be one ofconcise,detailed, orbullets, check that. A free-formstylevalue becomes part of your instructions, and a typo there changes behavior without any error.
Here is the allowed-choices check as a small extension:
ALLOWED_STYLES = {"concise", "detailed", "bullets"}
def render_summary(text, style):
if style not in ALLOWED_STYLES:
raise ValueError(f"style must be one of {sorted(ALLOWED_STYLES)}, got {style!r}")
return summarize.render(style=style, text=text)Keep this kind of rule in the code that calls the template, not inside the generic PromptTemplate class. The class should know about variables in general. Rules about particular variables belong to the prompt's callers.
Whitespace and multi-line values
Whitespace is part of the prompt. Two common problems:
- Indentation in templates. If you write a template inside an indented Python block using a triple-quoted string, the leading spaces become part of the prompt. Either keep the template in a file (the topic of a later chapter) or use
textwrap.dedent. - Multi-line values. A value containing several lines is inserted as-is, and
Templatedoes not re-indent the lines after the first. If the placeholder sits in the middle of an indented block, only the first line is indented. Put placeholders for long values on their own line, with no indentation.
Strip trailing whitespace from values at the call site if it matters. A trailing newline in text adds a blank line before whatever follows the placeholder in the template.
Testing validation
Validation code is easy to test, because its failures are exceptions. A few tests per template are enough. They use pytest, which you may need to install.
import pytest
def test_missing_variable():
with pytest.raises(ValueError, match="missing=\\['text'\\]"):
summarize.render(style="concise")
def test_extra_variable():
with pytest.raises(ValueError, match="extra=\\['tone'\\]"):
summarize.render(style="concise", text="hi", tone="formal")
def test_non_string_value():
with pytest.raises(TypeError):
summarize.render(style="concise", text=None)
def test_declaration_matches_template():
with pytest.raises(ValueError):
PromptTemplate("bad", "Hello $name and $other", ["name"])The last test is the one people skip. It confirms that the constructor really rejects a template whose declaration is out of date.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| `KeyError` at render time | A placeholder has no value | Check missing names before calling `substitute` |
| Literal `$text` in the model's input | `safe_substitute` was used | Use `substitute` |
| `ValueError: Invalid placeholder` | A bare `$` in the template, for example a price | Write `$$` |
| Output mentions `None` | A `None` value was converted to text | Check types before rendering |
| Value silently ignored | A misspelled variable name, with extra values not rejected | Reject extra names |
| `KeyError` on a brace such as `"label"` | `str.format` was used on a template that contains JSON | Use `Template`, or double the braces |
Where validation stops
Validation ensures the prompt is well-formed: every variable is present, of the right type, and of reasonable size. It does not tell you whether the content is safe or whether the model will behave well. A value can pass every check above and still contain text meant to override your instructions. The next chapter covers that case.
Exercise
A teammate adds $audience to a template's text but forgets to add audience to the declared variables list. Using the PromptTemplate class from this chapter, at what point does the mistake surface, and what does the error report?
Show answer
It surfaces in the constructor, when the template is created, before any render call. The comparison of get_identifiers() against the declared set fails, and the ValueError reports declared=['style', 'text'] used=['audience', 'style', 'text'] (with the template's own variable names). This is earlier and clearer than the KeyError that substitute would raise at request time.
Exercise
A function renders the prompt with safe_substitute and the caller passes {"style": "concise"} for a template that needs style and text. What does the model receive, and why is this worse than an exception?
Show answer
The model receives the prompt with the literal text $text where the input should be. safe_substitute leaves unfilled placeholders in place and raises nothing, so the call goes ahead and the model answers a prompt with no real input. The bug appears only as a poor output, which is much harder to trace than an immediate error.
Exercise
Write the check that rejects a text value longer than 5,000 characters, and say why a limit on characters is only an approximation of the real constraint.
Show answer
if len(text) > 5000: raise ValueError("text too long"). The real constraint is the model's context window, which is measured in tokens, not characters. The number of tokens per character varies with language and content, so a character limit is a cheap guard, and a tokenizer gives an exact count.