这三种提示模板是 LangChain 中不同的提示工程工具,各有其特点和适用场景:

1. PromptTemplate

最基础的提示模板类

from langchain_core.prompts import PromptTemplate
​
# 基础文本模板
template = """请回答以下问题:
问题:{question}
上下文:{context}"""
​
prompt = PromptTemplate(
    input_variables=["question", "context"],
    template=template
)
​
# 生成格式化后的字符串
formatted_prompt = prompt.format(question="什么是AI?", context="机器学习领域")

特点:

  • 生成纯文本字符串

  • 适用于传统的 LLM(如 text-davinci-003)

  • 不能直接用于聊天模型

2. ChatPromptTemplate

现代化的聊天模板类(推荐使用)

from langchain_core.prompts import ChatPromptTemplate, HumanMessagePromptTemplate, SystemMessagePromptTemplate
​
# 方法1:使用类
chat_prompt = ChatPromptTemplate.from_messages([
    SystemMessagePromptTemplate.from_template("你是一个有用的AI助手。"),
    HumanMessagePromptTemplate.from_template("问题:{question}"),
    HumanMessagePromptTemplate.from_template("上下文:{context}")
])
​
# 方法2:更简洁的语法
chat_prompt = ChatPromptTemplate.from_messages([
    ("system", "你是一个有用的AI助手。"),
    ("human", "问题:{question}"),
    ("human", "上下文:{context}")
])
​
# 生成聊天消息列表
messages = chat_prompt.format_messages(question="AI是什么?", context="机器学习")

特点:

  • 生成 BaseMessage 对象列表

  • 专门用于聊天模型(如 GPT-3.5/4)

  • 支持 system, human, ai 等不同角色消息

  • 更现代,推荐使用

3. HumanMessagePromptTemplate

专门用于创建人类消息的模板

from langchain_core.prompts import HumanMessagePromptTemplate
​
# 创建人类消息模板
human_template = HumanMessagePromptTemplate.from_template(
    "用户问题:{question}\n相关文档:{documents}"
)
​
# 生成人类消息
message = human_template.format_messages(
    question="如何学习Python?", 
    documents="一些文档内容"
)

特点:

  • 只生成人类消息(HumanMessage)

  • 通常与其他消息模板配合使用

  • 是 ChatPromptTemplate 的组成部分

主要区别对比

特性 PromptTemplate ChatPromptTemplate HumanMessagePromptTemplate
输出类型 字符串 BaseMessage 列表 HumanMessage 对象
适用模型 传统LLM 聊天模型 聊天模型
消息角色 无角色概念 支持多角色 仅人类角色
现代化 旧版 新版,推荐 旧版,逐步替代
使用场景 简单补全任务 对话、聊天应用 特定人类消息

实际应用示例

from langchain_core.prompts import (
    PromptTemplate, 
    ChatPromptTemplate, 
    HumanMessagePromptTemplate,
    SystemMessagePromptTemplate
)
from langchain_openai import ChatOpenAI
​
# 1. 传统方式(已不推荐)
traditional_prompt = PromptTemplate(
    input_variables=["question"],
    template="请回答:{question}"
)
​
# 2. 现代方式(推荐)
modern_chat_prompt = ChatPromptTemplate.from_messages([
    SystemMessagePromptTemplate.from_template("你是一个专业的AI助手。"),
    HumanMessagePromptTemplate.from_template("问题:{question}"),
])
​
# 使用聊天模型
llm = ChatOpenAI(model="gpt-3.5-turbo")
chain = modern_chat_prompt | llm
​
# 调用
response = chain.invoke({"question": "什么是机器学习?"})

总结

  • PromptTemplate: 基础文本模板,适用于传统模型

  • ChatPromptTemplate: 现代化聊天模板,支持多角色,推荐使用

  • HumanMessagePromptTemplate: 专门创建人类消息,通常作为 ChatPromptTemplate 的组件

建议: 在新项目中优先使用 ChatPromptTemplate,它更灵活、功能更强大,且符合当前的开发趋势。

Logo

有“AI”的1024 = 2048,欢迎大家加入2048 AI社区

更多推荐