langchain_core.prompts.ChatPromptTemplate
是 LangChain 框架中专为聊天模型设计的提示模板类,用于创建结构化、动态的消息序列。它支持定义系统消息、用户消息和助手消息,并允许在消息中插入变量,广泛应用于对话系统、问答链和代理应用。本文将从定义、核心功能、创建方法、应用场景、示例代码和注意事项等方面,系统讲解 ChatPromptTemplate
的功能与使用方法。
ChatPromptTemplate
?ChatPromptTemplate
是 LangChain 中 BaseChatPromptTemplate
的子类,专门为聊天模型(如 OpenAI 的 GPT 系列、Anthropic 的 Claude 等)设计。聊天模型通常期望接收一系列消息(而非单一字符串),每条消息具有特定角色(如“system”、“human”、“ai”)。ChatPromptTemplate
允许开发者定义包含多个消息的模板,并在消息内容中插入变量占位符,从而生成动态提示。
核心功能:
Runnable
接口,与 LangChain 的链、模型和代理无缝集成。设计目标:
ChatPromptTemplate
?在 LLM 应用中,聊天模型需要明确的指令和上下文来生成相关输出。ChatPromptTemplate
通过模板化消息序列,解决了以下问题:
MessagesPlaceholder
等机制,轻松管理对话历史或工具调用。从官方文档来看,ChatPromptTemplate
是 LangChain 提示模块的核心组件,广泛用于对话系统、问答链和工具集成场景。
ChatPromptTemplate
作为一个提示模板类,没有直接的“属性”暴露给用户,而是通过其构造函数和方法定义消息结构和行为。以下是其核心功能和相关属性的说明:
ChatPromptTemplate
的核心是消息序列,每个消息由角色和内容组成:
system
:系统消息,定义模型的行为或角色(如“你是一个 helpful assistant”)。human
:用户消息,表示用户输入。ai
:助手消息,表示模型的回复。{user_input}
)。ChatPromptTemplate
提供多种方法,支持提示的创建、格式化和处理:
format_messages(**kwargs)
:将变量替换为实际值,返回 BaseMessage
对象列表。invoke(input)
:根据输入变量生成 PromptValue
对象,可直接传递给聊天模型。partial(**kwargs)
:创建部分填充变量的模板,适合设置默认值。append(message)
:向模板追加单个消息。extend(messages)
:批量添加多个消息。save(file_path)
:将模板序列化为文件,便于复用。Runnable
接口的实现,支持 stream
(流式输出)、batch
(批量处理)和 astream_events
(事件流)。{user_input}
、{name}
)自动构成输入模式。partial
方法设置的默认变量。ChatPromptTemplate
的方法ChatPromptTemplate
提供了多种创建方式,灵活适应不同场景。以下是主要方法:
直接传递消息元组列表,每个元组包含角色和消息内容:
from langchain_core.prompts import ChatPromptTemplate
template = ChatPromptTemplate([
("system", "你是一个名叫 {name} 的 helpful assistant。"),
("human", "{user_input}")
])
from_messages
方法通过 from_messages
方法从消息列表创建模板,支持元组或消息对象:
template = ChatPromptTemplate.from_messages([
("system", "你是一个 helpful assistant。"),
("human", "你好!"),
("ai", "你好!我能帮你什么?"),
("human", "{user_input}")
])
from_messages
是最常用的创建方式,适合定义复杂的消息序列。
from_template
方法从单个字符串模板创建,自动视为人类消息:
template = ChatPromptTemplate.from_template("告诉我关于 {topic} 的信息。")
这会生成一个仅包含人类消息的模板,变量为 {topic}
。
MessagesPlaceholder
使用 MessagesPlaceholder
动态插入对话历史或外部消息:
from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder
template = ChatPromptTemplate.from_messages([
("system", "你是一个 helpful assistant。"),
MessagesPlaceholder("history"),
("human", "{input}")
])
ChatPromptTemplate
在 LangChain 的多个模块中广泛应用,以下是典型场景和实际用途:
from langchain_core.prompts import ChatPromptTemplate
from langchain_openai import ChatOpenAI
template = ChatPromptTemplate.from_messages([
("system", "你是一个知识渊博的助手,回答要简洁准确。"),
("human", "{question}")
])
model = ChatOpenAI(model="gpt-4o")
chain = template | model
response = chain.invoke({"question": "法国的首都是什么?"})
print(response.content)
输出:法国的首都是巴黎。MessagesPlaceholder
插入历史消息。from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder
from langchain_core.messages import HumanMessage, AIMessage
template = ChatPromptTemplate.from_messages([
("system", "你是一个 helpful assistant。"),
MessagesPlaceholder("history"),
("human", "{input}")
])
history = [
HumanMessage(content="你好,我叫小明。"),
AIMessage(content="你好,小明!很高兴认识你。")
]
prompt_value = template.invoke({
"history": history,
"input": "告诉我关于巴黎的信息。"
})
print(prompt_value.messages)
输出:[
SystemMessage(content='你是一个 helpful assistant。'),
HumanMessage(content='你好,我叫小明。'),
AIMessage(content='你好,小明!很高兴认识你。'),
HumanMessage(content='告诉我关于巴黎的信息。')
]
template = ChatPromptTemplate.from_messages([
("system", "根据以下文档回答问题:\n{context}"),
("human", "{question}")
])
context = "巴黎是法国的首都,位于塞纳河畔。"
prompt_value = template.invoke({
"context": context,
"question": "巴黎在哪里?"
})
template = ChatPromptTemplate.from_messages([
("system", "你是一个智能助手,可以使用工具:{tools}"),
("human", "{input}")
])
以下是一个结合对话历史和 RAG 的完整示例,展示 ChatPromptTemplate
的实际应用:
from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder
from langchain_core.messages import HumanMessage, AIMessage
from langchain_openai import ChatOpenAI
# 1. 创建提示模板
template = ChatPromptTemplate.from_messages([
("system", "你是一个 helpful assistant,基于以下上下文回答:\n{context}"),
MessagesPlaceholder("history"),
("human", "{input}")
])
# 2. 准备对话历史和上下文
context = "巴黎是法国的首都,人口约220万。"
history = [
HumanMessage(content="巴黎是哪个国家的首都?"),
AIMessage(content="巴黎是法国的首都。")
]
# 3. 生成提示
prompt_value = template.invoke({
"context": context,
"history": history,
"input": "巴黎有多少人口?"
})
# 4. 调用模型
model = ChatOpenAI(model="gpt-4o")
response = model.invoke(prompt_value)
print(response.content)
输出示例:
巴黎的人口大约为220万。
角色选择:
变量管理:
partial
方法预填充变量时,检查变量名是否与后续输入冲突。invoke
时都有值,否则会抛出异常。对话历史管理:
MessagesPlaceholder
时,传入的对话历史需为 BaseMessage
对象(如 HumanMessage
、AIMessage
)。性能优化:
batch
或 stream
方法,减少延迟。安全性:
版本兼容性:
langchain_core.prompts
,避免使用已弃用的模块。langchain_core.prompts.ChatPromptTemplate
是 LangChain 框架中用于聊天模型的核心提示工具,通过定义结构化的消息序列和动态变量,支持对话上下文管理、问答系统和代理应用。它提供了灵活的创建方法(如 from_messages
)、强大的功能(如 partial
和 invoke
)以及与 LangChain 生态系统的无缝集成。掌握 ChatPromptTemplate
的使用方法,可以帮助开发者高效构建复杂的 LLM 应用。
参考资源: