一、为什么推荐提示词模板?

在 LangChain 开发中,构造提示词既可以直接用 Python 字符串拼接(f-string、format()、+),也可以使用 LangChain 提供的 PromptTemplate 或 ChatPromptTemplate。

方式 1:字符串拼接

topic = "Python"
difficulty = "初学者"
​
prompt_str = f"你是一个{difficulty}级别的编程导师。请用简单易懂的语言解释{topic}。"
response = model.invoke(prompt_str)
  • ✅ 优点:简单直接、上手快、适合临时 demo、无额外学习成本;

  • ❌ 缺点:可读性差(变量多时混乱)、不易维护、无变量校验、难以支持复杂场景(多轮对话 / RAG / Few-shot)。

方式 2:提示词模板

from langchain.prompts import PromptTemplate
​
template = PromptTemplate.from_template(
    "你是一个{difficulty}级别的编程导师。请用简单易懂的语言解释{topic}。"
)
prompt = template.format(difficulty=difficulty, topic=topic)
response = model.invoke(prompt)
  • ✅ 优点:结构清晰(变量占位)、易维护可复用、自动变量校验、支持复杂场景、可与 LangChain 生态无缝集成、便于调试与日志追踪;

  • ❌ 缺点:有一定学习成本、初期写法略复杂、对极简单场景略"重"。

开发建议

场景

推荐方式

小项目 / 临时用

字符串拼接

正式开发 / AI 应用

提示词模板(必选)

二、提示词机制演进

LangChain 1.0 架构变革的核心演进之一是 Prompt 机制:结构化的、富含元数据的消息列表已取代单一字符串,成为与模型交互的标准数据格式。

旧时代:LLM + PromptTemplate(输入输出均为字符串)

  • 模型接口:对应 LangChain 中的 LLM 类,面向早期的文本补全模型;

  • 工作方式:模型接受单一字符串输入,据此生成后续文本;

  • Prompt 工具:核心是 PromptTemplate,接收变量渲染后输出完整字符串;

from langchain.prompts import PromptTemplate
​
prompt_template = PromptTemplate.from_template(
    "请给我一个关于{topic}的{type}解释。"
)
prompt = prompt_template.format(type="详细", topic="量子力学")
  • 局限性:模拟多轮聊天时需手动拼接伪造对话角色("Human:你好\nAI:..."),结构混乱、难以维护、易让模型混淆对话边界。

新时代:ChatModel + ChatPromptTemplate(输入输出均为消息列表)

  • 模型接口:对应 LangChain 1.0 的主流接口 ChatModel;

  • 工作方式:现代聊天模型 API 原生支持角色概念,要求输入结构化的消息列表;

  • Prompt 工具:ChatPromptTemplate 成为最核心的 Prompt 工具,接收变量并输出 List[BaseMessage]。

二者对比

特性

PromptTemplate

ChatPromptTemplate

输出格式

纯文本字符串

消息列表

角色支持

❌

✅ system/user/assistant

对话历史

❌ 不支持

✅ 支持

适用场景

简单提示

聊天、对话、多轮交互

ChatPromptTemplate 已取代 PromptTemplate,成为构建现代 LangChain 应用的首选工具。

三、ChatPromptTemplate 的使用

ChatPromptTemplate 是创建聊天消息列表的提示模板,适合处理多角色、多轮次的对话场景,支持 System / Human / AI 等不同角色的消息模板。

消息角色字符串:

角色字符串

含义

用途

"system"

系统消息

设定 AI 的行为、角色、规则

"user" / "human"

用户消息

用户的输入/问题

"assistant" / "ai"

AI 消息

AI 的回复(用于对话历史)

两种实例化方式

方式 1(推荐):调用 from_messages()

from langchain_core.prompts import ChatPromptTemplate
​
chat_template = ChatPromptTemplate.from_messages([
    ("system", "你是一个有帮助的AI机器人,你的名字是{name}。"),
    ("human", "你好,最近怎么样?"),
    ("ai", "我很好,谢谢!"),
    ("human", "{user_input}"),
])
​
prompt = chat_template.invoke({"name": "小明", "user_input": "你叫什么名字?"})

方式 2:使用实例初始化方法

prompt_template = ChatPromptTemplate([
    ("system", "你是一个AI开发工程师. 你的名字是 {name}."),
    ("human", "你能开发哪些AI应用?"),
    ("ai", "我能开发很多AI应用..."),
    ("human", "{user_input}")
])

说明:from_messages() 的底层也是调用类的 __init__() 方法。

模板调用的 3 种方式

方法

返回值

场景

invoke()

ChatPromptValue

推荐,可直接传给模型

format()

字符串

拼接/打印调试

format_messages()

消息列表

需要消息列表

# 1. invoke() → ChatPromptValue
prompt = prompt_template.invoke({"name": "小谷AI", "user_input": "你能帮我做什么?"})
​
# 2. format() → str
prompt = prompt_template.format(name="小谷AI", user_input="你能帮我做什么?")
​
# 3. format_messages() → list
prompt = prompt_template.format_messages(name="小谷AI", user_input="你能帮我做什么?")

结合 LLM 调用

# 1. 提供大模型
model = init_chat_model(model="gpt-5.4-mini", model_provider="openai", ...)
​
# 2. 提供提示词
chat_prompt = ChatPromptTemplate.from_messages([
    ("system", "你是一个数学家,你可以计算任何算式"),
    ("human", "{text}"),
])
​
# 3. 结合提示词调用大模型
prompt_value = chat_prompt.invoke({"text": "我今年18岁,我的舅舅今年38岁,一共多少岁?"})
output = model.invoke(prompt_value)
print(output.content)

四、更丰富的初始化参数类型

ChatPromptTemplate 的 messages 参数是列表类型,列表元素支持多种类型:

类型

说明

示例

str 列表

默认角色为 human(不推荐)

["Hello, {name}!"]

tuple 列表

角色 + 内容(最常用)

[("system", "..."), ("human", "...")]

dict 列表

键值对形式

[{"role": "system", "content": "..."}]

Message 列表

已实例化的消息对象

[SystemMessage(...), HumanMessage(...)]

MessagePromptTemplate 列表

消息模板类

SystemMessagePromptTemplate 等

BaseChatPromptTemplate 列表

嵌套的 ChatPromptTemplate

模板嵌套模板

常用消息模板类

from langchain_core.prompts import (
    ChatPromptTemplate,
    HumanMessagePromptTemplate,
    SystemMessagePromptTemplate,
)
​
system_message_prompt = SystemMessagePromptTemplate.from_template("你是一个{role}")
human_message_prompt = HumanMessagePromptTemplate.from_template("给我解释{concept},用浅显易懂的语言")
​
chat_prompt = ChatPromptTemplate.from_messages([
    system_message_prompt,
    human_message_prompt
])
​
formatted_messages = chat_prompt.invoke({"role": "物理学家", "concept": "相对论"})

注意:在 XxxMessage 中不能有占位符(如 HumanMessage(content="我的问题是:{word}") 中的 {word} 不会被替换),需要变量填充时要用对应的 MessagePromptTemplate。

五、高级特性

1. 部分变量预填充:partial()

预填充固定不变的变量,创建模板的变体,适合"某些变量在所有调用中都相同"或"为不同用户/场景创建定制模板"的场景。

template = ChatPromptTemplate.from_messages([
    ("system", "你是{role},目标用户是{audience}"),
    ("user", "{task}")
])
​
# 部分填充
customer_support_template = template.partial(role="客服专员", audience="普通用户")
​
# 现在只需提供 task
messages = customer_support_template.invoke({"task": "解释退款政策"})

2. 消息占位符:MessagesPlaceholder

当你不知道消息使用什么角色,或希望在格式化过程中插入消息列表时使用。对多轮对话历史存储和 Agent 中间步骤处理非常有用。

from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder
​
prompt_template = ChatPromptTemplate.from_messages([
    ("system", "你是一个非常友好的AI助手"),
    MessagesPlaceholder(variable_name="history"),
    ("human", "{question}")
])
​
prompt_template.invoke({
    "history": [
        ("human", "5 + 2 = ?"),
        ("ai", "5 + 2 = 7")
    ],
    "question": "结果再乘以4呢?"
})

3. 可复用模板库

建议在实际项目中创建模板库,统一管理各种提示词:

# templates.py
from langchain_core.prompts import ChatPromptTemplate
​
class PromptLibrary:
    TRANSLATOR = ChatPromptTemplate.from_messages([
        ("system", "你是专业翻译,精通{source_lang}和{target_lang}"),
        ("user", "翻译以下文本:\n{text}")
    ])
​
    CODE_REVIEWER = ChatPromptTemplate.from_messages([
        ("system", "你是{language}代码审查专家,重点关注{focus}"),
        ("user", "审查代码:\n```{language}\n{code}\n```")
    ])
​
# 使用
from templates import PromptLibrary
​
messages = PromptLibrary.TRANSLATOR.format_messages(
    source_lang="英语", target_lang="中文", text="Hello World"
)

4. 模板组合

方法 1:字符串组合

role_part = "你是一个{domain}专家。"
style_part = "回答风格:{style}。"
full_system = role_part + style_part
​
template = ChatPromptTemplate.from_messages([
    ("system", full_system),
    ("user", "{question}")
])

方法 2:使用 + 运算符(LangChain 1.0 支持)

template1 = ChatPromptTemplate.from_messages([("system", "你是助手")])
template2 = ChatPromptTemplate.from_messages([("user", "{input}")])
​
combined = template1 + template2 

小结

需求

推荐方式

简单文本补全

PromptTemplate

聊天 / 多轮对话

ChatPromptTemplate

固定角色定制

partial() 预填充

动态插入历史消息

MessagesPlaceholder

统一管理提示词

可复用模板库

组合复杂提示词

字符串组合 / + 运算符