Why hardcoded strings kill your app. Treating prompts as software components.
In our first lesson, we used:
prompt = f"Tell me a joke about {topic}"
This is fine for scripts, but terrible for apps.
{topic} contains instructions to ignore the prompt?LangChain has two types of templates, mirroring the two types of models.
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.")
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.")
# ])
By using ChatPromptTemplate, you are working with Message Objects, not just strings.
This means:
{topic} logic before calling the API.def get_joke_chain(tone):
# Pre-fill the 'tone' variable, leave 'topic' for later
partial = template.partial(tone=tone)
return partial | model
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."