Skip to course content
Free generative AI app course

Generative AI Application Development with Python

Unit 04.00: Templates with declared variables

A template fails on a missing variable before the API call. An f-string produces a prompt about None.

Declared variables, checked at render time

string.Template with two declared variables, one deliberately omitted.

The code catches the failure and then renders correctly.

import string

TEMPLATE = ("Answer the customer's question using only the POLICY below.\n\n"
            "POLICY:\n$policy\n\nQUESTION:\n$question")
template = string.Template(TEMPLATE)

declared = {m[1] or m[2] for m in string.Template.pattern.findall(TEMPLATE) if m[1] or m[2]}
print("declared variables:", sorted(declared))

try:
    template.substitute(question="How long?")
except KeyError as exc:
    print(f"missing variable caught before the API call: {exc}")

filled = template.substitute(policy="Refunds within 7 days.", question="How long?")
print(f"\nrendered {len(filled)} chars, no unfilled placeholders: "
      f"{'$' not in filled}")

# `substitute` raises on a missing variable; an f-string with a missing value
# produces the word "None" in the prompt and a confident answer about it.

The failure happens before any tokens are spent and names the missing variable. The f-string equivalent produces a successful call, a well-formed answer about account None, and nothing in any log to suggest a problem.

Template also survives $ and { characters in user content, which str.format does not.

The mistake this prevents

The mistake is building prompts by concatenation because it reads more naturally. Every concatenated prompt is a place where a missing value becomes a plausible sentence, and plausible wrong sentences are the failure this whole course is about.

Takeaway

Use a template with declared variables so a missing value fails before the call. Concatenation turns a missing value into a confident answer about nothing.