* LangChain 提示词模板详解:ChatPromptTemplate 的使用与高级特性

一、提示词模板(Prompt Templates)

1.1 为什么推荐提示词模板?

在 LangChain 开发中,构造提示词既可以直接使用 Python 字符串拼接(如 f-string、format() 或

+),也可以使用 LangChain 提供的 PromptTemplate 或 ChatPromptTemplate 。

举例1:字符串拼接方式

text 复制代码
 1  # 字符串拼接
 2  topic = "Python"
 3  difficulty = "初学者"
 4
 5  # 难以维护,容易出错
 6  prompt_str = f"你是一个{difficulty}级别的编程导师。请用简单易懂的语言解释{topic}。"
 7
 8  response = model.invoke(prompt_str)
 9  print(f"AI 回复:{response.content}...\n")

优点✅:

  • 简单直接,上手快

  • 适合临时 demo

  • 无额外学习成本

缺点❌:

  • 可读性差(变量多时混乱)

  • 不易维护(修改容易出错)

  • 无变量校验(容易漏/拼错)

  • 难以支持复杂场景(多轮对话 / RAG / Few-shot)

举例2:提示词模板

text 复制代码
  1  from langchain.prompts import PromptTemplate
  2
  3  topic = "Python"
  4  difficulty = "初学者"
  5
  6  template = PromptTemplate.from_template(
  7  "你是一个{difficulty}级别的编程导师。请用简单易懂的语言解释{topic}。"
  8  )
  9
 10  # 使用模板生成提示词
 11  prompt = template.format(difficulty=difficulty, topic=topic)
 12
 13  response = model.invoke(prompt)
 14  print(f"AI 回复:{response.content}...\n")
text 复制代码
  1  from langchain_core.prompts import ChatPromptTemplate
  2
  3  prompt_template = ChatPromptTemplate([
  4      ("system", "你是一个AI开发工程师. 你的名字是 {name}."),
  5      ("human", "{user_input}")
  6  ])
  7
  8  #调用format()方法,返回字符串
  9  prompt = prompt_template.invoke({"name":"小谷AI", "user_input":"你能帮我做什
     么?"})
 10  print(prompt)
 11

优点✅:

  • 结构清晰(变量占位)

  • 易维护、可复用

  • 自动变量校验(更安全)

  • 支持复杂场景(对话 / RAG / Agent)

  • 可与 LangChain 生态无缝集成

  • 便于调试与日志追踪

缺点❌:

  • 有一定学习成本

  • 初期写法略复杂

  • 对极简单场景略"重"

开发建议:

  • 小项目 / 临时用 → 字符串拼接

  • 正式开发 / AI应用 → 提示词模板(必选)

1.2 提示词机制演进

LangChain 1.0的架构变革中,核心的演进之一体现在 Prompt 机制上:一个结构化的、富含元数据的消

息列表已经取代单一字符串,成为与模型交互的标准数据格式。

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

① 模型接口:对应于 LangChain 中的LLM类,主要面向早期的文本补全模型。

② 工作方式:模型接受一个单一的字符串作为输人,基于此预测并生成后续的文

本内容(文本补全)。

③ Prompt 工具:核心工具是 PromptTemplate 。它的职责是接收一组变量,并通过

模板渲染,最终输出一个完整的字符串。

text 复制代码
  1  from langchain.prompts import PromptTemplate
  2
  3  prompt_template = PromptTemplate.from_template(
  4      "请给我一个关于{topic}的{type}解释。"
  5  )
  6
  7  #传入模板中的变量名
  8  prompt = prompt_template.format(type="详细", topic="量子力学")
  9
 10  print(prompt)

④ 局限性:当我们需要用这种方式模拟多轮聊天时,开发者必须在字符串中手动

拼接和伪造对话角色,例如:

text 复制代码
 1  "Human:你好\nAI:你好!有什么我能帮忙的吗?\nHuman:..."

这种方式不仅导致Prompt 的结构混乱、难以维护,也极易让模型混淆对话的边界与上下文,影响生成

质量。

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

① 模型接口:对应 LangChain 1.0 的主流接口 ChatModel。

② 工作方式:现代聊天模型 API 已原生支持角色概念。它们不再接受单一字符串,

而是要求输入一个结构化的消息列表。为构建复杂、可靠的多轮对话智能体系统奠定了坚实的基础。

③ Prompt 工具:ChatPromptTemplate 因此成为LangChain 1.0 中最核心的 Prompt工具。它的职

责是接收变量,并输出一个 List「BaseMessage](消息列表),该列表可直接传递给聊天模型。

二者对比:

特性 PromptTemplate ChatPromptTemplate
输出格式 纯文本字符串 消息列表
角色支持 ❌ 无 ✅ system/user/assistant
对话历史 ❌ 不支持 ✅ 支持
适用场景 简单提示 聊天、对话、多轮交互

因此,用于生成消息列表的 ChatPromptTemplate,也自然取代了生成字符串的 PromptTemplate,成

为构建现代LangChain 应用的首选工具。

1.3 ChatPromptTemplate 的使用

在LangChain 1.0中,ChatPromptTemplate 是用于生成消息列表的核心组件。

ChatPromptTemplate是创建聊天消息列表的提示模板。它比普通 PromptTemplate 更适合处理多角

色、多轮次的对话场景。支持 System / Human / AI 等不同角色的消息模板。

消息类型:

角色字符串 含义 用途
"system" 系统消息 设定 AI 的行为、角色、规则
"user" / "human" 用户消息 用户的输入/问题
"assistant" / "ai" AI 消息 AI 的回复(用于对话历史)

1.3.1 两种实例化方式

ChatPromptTemplate 可以通过初始化方法或 from_messages 方法来实例化提示词模板。实例化

时需要传入 messages参数。常见类型是:tuple构成的列表,参数类型(role : str,content : str )

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

该方法允许传入一个由元组(Tuple)构成的列表,列表中的每一个元组都代表一条具有特定角色的消

息。

举例1:

text 复制代码
  1  # 导入相关依赖
  2  from langchain_core.prompts import ChatPromptTemplate
  3
  4  # 定义聊天提示词模版
  5  chat_template = ChatPromptTemplate.from_messages(
  6      [
  7          ("system", "你是一个有帮助的AI机器人,你的名字是{name}。"),
  8          ("human", "你好,最近怎么样?"),
  9          ("ai", "我很好,谢谢!"),
 10          ("human", "{user_input}"),
 11      ]
 12  )
 13
 14  # 格式化聊天提示词模版中的变量
 15  prompt = chat_template.invoke({"name":"小明", "user_input":"你叫什么名字?"})
 16
 17  # 打印格式化后的聊天提示词模版内容
 18  print(prompt)
text 复制代码
 1  messages=[SystemMessage(content='你是一个有帮助的AI机器人,你的名字是小明。',
    additional_kwargs={}, response_metadata={}), HumanMessage(content='你好,
    最近怎么样?', additional_kwargs={}, response_metadata={}),
    AIMessage(content='我很好,谢谢!', additional_kwargs={},
    response_metadata={}, tool_calls=[], invalid_tool_calls=[]),
    HumanMessage(content='你叫什么名字?', additional_kwargs={},
    response_metadata={})]

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

举例:

text 复制代码
  1  from langchain_core.prompts import ChatPromptTemplate
  2
  3  #参数类型这里使用的是tuple构成的list
  4  prompt_template = ChatPromptTemplate([
  5      # 字符串 role + 字符串 content
  6      ("system", "你是一个AI开发工程师. 你的名字是 {name}."),
  7      ("human", "你能开发哪些AI应用?"),
  8      ("ai", "我能开发很多AI应用, 比如聊天机器人, 图像识别, 自然语言处理等."),
  9      ("human", "{user_input}")
 10  ])
 11
 12  #调用invoke()方法,返回ChatPromptValue
 13  prompt = prompt_template.invoke({"name":"小谷AI", "user_input":"你能帮我做什
     么?"})
 14  print(prompt)
 15
text 复制代码
 1  messages=[SystemMessage(content='你是一个AI开发工程师. 你的名字是 小谷AI.',
    additional_kwargs={}, response_metadata={}), HumanMessage(content='你能开
    发哪些AI应用?', additional_kwargs={}, response_metadata={}),
    AIMessage(content='我能开发很多AI应用, 比如聊天机器人, 图像识别, 自然语言处理
    等.', additional_kwargs={}, response_metadata={}, tool_calls=[],
    invalid_tool_calls=[]), HumanMessage(content='你能帮我做什么?',
    additional_kwargs={}, response_metadata={})]

说明:from_messages()的底层,也是调用的类的__init()__方法

1.3.2 模板调用的3种方式

对比:invoke() 、format() 、format_messages()

方式1:使用 invoke()

返回ChatPromptValue

text 复制代码
  1  from langchain_core.prompts import ChatPromptTemplate
  2
  3  #参数类型这里使用的是tuple构成的list
  4  prompt_template = ChatPromptTemplate([
  5      # 字符串 role + 字符串 content
  6      ("system", "你是一个AI开发工程师. 你的名字是 {name}."),
  7      ("human", "你能开发哪些AI应用?"),
  8      ("ai", "我能开发很多AI应用, 比如聊天机器人, 图像识别, 自然语言处理等."),
  9      ("human", "{user_input}")
 10  ])
 11
 12  prompt = prompt_template.invoke({"name":"小谷AI", "user_input":"你能帮我做什
     么?"})
 13  print(type(prompt))
 14  print(prompt)
 15  print(len(prompt.messages))

<class 'langchain_core.prompt_values.ChatPromptValue'>

messages=[SystemMessage(content='你是一个AI开发工程师. 你的名字是 小谷AI.',

additional_kwargs={}, response_metadata={}), HumanMessage(content='你能开发哪些AI应

用?', additional_kwargs={}, response_metadata={}), AIMessage(content='我能开发很多AI应用,

比如聊天机器人, 图像识别, 自然语言处理等.', additional_kwargs={}, response_metadata={}),

HumanMessage(content='你能帮我做什么?', additional_kwargs={}, response_metadata={})]

4

方式2:使用format()

返回字符串

text 复制代码
  1  from langchain_core.prompts import ChatPromptTemplate
  2
  3  #参数类型这里使用的是tuple构成的list
  4  prompt_template = ChatPromptTemplate([
  5      # 字符串 role + 字符串 content
  6      ("system", "你是一个AI开发工程师. 你的名字是 {name}."),
  7      ("human", "你能开发哪些AI应用?"),
  8      ("ai", "我能开发很多AI应用, 比如聊天机器人, 图像识别, 自然语言处理等."),
  9      ("human", "{user_input}")
 10  ])
 11
 12  #方式1:调用format()方法,返回字符串
 13  prompt = prompt_template.format(name="小谷AI", user_input="你能帮我做什么?")
 14  print(type(prompt))
 15  print(prompt)
text 复制代码
 1  <class 'str'>
 2
 3  System: 你是一个AI开发工程师. 你的名字是 小谷AI.
 4  Human: 你能开发哪些AI应用?
 5  AI: 我能开发很多AI应用, 比如聊天机器人, 图像识别, 自然语言处理等.
 6  Human: 你能帮我做什么?

方式3:使用format_messages()

返回消息列表

text 复制代码
  1  from langchain_core.prompts import ChatPromptTemplate
  2
  3  prompt_template = ChatPromptTemplate([
  4      ("system", "你是一个AI开发工程师. 你的名字是 {name}."),
  5      ("human", "你能开发哪些AI应用?"),
  6      ("ai", "我能开发很多AI应用, 比如聊天机器人, 图像识别, 自然语言处理等."),
  7      ("human", "{user_input}")
  8  ])
  9
 10  #调用format_messages()方法,返回消息列表
 11  prompt = prompt_template.format_messages(name="小谷AI", user_input="你能帮我做
     什么?")
 12  print(type(prompt))
 13  print(prompt)
text 复制代码
 1  <class 'list'>
 2  [SystemMessage(content='你是一个AI开发工程师. 你的名字是 小谷AI.',
    additional_kwargs={}, response_metadata={}), HumanMessage(content='你能开
    发哪些AI应用?', additional_kwargs={}, response_metadata={}),
    AIMessage(content='我能开发很多AI应用, 比如聊天机器人, 图像识别, 自然语言处理
    等.', additional_kwargs={}, response_metadata={}, tool_calls=[],
    invalid_tool_calls=[]), HumanMessage(content='你能帮我做什么?',
    additional_kwargs={}, response_metadata={})]

1.3.3 结合LLM调用

举例:

text 复制代码
  1  from dotenv import load_dotenv
  2  from langchain_core.prompts import ChatPromptTemplate
  3  import os
  4  from langchain.chat_models import init_chat_model
  5
  6  ######1、提供大模型#########
  7  load_dotenv(override=True)
  8
  9  CLOSEAI_API_KEY = os.getenv("CLOSEAI_API_KEY")
 10  CLOSEAI_BASE_URL = os.getenv("CLOSEAI_BASE_URL")
 11
 12  model = init_chat_model(
 13      model="gpt-5.4-mini",
 14      model_provider="openai",
 15      api_key=CLOSEAI_API_KEY,
 16      base_url=CLOSEAI_BASE_URL
 17  )
 18
 19  ######2、提供提示词#########
 20  chat_prompt = ChatPromptTemplate.from_messages([
 21      ("system", "你是一个数学家,你可以计算任何算式"),
 22      ("human", "{text}"),
 23  ])
 24
 25
 26  # 输入提示
 27  prompt_value = chat_prompt.invoke({
 28      "text":"我今年18岁,我的舅舅今年38岁,我的爷爷今年72岁,我和舅舅一共多少岁了?"
 29  })
 30
 31
 32  ######3、结合提示词,调用大模型#########
 33  # 得到模型的输出
 34  output = model.invoke(prompt_value)
 35  # 打印输出内容
 36  print(output.content)
text 复制代码
 1  你今年 18 岁,舅舅今年 38 岁。
 2  一共是:
 3
 4  18 + 38 = **56 岁**
 5
 6  所以,你和舅舅一共 **56 岁**。

1.3.4 更丰富的初始化参数类型

前面讲了ChatPromptTemplate的两种创建方式。我们看到不管使用实例初始化方法,还是使用

from_messages(),参数类型都是列表类型。列表中的元素可以是多种类型,前面我们主要测试了元

组类型。

源码:

text 复制代码
 1  def __init__(self,
 2               messages: Sequence[BaseMessagePromptTemplate | BaseMessage |
    BaseChatPromptTemplate | tuple[str | type, str | list[dict] | list[object]] |
    str | dict[str, Any]],
 3               *,
 4               template_format: Literal["f-string", "mustache", "jinja2"] = "f-
    string",
 5               **kwargs: Any) -> None

源码:

text 复制代码
 1  @classmethod def from_messages(cls,
 2                    messages: Sequence[BaseMessagePromptTemplate | BaseMessage
    | BaseChatPromptTemplate | tuple[str | type, str | list[dict] | list[object]]
    | str | dict[str, Any]],
 3                    template_format: Literal["f-string", "mustache", "jinja2"]
    = "f-string")
 4    -> ChatPromptTemplate

结论:参数是列表类型,列表的元素可以是字符串、字典、字符串构成的元组、消息类型、提示词模板

类型、消息提示词模板类型等

类型1:str列表类型

列表参数格式是str类型(不推荐),因为默认角色都是human

text 复制代码
  1  #1.导入相关依赖
  2  from langchain_core.prompts import ChatPromptTemplate
  3
  4  # 2.定义聊天提示词模版
  5  chat_template = ChatPromptTemplate.from_messages(
  6    [
  7      "Hello, {name}!"  # 等价于 ("human", "Hello, {name}!")
  8      ]
  9  )
 10
 11  # 3. 使用invoke执行
 12  messages = chat_template.invoke({"name":"小谷AI"})
 13
 14  # 4.打印格式化后的聊天提示词模版内容
 15  print(messages)
text 复制代码
 1  messages=[HumanMessage(content='Hello, 小谷AI!', additional_kwargs={},
    response_metadata={})]

类型2:tuple列表类型

列表参数格式是元组类型

text 复制代码
 1  # 示例: 元组形式的消息
 2  prompt = ChatPromptTemplate.from_messages([
 3      ("system", "你的名字是{role}."),
 4      ("human", "很高兴认识你"),
 5  ])
 6
 7  print(prompt.invoke({"role":"小智"}))
text 复制代码
 1  messages=[SystemMessage(content='你的名字是小智.', additional_kwargs={},
    response_metadata={}), HumanMessage(content='很高兴认识你',
    additional_kwargs={}, response_metadata={})]

类型3:dict列表类型

列表参数格式是dict类型

text 复制代码
 1  # 示例: 字典形式的消息
 2  prompt = ChatPromptTemplate.from_messages([
 3      {"role": "system", "content": "你的名字是{role}."},
 4      {"role": "human", "content":"很高兴认识你"},
 5  ])
 6
 7  print(prompt.invoke({"role":"小智"}))
text 复制代码
 1  messages=[SystemMessage(content='你的名字是小智.', additional_kwargs={},
    response_metadata={}), HumanMessage(content='很高兴认识你',
    additional_kwargs={}, response_metadata={})]

类型4:Message列表类型

text 复制代码
  1  from langchain_core.messages import SystemMessage,HumanMessage
  2
  3  chat_prompt_template = ChatPromptTemplate.from_messages([
  4      SystemMessage(content="我是一个贴心的智能助手"),
  5      HumanMessage(content="我的问题是:人工智能英文怎么说?")
  6
  7  ])
  8
  9  messages = chat_prompt_template.invoke({})
 10  print(messages)
 11  print(type(messages))

messages=[SystemMessage(content='我是一个贴心的智能助手', additional_kwargs={},

response_metadata={}), HumanMessage(content='我的问题是:人工智能英文怎么说?',

additional_kwargs={}, response_metadata={})]

<class 'langchain_core.prompt_values.ChatPromptValue'>

注意:在XxxMessage中不能有占位符。即:

text 复制代码
  1  from langchain_core.messages import SystemMessage,HumanMessage
  2
  3  chat_prompt_template = ChatPromptTemplate.from_messages([
  4      SystemMessage(content="我是一个贴心的智能助手"),
  5      HumanMessage(content="我的问题是:{word}英文怎么说?")
  6
  7  ])
  8
  9  messages = chat_prompt_template.invoke({"word":"人工智能"})
 10  print(messages)
 11  print(type(messages))
text 复制代码
 1  messages=[SystemMessage(content='我是一个贴心的智能助手', additional_kwargs=
    {}, response_metadata={}), HumanMessage(content='我的问题是:{word}英文怎么
    说?', additional_kwargs={}, response_metadata={})]
 2  <class 'langchain_core.prompt_values.ChatPromptValue'>

类型5:MessagePromptTemplate列表类型

LangChain提供不同类型的MessagePromptTemplate。最常用的是

SystemMessagePromptTemplate 、HumanMessagePromptTemplate 和

AIMessagePromptTemplate ,分别创建系统消息、人工消息和AI消息。

基本概念:

HumanMessagePromptTemplate,专用于生成用户消息(HumanMessage)的模板类

  • 模板化:支持使用变量占位符,可以在运行时填充具体值

  • 格式化:能够将模板与输入变量结合生成最终的聊天消息

  • 输出类型:生成 HumanMessage 对象(content + role="human" )

  • 设计目的 :简化用户输入消息的模板化构造,避免重复定义角色

SystemMessagePromptTemplate、AIMessagePromptTemplate:类似于上面,不再赘述

举例1:

text 复制代码
  1  # 导入聊天消息类模板
  2  from langchain_core.prompts import ChatPromptTemplate,
     HumanMessagePromptTemplate, SystemMessagePromptTemplate
  3
  4  # 创建消息模板
  5  system_message_prompt = SystemMessagePromptTemplate.from_template("你是一个
     {role}")
  6
  7  human_message_prompt = HumanMessagePromptTemplate.from_template("给我解释
     {concept},用浅显易懂的语言")
  8
  9  # 组合成聊天提示模板
 10  chat_prompt = ChatPromptTemplate.from_messages([
 11      system_message_prompt,
 12      human_message_prompt
 13  ])
 14
 15  # 格式化提示
 16  formatted_messages = chat_prompt.invoke({"role":"物理学家","concept":"相对
     论"})
 17  print(formatted_messages)
text 复制代码
 1  messages=[SystemMessage(content='你是一个物理学家', additional_kwargs={},
    response_metadata={}), HumanMessage(content='给我解释相对论,用浅显易懂的语
    言', additional_kwargs={}, response_metadata={})]

类型6:BaseChatPromptTemplate列表类型

使用 BaseChatPromptTemplate,可以理解为ChatPromptTemplate里嵌套了

ChatPromptTemplate。

举例1:带参数

text 复制代码
  1  from langchain_core.prompts import ChatPromptTemplate
  2
  3  # 使用 BaseChatPromptTemplate(嵌套的 ChatPromptTemplate)
  4  nested_prompt_template1 = ChatPromptTemplate.from_messages([
  5      ("system", "我是一个人工智能助手,我的名字叫{name}")
  6  ])
  7  nested_prompt_template2 = ChatPromptTemplate.from_messages([
  8      ("human", "很高兴认识你,我的问题是{question}")
  9  ])
 10
 11  prompt_template = ChatPromptTemplate.from_messages([
 12      nested_prompt_template1,nested_prompt_template2
 13  ])
 14
 15  prompt_template.invoke({"name":"小智","question":"你为什么这么帅?"})
text 复制代码
 1  ChatPromptValue(messages=[SystemMessage(content='我是一个人工智能助手,我的名
    字叫小智', additional_kwargs={}, response_metadata={}),
    HumanMessage(content='很高兴认识你,我的问题是你为什么这么帅?',
    additional_kwargs={}, response_metadata={})])

举例2:不带参数

text 复制代码
  1  from langchain_core.prompts import ChatPromptTemplate
  2
  3  # 使用 BaseChatPromptTemplate(嵌套的 ChatPromptTemplate)
  4  nested_prompt_template1 = ChatPromptTemplate.from_messages([("system", "我是
     一个人工智能助手")])
  5  nested_prompt_template2 = ChatPromptTemplate.from_messages([("human", "很高兴
     认识你")])
  6
  7  prompt_template = ChatPromptTemplate.from_messages([
  8      nested_prompt_template1,nested_prompt_template2
  9  ])
 10
 11  prompt_template.invoke({})
text 复制代码
 1  ChatPromptValue(messages=[SystemMessage(content='我是一个人工智能助手',
    additional_kwargs={}, response_metadata={}), HumanMessage(content='很高兴
    认识你', additional_kwargs={}, response_metadata={})])

举例3:综合使用

text 复制代码
  1  from langchain_core.prompts import (
  2      ChatPromptTemplate,
  3      SystemMessagePromptTemplate,
  4      HumanMessagePromptTemplate,
  5  )
  6  from langchain_core.messages import SystemMessage, HumanMessage
  7
  8  # 示例 1: 使用 BaseMessage(已实例化的消息)
  9  system_msg = SystemMessage(content="你是一个AI工程师。")
 10  human_msg = HumanMessage(content="你好!")
 11
 12  # 示例 2: 使用 BaseMessagePromptTemplate
 13  system_prompt = SystemMessagePromptTemplate.from_template("你是一个{role}.")
 14  human_prompt = HumanMessagePromptTemplate.from_template("{user_input}")
 15
 16  # 示例 3: 使用 BaseChatPromptTemplate(嵌套的 ChatPromptTemplate)
 17  nested_prompt = ChatPromptTemplate.from_messages([("system", "嵌套提示词")])
 18
 19  prompt = ChatPromptTemplate.from_messages([
 20      system_msg,     # MessageLike (BaseMessage)
 21      human_msg,      # MessageLike (BaseMessage)
 22      system_prompt,  # MessageLike (BaseMessagePromptTemplate)
 23      human_prompt,   # MessageLike (BaseMessagePromptTemplate)
 24      nested_prompt,  # MessageLike (BaseChatPromptTemplate)
 25  ])
 26
 27  prompt.invoke({"role":"人工智能专家","user_input":"介绍一下大模型的应用场景"})
text 复制代码
 1  ChatPromptValue(messages=[SystemMessage(content='你是一个AI工程师。',
    additional_kwargs={}, response_metadata={}), HumanMessage(content='你
    好!', additional_kwargs={}, response_metadata={}),
    SystemMessage(content='你是一个人工智能专家.', additional_kwargs={},
    response_metadata={}), HumanMessage(content='介绍一下大模型的应用场景',
    additional_kwargs={}, response_metadata={}), SystemMessage(content='嵌套
    提示词', additional_kwargs={}, response_metadata={})])

1.4 高级特性

1.4.1 部分变量预填充:partial()

预填充某些固定不变的变量,创建模板的变体。

使用场景:

  • 某些变量在所有调用中都相同

  • 需要为不同用户/场景创建定制模板

举例1:

text 复制代码
  1  from langchain_core.prompts import ChatPromptTemplate
  2
  3  # 原始模板
  4  template = ChatPromptTemplate.from_messages([
  5      ("system", "你是{role},目标用户是{audience}"),
  6      ("user", "{task}")
  7  ])
  8
  9  # 部分填充
 10  customer_support_template = template.partial(
 11      role="客服专员",
 12      audience="普通用户"
 13  )
 14
 15  # 现在只需要提供 task
 16  messages = customer_support_template.invoke({"task":"解释退款政策"})
 17  print(messages)
text 复制代码
 1  messages=[SystemMessage(content='你是客服专员,目标用户是普通用户',
    additional_kwargs={}, response_metadata={}), HumanMessage(content='解释退
    款政策', additional_kwargs={}, response_metadata={})]

举例2:

text 复制代码
  1  # 场景:为不同部门创建专用模板
  2  base_template = ChatPromptTemplate.from_messages([
  3      ("system", "你是{department}的{role}"),
  4      ("user", "{task}")
  5  ])
  6
  7  # IT 部门
  8  it_template = base_template.partial(
  9      department="IT 部门",
 10      role="技术支持"
 11  )
 12
 13  # 销售部门
 14  sales_template = base_template.partial(
 15      department="销售部门",
 16      role="销售顾问"
 17  )
 18
 19  sales_template.invoke({"task":"为什么每年年底汽车会促销"})
text 复制代码
 1  ChatPromptValue(messages=[SystemMessage(content='你是销售部门的销售顾问',
    additional_kwargs={}, response_metadata={}), HumanMessage(content='为什么
    每年年底汽车会促销', additional_kwargs={}, response_metadata={})])

1.4.2 消息占位符

当你不确定消息提示模板使用什么角色,或者希望在格式化过程中插入消息列表时,该怎么办? 这就

需要使用消息占位符,负责在特定位置添加消息列表。

使用场景:多轮对话系统存储历史消息以及Agent的中间步骤处理此功能非常有用。

方式1:JSON形式

举例1:

text 复制代码
  1  from langchain_core.prompts import ChatPromptTemplate
  2
  3  template = ChatPromptTemplate.from_messages(
  4      [
  5          ("system", "你是一个有用的AI助手"),
  6          ("placeholder", "{conversation}"),
  7      ]
  8  )
  9
 10  prompt_value = template.invoke(
 11      {
 12          "conversation": [
 13              ("human", "你好!"),
 14              ("ai", "今天我能帮你做什么?"),
 15              ("human", "你能给我做一个冰激凌吗?"),
 16              ("ai", "抱歉,我没有这样的能力"),
 17          ]
 18      }
 19  )
 20
 21  print(prompt_value)

输出

text 复制代码
 1  messages=[SystemMessage(content='你是一个有用的AI助手', additional_kwargs=
    {}, response_metadata={}), HumanMessage(content='你好!',
    additional_kwargs={}, response_metadata={}), AIMessage(content='今天我能帮
    你做什么?', additional_kwargs={}, response_metadata={}, tool_calls=[],
    invalid_tool_calls=[]), HumanMessage(content='你能给我做一个冰激凌吗?',
    additional_kwargs={}, response_metadata={}), AIMessage(content='抱歉,我没
    有这样的能力', additional_kwargs={}, response_metadata={}, tool_calls=[],
    invalid_tool_calls=[])]

方式2:MessagesPlaceholder实例

举例1:

text 复制代码
  1  from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder
  2  from langchain_core.messages import HumanMessage
  3
  4  prompt_template = ChatPromptTemplate.from_messages([
  5      ("system", "You are a helpful assistant"),
  6      MessagesPlaceholder("msgs")
  7  ])
  8  prompt_template.invoke({"msgs": [HumanMessage(content="hi!")]})
  9
 10  # prompt_template.format_messages(msgs=[HumanMessage(content="hi!")])
text 复制代码
 1  ChatPromptValue(messages=[SystemMessage(content='You are a helpful
    assistant', additional_kwargs={}, response_metadata={}),
    HumanMessage(content='hi!', additional_kwargs={}, response_metadata=
    {})])

这将生成两条消息,第一条是系统消息,第二条是我们传入的 HumanMessage。 如果我们传入了 5 条

消息,那么总共会生成 6 条消息(系统消息加上传入的 5 条消息)。 这对于将一系列消息插入到特定位

置非常有用。

举例2:存储对话历史内容

text 复制代码
  1  from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder
  2
  3  prompt_template = ChatPromptTemplate.from_messages(
  4      [
  5          ("system", "你是一个非常友好的AI助手"),
  6          MessagesPlaceholder(variable_name="history"),
  7          ("human", "{question}")
  8      ]
  9  )
 10
 11  prompt_template.invoke(
 12      {
 13          "history": [
 14              ("human", "5 + 2 = ?"),
 15              ("ai", "5 + 2 = 7")
 16          ],
 17          "question": "结果再乘以4呢?"
 18      }
 19  )
text 复制代码
 1  ChatPromptValue(messages=[SystemMessage(content='你是一个非常友好的AI助手',
    additional_kwargs={}, response_metadata={}), HumanMessage(content='5 + 2
    = ?', additional_kwargs={}, response_metadata={}), AIMessage(content='5
    + 2 = 7', additional_kwargs={}, response_metadata={}, tool_calls=[],
    invalid_tool_calls=[]), HumanMessage(content='结果再乘以4呢?',
    additional_kwargs={}, response_metadata={})])

1.4.3 可复用模板库

在实际项目中,建议创建模板库。

举例1:

templates.py文件声明如下

text 复制代码
  1  from langchain_core.prompts import ChatPromptTemplate
  2
  3  class PromptLibrary:
  4      """可复用的提示词模板库"""
  5
  6      TRANSLATOR = ChatPromptTemplate.from_messages([
  7          ("system", "你是专业翻译,精通{source_lang}和{target_lang}"),
  8          ("user", "翻译以下文本:\n{text}")
  9      ])
 10
 11      CODE_REVIEWER = ChatPromptTemplate.from_messages([
 12          ("system", "你是{language}代码审查专家,重点关注{focus}"),
 13          ("user", "审查代码:\n```{language}\n{code}\n```")
 14      ])
 15
 16      SUMMARIZER = ChatPromptTemplate.from_messages([
 17          ("system", "你是内容摘要专家"),
 18          ("user", "将以下内容总结为{num}个要点:\n{content}")
 19      ])
 20
 21      TUTOR = ChatPromptTemplate.from_messages([
 22          ("system", "你是{subject}导师,学生水平:{level}"),
 23          ("user", "{question}")
 24      ])

其它文件中使用:

text 复制代码
 1  from templates import PromptLibrary
 2
 3  messages = PromptLibrary.TRANSLATOR.format_messages(
 4      source_lang="英语",
 5      target_lang="中文",
 6      text="Hello World"
 7  )

举例2:

text 复制代码
  1  # templates/
  2  # ├── __init__.py
  3  # ├── common.py        # 通用模板
  4  # ├── translation.py   # 翻译相关
  5  # └── coding.py        # 编程相关
  6
  7  # common.py
  8  from langchain_core.prompts import ChatPromptTemplate
  9
 10  FRIENDLY_ASSISTANT = ChatPromptTemplate.from_messages([
 11      ("system", "你是一个友好的助手"),
 12      ("user", "{input}")
 13  ])

1.4.4 模板组合

将多个模板片段组合成复杂的提示词。

方法 1:字符串组合

text 复制代码
  1  # 定义可复用的部分
  2  role_part = "你是一个{domain}专家。"
  3  style_part = "回答风格:{style}。"
  4  constraint_part = "限制:{constraint}。"
  5
  6  # 组合
  7  full_system = role_part + style_part + constraint_part
  8
  9  template = ChatPromptTemplate.from_messages([
 10      ("system", full_system),
 11      ("user", "{question}")
 12  ])

方法 2:使用 + 运算符

text 复制代码
  1  template1 = ChatPromptTemplate.from_messages([
  2      ("system", "你是助手")
  3  ])
  4
  5  template2 = ChatPromptTemplate.from_messages([
  6      ("user", "{input}")
  7  ])
  8
  9  # 组合(LangChain 1.0 支持)
 10  combined = template1 + template2
相关推荐
鬓戈1 小时前
Rust 语言与 AI 应用生态调研及学习路径
人工智能·学习·rust
天远API1 小时前
零信任架构实战:基于天远人企关联构建自动化图谱网关
网络·人工智能·架构·自动化
爱吃提升1 小时前
文生视频模型发展趋势(2026)
人工智能·音视频
AIGS0011 小时前
什么是本体语义平台?和知识图谱、传统数据中台的区别在哪
人工智能·知识图谱·数据中台·ai问数·本体语义平台·智能数据中台
YOLO数据集集合1 小时前
烟叶病虫害检测数据集 | 烟叶病害 无人机航拍 智慧农业 病害检测 9125期
人工智能·目标检测·目标跟踪·无人机·烟草病虫·烟草虫害
Experience-摆渡1 小时前
一个开源免费的本地AI抠图工具 unbagrnd:断网也能用的背景移除
人工智能·开源
只是甲1 小时前
Text2SQL 系列博客 07:4 步选型法(上)- 场景与标准的定义
人工智能·text2sql·nl2sql·ai agent·智能问数
Csvn2 小时前
AI 应用日志别再 print 了:结构化日志 + request_id 贯穿(O01)
人工智能
空 白II2 小时前
9.26 大语言模型研究简报:把 Agent 开发做成“数据—训练—Harness”闭环
人工智能·语言模型·自然语言处理