PromptTemplate vs ChatPromptTemplate
Why hardcoded strings kill your app. Treating prompts as software components.
PromptTemplates
1. Why Not Just f-strings?
In our first lesson, we used:
prompt = f"Tell me a joke about {topic}"
This is fine for scripts, but terrible for apps.
- Security injection: What if
{topic}contains instructions to ignore the prompt? - No Type Checking: You don't know what variables are missing until runtime.
- No Serialization: You can't save an f-string to a file and load it later.
2. Text Prompts vs Chat Prompts
LangChain has two types of templates, mirroring the two types of models.
A. PromptTemplate (String In, String Out)
Used for older "Instruction" models (like GPT-3 davinci) or raw text completion.
from langchain_core.prompts import PromptTemplate
template = PromptTemplate.from_template("Tell me a joke about {topic}.")
formatted = template.invoke({"topic": "bears"})
# Output: StringPromptValue(text="Tell me a joke about bears.")B. ChatPromptTemplate (Dict In, Message List Out)
Used for Chat Models (GPT-4, Claude). This is what you will use 99% of the time.
from langchain_core.prompts import ChatPromptTemplate
template = ChatPromptTemplate.from_messages([
("system", "You are a specialized AI."),
("human", "Tell me a joke about {topic}.")
])
formatted = template.invoke({"topic": "bears"})
# Output: ChatPromptValue(messages=[
# SystemMessage(content="You are a specialized AI."),
# HumanMessage(content="Tell me a joke about bears.")
# ])3. Why This Object Model Matters
By using ChatPromptTemplate, you are working with Message Objects, not just strings.
This means:
- Validation: It checks if you forgot to pass
{topic}logic before calling the API. - Modularity: You can reuse the "System Message" across 10 different chains.
- Partial Formatting: You can "pre-fill" variables.
def get_joke_chain(tone):
# Pre-fill the 'tone' variable, leave 'topic' for later
partial = template.partial(tone=tone)
return partial | model4. Summary
Stop concatenating strings.
Use ChatPromptTemplate to structure your inputs. It’s safer, cleaner, and strictly typed.
Key Intuition: "Prompts are software components, not just text."