LangChain-PromptTemplate和ChatPromptTemplate
·
1. 本质区别:“纯文本提示” vs “结构化聊天提示”
(1)PromptTemplate(通用提示模板)
from langchain_core.prompts import PromptTemplate
# 生成的是纯文本提示(无角色区分)
prompt_template = PromptTemplate.from_template("Tell me a joke about {topic}")
result = prompt_template.invoke({"topic": "cats"})
print(result) # 输出:Tell me a joke about cats
- 核心特点:生成的是单一字符串文本,没有“角色”概念(比如不分“系统消息”“用户消息”),本质是“无结构的纯文本”。
- 返回类型:
StringPromptValue对象,其text属性就是最终的字符串(如Tell me a joke about cats)。 - 适用场景:适配“非聊天类模型”(如纯文本补全模型),或需要自定义简单文本提示的场景。
(2)ChatPromptTemplate(聊天提示模板)
from langchain_core.prompts import ChatPromptTemplate
# 生成的是结构化多角色消息
prompt_template = ChatPromptTemplate.from_messages([
("system", "You are a helpful assistant"),
("user", "Tell me a joke about {topic}")
])
result = prompt_template.invoke({"topic": "cats"})
print(result)
- 核心输出:
ChatPromptValue(messages=[ SystemMessage(content='You are a helpful assistant', ...), HumanMessage(content='Tell me a joke about cats', ...) ]) - 核心特点:生成的是多角色消息列表(区分
system(系统)、user(用户)等角色),本质是“结构化的聊天上下文”。 - 返回类型:
ChatPromptValue对象,其messages属性是包含角色信息的消息列表。 - 适用场景:适配“聊天类模型”(如 GPT-3.5/4、Claude 等),这些模型原生支持“角色区分”的对话格式,能更好地理解系统设定和用户输入的关系。
2. 关键差异对比
| 对比维度 | PromptTemplate | ChatPromptTemplate |
|---|---|---|
| 结构类型 | 纯文本(无角色,单一字符串) | 结构化消息列表(区分角色,如 system/user) |
| 模型适配性 | 更适合“文本补全模型”(无对话角色概念) | 专为“聊天模型”设计(如 ChatGPT 类模型) |
| 功能边界 | 只能生成简单文本,无法表达多轮对话历史 | 支持多轮对话(可插入历史消息)、系统角色设定 |
| 角色支持 | 不支持角色区分,所有内容都是“无角色文本” | 支持 system/user/assistant 等多角色 |
| 灵活性 | 低:仅能替换文本变量 | 高:可动态插入消息列表(如通过 MessagesPlaceholder) |
3. 对模型输出的影响
- 用
PromptTemplate生成的纯文本提示传给聊天模型时,模型会将所有内容视为“用户输入”,可能忽略潜在的“系统设定”意图。 - 用
ChatPromptTemplate生成的结构化消息传给聊天模型时,模型能明确区分“系统设定”(如You are a helpful assistant)和“用户请求”(如Tell me a joke about cats),从而更精准地遵循系统角色约束。
总结
简单说:
PromptTemplate是“无角色的纯文本模板”,适合简单文本生成场景;ChatPromptTemplate是“带角色的结构化聊天模板”,专为聊天模型设计,能更好地支持系统设定、多轮对话等复杂交互。
在实际开发中,对接聊天模型(如 OpenAI 的 gpt-3.5-turbo)时,优先使用 ChatPromptTemplate,因为它能充分利用模型对角色信息的原生支持,生成更符合预期的响应。
更多推荐



所有评论(0)