LangChain Mastery

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.

Python
from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholderprompt = ChatPromptTemplate.from_messages([    ("system", "You are a support agent for {company}. Answer in {language}. "               "Use only the help articles below.\n\n{articles}"),    MessagesPlaceholder("history", optional=True),    ("human", "{question}"),]).partial(company="PayEase")value = prompt.invoke({"language": "English", "articles": "...",                       "question": "How do I reset my PIN?"})print(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

ClassOutputUse it for
ChatPromptTemplateA list of messagesEvery chat model (the default)
PromptTemplateOne stringLegacy completion models, or building a string inside a step
MessagesPlaceholderInserts a list of messagesChat history, agent scratchpad
FewShotChatMessagePromptTemplateExample human/AI pairsFew-shot prompting

Useful features

  • Validation. If a variable is missing, invoke raises a KeyError that 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 use template_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.