LangChain 中支持许多的模板(Template)类型,这些模板用于格式化输入,生成 LLM 可处理的提示文本。
本文基于 LangChain 0.3.x,详细介绍 LangChain 中支持的模板类(主要在 langchain_core.prompts
模块),包括功能、参数和使用场景,并提供一个独立示例,展示如何使用 PromptTemplate
和 ChatPromptTemplate
构建一个简单的问答应用,使用 langchain_openai.ChatOpenAI
作为 LLM。
LangChain 中的模板类型
LangChain 的模板类主要位于 langchain_core.prompts
模块,用于创建结构化的提示,动态填充变量以供 LLM 处理。这些模板支持不同的提示格式(如纯文本、聊天消息),适用于各种任务(如问答、对话、RAG)。以下是 LangChain 支持的主要模板类型,基于官方文档(Prompts) 和源码分析。
1. PromptTemplate
- 描述:生成纯文本提示的模板,适合非聊天模型或简单任务。
- 模块:
langchain_core.prompts.PromptTemplate
- 功能:
- 使用字符串模板,包含占位符(如
{variable}
)。 - 支持
f-string
或jinja2
格式化。 - 动态填充变量,生成最终提示。
- 使用字符串模板,包含占位符(如
- 主要参数:
template
(必填):字符串模板,如"问题:{question}\n回答:"
。input_variables
(可选):模板中使用的变量列表。template_format
(默认"f-string"
):格式化方式("f-string"
,"jinja2"
)。partial_variables
(可选):预定义的部分变量。
- 方法:
format(**kwargs) -> str
:生成格式化后的字符串。format_prompt(**kwargs) -> PromptValue
:返回PromptValue
对象(内部用)。partial(**kwargs) -> PromptTemplate
:填充部分变量,返回新模板。
- 使用场景:
- 简单问答或文本生成。
- 与非聊天 LLM(如
LlamaCpp
)结合。 - 格式化 RAG 系统的上下文。
- 示例:
from langchain_core.prompts import PromptTemplate template = PromptTemplate( template="问题:{question}\n回答:", input_variables=["question"] ) prompt = template.format(question="什么是人工智能?") # 输出: "问题:什么是人工智能?\n回答:"
2. ChatPromptTemplate
- 描述:生成聊天消息列表的模板,适合聊天模型(如
ChatOpenAI
)。 - 模块:
langchain_core.prompts.ChatPromptTemplate
- 功能:
- 创建结构化消息(如
SystemMessage
,HumanMessage
,AIMessage
)。 - 支持
MessagesPlaceholder
动态注入对话历史。 - 适配聊天模型的输入格式。
- 创建结构化消息(如
- 主要参数:
messages
(必填):消息模板列表,包含SystemMessagePromptTemplate
、HumanMessagePromptTemplate
等。input_variables
(可选):模板中使用的变量。
- 方法:
format_messages(**kwargs) -> List[BaseMessage]
:生成消息列表。format_prompt(**kwargs) -> ChatPromptValue
:返回ChatPromptValue
对象。from_messages(cls, messages) -> ChatPromptTemplate
:类方法,从消息列表创建模板。
- 使用场景:
- 对话系统或 RAG(结合对话历史)。
- 与聊天模型(如
ChatOpenAI
,ChatAnthropic
)结合。 - 需要系统指令或多轮对话。
- 示例:
from langchain_core.prompts import ChatPromptTemplate template = ChatPromptTemplate.from_messages([ ("system", "你是一个专家,回答问题。"), ("human", "问题:{question}") ]) messages = template.format_messages(question="什么是人工智能?") # 输出: [SystemMessage(content="你是一个专家..."), HumanMessage(content="问题:什么是人工智能?")]
3. SystemMessagePromptTemplate
- 描述:生成系统消息的模板,通常用于设置 LLM 的角色或行为。
- 模块:
langchain_core.prompts.chat.SystemMessagePromptTemplate
- 功能:
- 创建
SystemMessage
,定义对话的上下文或指令。 - 常用于
ChatPromptTemplate
内。
- 创建
- 主要参数:
prompt
:PromptTemplate
实例,定义系统消息内容。input_variables
:变量列表。
- 使用场景:
- 定义 LLM 的角色(如 “你是一个历史学家”)。
- 设置对话的全局指令。
- 示例:
from langchain_core.prompts import SystemMessagePromptTemplate, PromptTemplate system_template = SystemMessagePromptTemplate.from_template( "你是{role}专家。", input_variables=["role"] ) message = system_template.format(role="人工智能") # 输出: SystemMessage(content="你是人工智能专家。")
4. HumanMessagePromptTemplate
- 描述:生成用户消息的模板,表示用户输入。
- 模块:
langchain_core.prompts.chat.HumanMessagePromptTemplate
- 功能:
- 创建
HumanMessage
,表示用户的问题或输入。 - 常用于
ChatPromptTemplate
内。
- 创建
- 主要参数:
prompt
:PromptTemplate
实例,定义用户消息内容。input_variables
:变量列表。
- 使用场景:
- 格式化用户问题或指令。
- 构建多轮对话。
- 示例:
from langchain_core.prompts import HumanMessagePromptTemplate, PromptTemplate human_template = HumanMessagePromptTemplate.from_template( "问题:{question}", input_variables=["question"] ) message = human_template.format(question="什么是人工智能?") # 输出: HumanMessage(content="问题:什么是人工智能?")
5. AIMessagePromptTemplate
- 描述:生成 AI 消息的模板,表示 LLM 的响应(较少直接使用)。
- 模块:
langchain_core.prompts.chat.AIMessagePromptTemplate
- 功能:
- 创建
AIMessage
,模拟 LLM 的输出。 - 通常用于测试或构造对话历史。
- 创建
- 主要参数:
prompt
:PromptTemplate
实例,定义 AI 消息内容。input_variables
:变量列表。
- 使用场景:
- 模拟对话历史。
- 测试链的行为。
- 示例:
from langchain_core.prompts import AIMessagePromptTemplate, PromptTemplate ai_template = AIMessagePromptTemplate.from_template( "回答:{answer}", input_variables=["answer"] ) message = ai_template.format(answer="人工智能是...") # 输出: AIMessage(content="回答:人工智能是...")
6. MessagesPlaceholder
- 描述:占位符,用于动态注入对话历史或消息列表。
- 模块:
langchain_core.prompts.chat.MessagesPlaceholder
- 功能:
- 在
ChatPromptTemplate
中预留位置,填充BaseMessage
列表(如对话历史)。 - 常与
RunnableWithMessageHistory
结合。
- 在
- 主要参数:
variable_name
(必填):占位符名称。optional
(默认False
):是否允许空消息列表。
- 使用场景:
- 管理对话历史(如
ChatMessageHistory
)。 - 构建支持多轮对话的链。
- 管理对话历史(如
- 示例:
from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder template = ChatPromptTemplate.from_messages([ MessagesPlaceholder(variable_name="chat_history"), ("human", "{question}") ])
7. FewShotPromptTemplate
- 描述:支持少样本学习(Few-Shot Learning)的模板,提供示例提示。
- 模块:
langchain_core.prompts.FewShotPromptTemplate
- 功能:
- 包含示例(
examples
)和前缀/后缀模板,生成带示例的提示。 - 支持动态选择示例(通过
example_selector
)。
- 包含示例(
- 主要参数:
examples
:示例列表,每个示例是字典。example_prompt
:PromptTemplate
,定义示例格式。prefix
/suffix
:提示的前缀/后缀。input_variables
:变量列表。example_selector
(可选):动态选择示例的工具。
- 使用场景:
- 少样本学习,教 LLM 特定任务。
- 格式化复杂任务(如分类、翻译)。
- 示例:
from langchain_core.prompts import FewShotPromptTemplate, PromptTemplate examples = [ {"question": "什么是太阳?", "answer": "太阳是恒星。"}, {"question": "什么是月亮?", "answer": "月亮是卫星。"} ] example_prompt = PromptTemplate( template="问题:{question}\n回答:{answer}\n", input_variables=["question", "answer"] ) template = FewShotPromptTemplate( examples=examples, example_prompt=example_prompt, prefix="你是一个天文学家,回答问题:", suffix="问题:{question}\n回答:", input_variables=["question"] ) prompt = template.format(question="什么是星星?") # 输出: 你是一个天文学家,回答问题: # 问题:什么是太阳? # 回答:太阳是恒星。 # 问题:什么是月亮? # 回答:月亮是卫星。 # 问题:什么是星星? # 回答:
8. FewShotChatPromptTemplate
- 描述:支持少样本学习的聊天模板,生成消息列表。
- 模块:
langchain_core.prompts.FewShotChatPromptTemplate
- 功能:
- 类似
FewShotPromptTemplate
,但生成SystemMessage
/HumanMessage
等。 - 适合聊天模型的少样本任务。
- 类似
- 主要参数:
examples
:示例列表。example_prompt
:ChatPromptTemplate
,定义示例格式。input_variables
:变量列表。
- 使用场景:
- 聊天模型的少样本学习。
- 复杂对话任务。
- 示例:
from langchain_core.prompts import FewShotChatPromptTemplate, ChatPromptTemplate examples = [ {"input": "什么是太阳?", "output": "太阳是恒星。"} ] example_prompt = ChatPromptTemplate.from_messages([ ("human", "{input}"), ("ai", "{output}") ]) template = FewShotChatPromptTemplate( examples=examples, example_prompt=example_prompt, input_variables=["question"] )
9. PipelinePromptTemplate
- 描述:组合多个模板,生成复杂的提示。
- 模块:
langchain_core.prompts.PipelinePromptTemplate
- 功能:
- 将子模板(如
PromptTemplate
)组合成最终提示。 - 支持嵌套和依赖关系。
- 将子模板(如
- 主要参数:
final_prompt
:最终的PromptTemplate
。pipeline_prompts
:子模板列表,每个元素是(name, PromptTemplate)
。
- 使用场景:
- 复杂任务,需多个提示阶段。
- 动态组合上下文和指令。
- 示例:
from langchain_core.prompts import PipelinePromptTemplate, PromptTemplate final_template = PromptTemplate.from_template("{intro}\n{question}") intro_template = PromptTemplate.from_template("你是一个专家。") pipeline = PipelinePromptTemplate( final_prompt=final_template, pipeline_prompts=[("intro", intro_template), ("question", PromptTemplate.from_template("问题:{q}"))] ) prompt = pipeline.format(q="什么是人工智能?") # 输出: 你是一个专家。 # 问题:什么是人工智能?
模板类型总结
模板类 | 模块 | 输出类型 | 主要场景 |
---|---|---|---|
PromptTemplate | langchain_core.prompts | 纯文本 | 简单问答、RAG、非聊天模型 |
ChatPromptTemplate | langchain_core.prompts | 消息列表 | 对话、聊天模型、RAG |
SystemMessagePromptTemplate | langchain_core.prompts.chat | SystemMessage | 设置角色、指令 |
HumanMessagePromptTemplate | langchain_core.prompts.chat | HumanMessage | 用户输入 |
AIMessagePromptTemplate | langchain_core.prompts.chat | AIMessage | 模拟 AI 响应 |
MessagesPlaceholder | langchain_core.prompts.chat | 消息占位符 | 对话历史 |
FewShotPromptTemplate | langchain_core.prompts | 纯文本 | 少样本学习 |
FewShotChatPromptTemplate | langchain_core.prompts | 消息列表 | 聊天模型少样本学习 |
PipelinePromptTemplate | langchain_core.prompts | 纯文本 | 复杂提示组合 |
推荐模板:
- 简单任务:
PromptTemplate
(纯文本,易用)。 - 对话系统:
ChatPromptTemplate
(支持聊天模型和历史)。 - 复杂任务:
FewShotPromptTemplate
或PipelinePromptTemplate
。
使用模板的问答示例
以下是一个独立示例,展示如何使用 PromptTemplate
和 ChatPromptTemplate
,结合 langchain_openai.ChatOpenAI
构建一个简单的问答应用,回答关于机器学习的问题。
代码:
import os
os.environ["OPENAI_API_KEY"] = "Your OpenAI API Key"
from langchain_openai import ChatOpenAI
from langchain_core.prompts import PromptTemplate, ChatPromptTemplate
from langchain_core.output_parsers import StrOutputParser
from langchain_core.runnables import RunnablePassthrough
# 初始化 ChatOpenAI LLM
llm = ChatOpenAI(temperature=0, model="gpt-4")
# 定义 PromptTemplate(纯文本)
text_prompt = PromptTemplate(
template="""你是一个机器学习专家,回答以下问题:
问题:{question}
回答:""",
input_variables=["question"]
)
# 定义 ChatPromptTemplate(消息列表)
chat_prompt = ChatPromptTemplate.from_messages([
("system", "你是一个机器学习专家,简洁回答问题。"),
("human", "{question}")
])
# 创建问答链(使用 ChatPromptTemplate)
qa_chain = (
{"question": RunnablePassthrough()}
| chat_prompt
| llm
| StrOutputParser()
)
# 调用链
print("问答链输出:")
response = qa_chain.invoke("什么是机器学习?")
print(response)
response = qa_chain.invoke("它的主要类型有哪些?")
print(response)
输出示例:
问答链输出:
机器学习是人工智能的分支,通过数据训练模型以进行预测或决策。
机器学习的主要类型包括监督学习、无监督学习和强化学习。
代码说明
- 模板使用:
PromptTemplate
:定义纯文本提示(未直接使用,仅展示)。ChatPromptTemplate
:生成消息列表,包含系统指令和用户问题,适合ChatOpenAI
。
- LLM:
ChatOpenAI
(gpt-4
)生成高质量答案。
- 问答链:
- LCEL 链组合
chat_prompt
、llm
和StrOutputParser
。 RunnablePassthrough
传递输入问题。
- LCEL 链组合
- 主题:
- 示例聚焦机器学习问答,简单且独立。
- 独立性:
- 不涉及向量存储、RAG 或之前的 Milvus、LlamaCpp 内容。
运行要求:
- OpenAI API 密钥有效。
- 安装依赖:
pip install --upgrade langchain langchain-core langchain-openai
注意事项
- API 密钥:
- 使用
.env
文件:from dotenv import load_dotenv load_dotenv()
- 确保密钥支持
gpt-4
。
- 使用
- 依赖:
- 安装:
pip install --upgrade langchain langchain-core langchain-openai
- 安装:
- 模板选择:
- 聊天模型:优先使用
ChatPromptTemplate
,支持消息格式。 - 非聊天模型:使用
PromptTemplate
,如结合LlamaCpp
。 - 对话历史:添加
MessagesPlaceholder
。
- 聊天模型:优先使用
- 性能优化:
- 模板:
- 确保
input_variables
与占位符一致。 - 使用简洁模板,减少 LLM 处理负担。
- 确保
- LLM:
- 调整
temperature
(如 0.5)控制随机性。 - 设置
max_tokens
(如 512)限制输出长度。
- 调整
- 模板:
- 错误调试:
- 变量缺失:
- 检查
format
或format_messages
的输入:prompt.format(question="测试") # 确保所有变量提供
- 检查
- 输出格式:
- 使用
StrOutputParser
确保纯文本输出。 - 若需 JSON,改用
JsonOutputParser
:from langchain_core.output_parsers import JsonOutputParser
- 使用
- 变量缺失:
常见问题
Q1:如何选择合适的模板?
A:
- 简单问答:
PromptTemplate
(纯文本,易用)。 - 对话系统:
ChatPromptTemplate
(支持消息和历史)。 - 少样本学习:
FewShotPromptTemplate
或FewShotChatPromptTemplate
。 - 复杂提示:
PipelinePromptTemplate
。
Q2:如何添加对话历史?
A:使用 ChatPromptTemplate
结合 MessagesPlaceholder
和 RunnableWithMessageHistory
:
from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder
from langchain_core.runnables.history import RunnableWithMessageHistory
from langchain_community.chat_message_histories import ChatMessageHistory
prompt = ChatPromptTemplate.from_messages([
MessagesPlaceholder(variable_name="chat_history"),
("human", "{question}")
])
chain = prompt | llm | StrOutputParser()
chain_with_history = RunnableWithMessageHistory(
chain,
lambda session_id: ChatMessageHistory(),
input_messages_key="question",
history_messages_key="chat_history"
)
Q3:可以结合 RAG 吗?
A:可以,使用 PromptTemplate
或 ChatPromptTemplate
包含上下文:
prompt = ChatPromptTemplate.from_messages([
("system", "根据上下文回答:{context}"),
("human", "{question}")
])
Q4:支持其他模板格式吗?
A:支持 jinja2
(需安装 jinja2
):
prompt = PromptTemplate(
template="Question: {{ question }}\nAnswer:",
input_variables=["question"],
template_format="jinja2"
)
总结
LangChain 的模板类(在 langchain_core.prompts
)包括:
PromptTemplate
:纯文本提示,适合简单任务。ChatPromptTemplate
:消息列表,适合聊天模型。SystemMessagePromptTemplate
/HumanMessagePromptTemplate
/AIMessagePromptTemplate
:消息类型,构建对话。MessagesPlaceholder
:动态历史注入。FewShotPromptTemplate
/FewShotChatPromptTemplate
:少样本学习。PipelinePromptTemplate
:复杂提示组合。