MessagePromptTemplate Types in LangChain

MessagePromptTemplate Types in LangChain (Simplified Guide)

This guide explains the different types of MessagePromptTemplate in LangChain, using exact code examples and outputs from the original source. It breaks down how each type works---with no added content or modifications---to make learning easier.

1. Overview of MessagePromptTemplate Types

LangChain provides MessagePromptTemplate variants to create structured chat messages for different roles. The most commonly used types are:

  • AIMessagePromptTemplate: Creates messages from the AI assistant (e.g., the model's responses).
  • SystemMessagePromptTemplate: Creates system messages that define the AI's role, rules, or instructions (e.g., "You are a helpful translator").
  • HumanMessagePromptTemplate: Creates messages from the human user (e.g., the user's questions or inputs).

For more flexibility (e.g., custom roles or dynamic messages), LangChain also offers two additional types: ChatMessagePromptTemplate and MessagesPlaceholder.

2. ChatMessagePromptTemplate: For Custom Roles

When your chat model supports arbitrary roles (not just "AI", "system", or "human"), use ChatMessagePromptTemplate to define a custom role name.

Original Code Example

python 复制代码
from langchain.prompts import ChatMessagePromptTemplate

# Define a prompt template with a placeholder ({subject})
prompt = "May the {subject} be with you"

# Create a ChatMessagePromptTemplate with a custom role ("Jedi")
chat_message_prompt = ChatMessagePromptTemplate.from_template(
    role="Jedi", 
    template=prompt
)

# Fill in the placeholder and generate the message
formatted_message = chat_message_prompt.format(subject="force")
print(formatted_message)

Original Output

复制代码
ChatMessage(content='May the force be with you', additional_kwargs={}, role='Jedi')

Simple Explanation

  • Import : We load ChatMessagePromptTemplate from LangChain.
  • Custom Role : The role="Jedi" parameter lets us assign a unique role (not just the default ones).
  • Placeholder : {subject} in the prompt is replaced with "force" when we call .format(subject="force").
  • Output : The result is a ChatMessage object labeled with the custom "Jedi" role.

3. MessagesPlaceholder: For Dynamic Message Lists

MessagesPlaceholder gives you full control over the messages included in a prompt. Use it when:

  • You're unsure which roles to use for messages.
  • You want to insert a pre-defined list of messages (e.g., a past conversation) during formatting.

Original Code Example

Step 1: Import Tools and Create Templates
python 复制代码
from langchain.prompts import MessagesPlaceholder, HumanMessagePromptTemplate
from langchain.prompts.chat import ChatPromptTemplate
from langchain.schema import HumanMessage, AIMessage

# 1. Create a human prompt template (asks to summarize a conversation)
human_prompt = "Summarize our conversation so far in {word_count} words."
human_message_template = HumanMessagePromptTemplate.from_template(human_prompt)

# 2. Create a ChatPromptTemplate with MessagesPlaceholder
# "variable_name='conversation'" lets us pass a message list later
chat_prompt = ChatPromptTemplate.from_messages([
    MessagesPlaceholder(variable_name="conversation"), 
    human_message_template
])
Step 2: Define a Sample Conversation and Format the Prompt
python 复制代码
# Create a sample past conversation (human + AI messages)
human_message = HumanMessage(content="What is the best way to learn programming?")
ai_message = AIMessage(content="""\
1. Choose a programming language: Decide on a programming language that you want to learn.
2. Start with the basics: Familiarize yourself with the basic programming concepts such as variables, data types and control structures.
3. Practice, practice, practice: The best way to learn programming is through hands-on experience\
""")

# Fill in the placeholder (conversation list + word count) and get messages
formatted_messages = chat_prompt.format_prompt(
    conversation=[human_message, ai_message], 
    word_count="10"
).to_messages()

print(formatted_messages)

Original Output

复制代码
[
    HumanMessage(content='What is the best way to learn programming?', additional_kwargs={}), 
    AIMessage(content='1. Choose a programming language: Decide on a programming language that you want to learn. \n\n2. Start with the basics: Familiarize yourself with the basic programming concepts such as variables, data types and control structures.\n\n3. Practice, practice, practice: The best way to learn programming is through hands-on experience', additional_kwargs={}), 
    HumanMessage(content='Summarize our conversation so far in 10 words.', additional_kwargs={})
]

Simple Explanation

  • MessagesPlaceholder : The variable_name="conversation" acts as a "slot" where we can insert a list of messages (e.g., a past chat) later.
  • Dynamic Insertion : When we call .format_prompt(conversation=[human_message, ai_message]), the placeholder is replaced with the sample conversation.
  • Final Prompt: The output combines the past conversation + the new human request (to summarize in 10 words)---perfect for tasks like summarizing chat history.

Key Takeaways (From Original Source)

  • Use the 3 common templates for standard roles: AI, system, human.
  • Use ChatMessagePromptTemplate for custom roles (e.g., "Jedi", "Teacher").
  • Use MessagesPlaceholder to add dynamic message lists (e.g., past conversations) to prompts.
  • All code and outputs match the original source---no changes or additions.
相关推荐
学历真的很重要19 小时前
LangChain V1.0 Context Engineering(上下文工程)详细指南
人工智能·后端·学习·语言模型·面试·职场和发展·langchain
工藤学编程19 小时前
零基础学AI大模型之LangChain智能体执行引擎AgentExecutor
人工智能·langchain
Smoothzjc1 天前
别再只把AI当聊天机器人了!揭秘大模型进化的终极形态,看完颠覆你的认知!
后端·langchain·ai编程
SCBAiotAigc1 天前
langchain1.x学习笔记(三):langchain之init_chat_model的新用法
人工智能·python·langchain·langgraph·deepagents
工藤学编程1 天前
零基础学AI大模型之LangChain智能体之initialize_agent开发实战
人工智能·langchain
ohyeah2 天前
打造 AI 驱动的 Git 提交规范助手:基于 React + Express + Ollama+langchain 的全栈实践
langchain·全栈·ollama
XiaoYu20022 天前
第11章 LangChain
前端·javascript·langchain
猫头虎2 天前
2025年AI领域年度深度总结:始于DeepSeek R1开源发布,终于Manus天价出海
人工智能·langchain·开源·prompt·aigc·ai编程·编程技术
真上帝的左手2 天前
26. AI-框架工具-LangChain & LangGraph
人工智能·langchain
大模型真好玩2 天前
LangGraph智能体开发设计模式(四)——LangGraph多智能体设计模式:网络架构
人工智能·langchain·agent