Unit 02.01: Prompt templates with validated inputs
The main thing a template gives you over an f-string is that it fails before the model call rather than after.
Declared inputs, checked at render time
A template knows its own variables and raises when one is missing.
The code declares two inputs, renders with one missing, and catches the failure.
from langchain_core.prompts import ChatPromptTemplate
prompt = ChatPromptTemplate.from_messages([
("human", "Account {account_id}: {question}"),
])
print("declared inputs:", sorted(prompt.input_variables))
try:
prompt.invoke({"question": "what is my balance?"})
except KeyError as exc:
print(f"missing input caught at template time: {exc}")
ok = prompt.invoke({"account_id": "ACC-1187", "question": "what is my balance?"})
print("filled:", ok.messages[0].content)
# The failure happens before the model call, which is the point. An f-string
# with a missing variable produces a prompt containing the word "None" and a
# confident answer about account None.
The failure happens before any API call - no tokens spent, no confident answer produced. That is the whole value.
Compare with the f-string equivalent. A missing variable there gives you a prompt containing the word None, a successful API call, and a well-formed answer about account None. Nothing raises, nothing logs, and the answer looks exactly like every other answer.
The mistake this prevents
The mistake is building the prompt by string concatenation because it reads more naturally. Every concatenated prompt is a place where a missing value becomes a plausible sentence, and plausible sentences are the failure mode this entire course is about.
Takeaway
Templates fail at render time on a missing input; f-strings produce a prompt about None and a confident answer. That is the difference worth the syntax.
