Course Content
LangChain Mastery
7 sections · 109 lessons
What is a PromptTemplate in LangChain, and how is it used?
What you need to know
Without templates, prompts get built with f-strings in many places. Then one change to wording means hunting through the code, and a missing variable silently sends a broken prompt.
1from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder23prompt = ChatPromptTemplate.from_messages([4 ("system", "You are a support agent for {company}. Answer in {language}. "5 "Use only the help articles below.\n\n{articles}"),6 MessagesPlaceholder("history", optional=True),7 ("human", "{question}"),8]).partial(company="PayEase")910value = prompt.invoke({"language": "English", "articles": "...",11 "question": "How do I reset my PIN?"})12print(value.to_messages())prompt.invoke returns a prompt value that holds a list of messages. In a chain you rarely call it yourself: prompt | llm passes that value straight to the model.
The main types
| Class | Output | Use it for |
|---|---|---|
ChatPromptTemplate | A list of messages | Every chat model (the default) |
PromptTemplate | One string | Legacy completion models, or building a string inside a step |
MessagesPlaceholder | Inserts a list of messages | Chat history, agent scratchpad |
FewShotChatMessagePromptTemplate | Example human/AI pairs | Few-shot prompting |
Useful features
- Validation. If a variable is missing,
invokeraises aKeyErrorthat names it, before any money is spent on a model call. partial. Pre-fill a variable with a value, or with a function that runs at format time, such as today's date.- Escaping. A literal brace in the prompt, like a JSON example, must be doubled:
{{"total": 0}}. - Versioning. Prompts can be stored in LangSmith and loaded with
Client().pull_prompt("name"), so they can change without a code deploy.
A real-life example
A support bot over a fintech company's help-centre docs had its prompt copied into three services. When legal asked for a new line ("Never promise a refund date"), one service was missed, and the bot kept promising "refund in 3 days" for another month. The team moved the prompt into one ChatPromptTemplate in a shared module, with {articles} and {question} as variables and company filled by partial. The next wording change was one pull request, reviewed once, and the unit test that renders the template with sample inputs caught a typo ({artciles}) before release.
Follow-up questions to expect
- "Why does my JSON example in the prompt cause a missing-variable error?" — Single braces are read as variables. Double them,
{{ }}, or usetemplate_format="mustache". - "How do you add chat history to a prompt?" — Put a
MessagesPlaceholder("history")between the system and human messages and pass a list of messages under that key. - "String template or chat template?" — Chat template, because every current model is a chat model and system messages are handled properly.