LangChain消息系统全解析:从基础到实战(四)

文章目录

  • [一、Messages 消息](#一、Messages 消息)
    • [1.1 消息的内部结构](#1.1 消息的内部结构)
    • [1.2 对话历史管理(聊天记忆)](#1.2 对话历史管理(聊天记忆))
    • [1.3 消息属性 content (字符串类型、字典列表)](#1.3 消息属性 content (字符串类型、字典列表))
    • [1.4 消息属性 content_blocks(解决各供应商 API 格式差异问题)](#1.4 消息属性 content_blocks(解决各供应商 API 格式差异问题))
  • 二、提示词模板
    • [2.1 ChatPromptTemplate 的使用](#2.1 ChatPromptTemplate 的使用)
    • [2.2 模板调用方式](#2.2 模板调用方式)
    • [2.3 更丰富的初始化参数类型](#2.3 更丰富的初始化参数类型)
    • [2.4 高级特性](#2.4 高级特性)
      • [2.4.1 partial(部分变量预填充)](#2.4.1 partial(部分变量预填充))
      • [2.4.2 消息占位符](#2.4.2 消息占位符)
      • [2.4.3 可复用模板库](#2.4.3 可复用模板库)
      • [2.4.4 模板组合](#2.4.4 模板组合)

声明 :该章节涉及模型的初始化,模型的初始化代码参考如下,后续该内容将省略(后续代码中使用的 model 都需要类似下面一样初始化):

python 复制代码
from langchain.chat_models import init_chat_model
from dotenv import load_dotenv
import os

# 从.env文件中加载环境变量
load_dotenv(override=True)
CLOSEAI_API_KEY = os.getenv("CLOSEAI_API_KEY")
CLOSEAI_BASE_URL = os.getenv("CLOSEAI_BASE_URL")

model = init_chat_model(
	model="gpt-5.4-mini",
	model_provider="openai",
	api_key=CLOSEAI_API_KEY,
	base_url=CLOSEAI_BASE_URL
)

一、Messages 消息

大模型没有记忆,它的输出只和输入模型的内容有关(上下文)。很多大模型API服务也没有在服务端维护会话历史,是无状态的。因此,如果应用需要记住对话历史,需要在程序中维护消息列表。
在 LangChain 中,Message(消息)是模型交互的最基本单元。它既代表模型接收到的输入(Input) ,也代表模型生成的输出(Output) 。
每一轮与大模型的对话,都由一条或多条 Message 构成。每个 Message 不仅包含 文字内容 ,还携带描述上下文状态的 元信息(metadata) ,用于保持对话的一致性和可追踪性。比如,模型在多轮交互中理解"谁在说话"、"说了什么"、"这条信息属于哪一轮对话"
LangChain 在 1.0 中提供了跨模型统一的 Message 标准。无论你使用的是 OpenAI、Anthropic、Gemini 还是本地模型,这一标准都能保持一致的行为。好处:

  • 兼容性强 :不同模型的消息格式自动对齐。
  • 可扩展性高 :方便添加多模态内容或自定义字段。
  • 可追踪性好 :为 LangSmith 等调试工具提供一致的上下文数据结构

1.1 消息的内部结构

LangChain的消息(Message)对象包含三种字段:

  • Role :消息所属的角色或类型,如 system 、 user 、 assistant 。
  • Content:消息内容
  • Metadata:(可选)元数据,存储额外信息。如:消息ID、响应时间、token消耗量、消息标签等

消息的类型

LangChain定义了很多消息类型,通过 role 区分。常用的有四种:系统消息(system)、用户消息(user)、助手消息(assistant、ai)、工具调用消息(tool)

角色 字典格式 对象格式 用途 示例
System {"role": "system", ...} SystemMessage(...) 设定 AI 的行为、角色、规则 "你是一个专业的数学老师"
User {"role":"user", ...} HumanMessage(...) 用户输入 "什么是微积分?"
Assistant {"role":"assistant",...} AIMessage(...) AI 的回复 "微积分是研究变化率的数学分支..."
Tool {"role": "tool",...} ToolMessage(...) 工具执行的结果 "今天北京天气晴朗,万里无云"
  • 系统消息 :也称为系统提示词,用于在对话开始时为模型设定角色、行为准则和上下文背景。它像是给AI助手的一
    份工作说明书,决定了其回答问题的风格、领域和专业范围。
  • 用户消息 :也称为用户提示词,在多轮对话中,它表示用户的一次输入。可以包含简单的文本问题,也可以是复杂
    的多模态内容(如图片、音频、文档等)。
  • 助手消息:代表模型的回复,包括生成的文本、工具调用、元数据等。
  • 工具调用消息:工具调用结果匹配的消息类型。将此消息返回给模型,让模型基于这个结果继续生成回复。在Tools一节详细介绍。
    消息类型一:json格式举例
python 复制代码
# 通过JSON初始化
messages = [
	{"role": "system", "content": "你是一个善于给出通俗易懂解释的AI助手"},
	{"role": "user", "content": "你好"},
	{"role": "assistant", "content": "你好!我能帮你什么?"},
	{"role": "user", "content": "什么是机器学习"}
]

response = model.invoke(messages)
print(response.content)

消息类型二:对象格式举例

python 复制代码
from langchain_core.messages import SystemMessage,HumanMessage,AIMessage

# 通过JSON初始化
messages = [
	SystemMessage(content="你是一个善于给出通俗易懂解释的AI助手"),   # 可省略字段 content=
	HumanMessage(content="你好"),       # 可省略字段 content=    还可以拥有name (用户名)、id(message的ID)
	AIMessage("你好!我能帮你什么?"),
	HumanMessage("什么是机器学习"),
]

response = model.invoke(messages)
print(response.content)

消息对象说明

  • SystemMessage参数列表:content :消息内容,字段名可以省略
python 复制代码
SystemMessage("你是个善解人意的助手")
# 或者
SystemMessage(content="你是个善解人意的助手")  # 同上
  • HumanMessage参数列表:消息内容,字段名可以省略。该函数拥有 name 和 id 元数据字段,当消息类型相同,对消息进行区分。但不是所有模型都支持这一功能,是否支持取决于模型供应商,需要查看官方手册。
python 复制代码
HumanMessage("你好啊~")   
# 或者
HumanMessage(content="你好啊~")

举例:通过调用展示 name 的作用。模型加载了 name传递的信息,这在多人对话场景很有用。

python 复制代码
from langchain_core.messages import SystemMessage,HumanMessage,AIMessage

messages = [
	SystemMessage("你是一个信息抽取器。你会收到多条来自不同发言者的 user 消息。每条消息可能带有 name 字段。你的任务是:严格根据每条消息的 name 提取发言者及其观点,并输出JSON。禁止使用"第一个人/第二个人"这种相对称呼。若某条消息没有 name,则输出 unknown。输出格式:{\"speakers\":[{\"name\":\"...\",\"claim\":\"...\"}]}"),
	HumanMessage(
		content="我认为 1+1=2",
		name="Bob"
	),
	HumanMessage(
		content="我认为 1+1>2",
		name="Tom"
	),
	HumanMessage(
		content="请列出谁说了什么,不要判断对错。",
		name="audience"
	)
]

response = model.invoke(messages)
print(response.content)
'''
{"speakers":[{"name":"Bob","claim":"我认为 1+1=2"},{"name":"Tom","claim":"我认为 1+1>2"},
{"name":"audience","claim":"请列出谁说了什么,不要判断对错。"}]}
'''

使用 ChatOpenRouter 调用没有将 name 正确传递给模型服务(输出的 name 为 unknown)

python 复制代码
from langchain_openrouter import ChatOpenRouter

messages = [
	SystemMessage("你是一个信息抽取器。你会收到多条来自不同发言者的 user 消息。每条消息可能带有 name 字段。你的任务是:严格根据每条消息的 name 提取发言者及其观点,并输出JSON。禁止使用"第一个人/第二个人"这种相对称呼。若某条消息没有 name,则输出 unknown。输出格式:{\"speakers\":[{\"name\":\"...\",\"claim\":\"...\"}]}"),
	HumanMessage(
		content="我认为 1+1=2",
		name="Bob"
	),
	HumanMessage(
		content="我认为 1+1>2",
		name="Tom"
	),
	HumanMessage(
		content="请列出谁说了什么,不要判断对错。",
		name="audience"
	)
]

response = model.invoke(messages)
print(response.content)
'''
{"speakers":[{"name":"unknown","claim":"我认为 1+1=2"},{"name":"unknown","claim":"我认
为 1+1>2"}]}
'''
  • AIMessage参数列表:模型输出的原始内容,字段名可以省略
python 复制代码
AIMessage("你好~")

response_metadata :AIMessage特有属性,LLM的响应中附加元数据,根据不同模型会有不同,如可能会包含本次token使用量等信息。

tool_calls :AIMessage特有属性,表示工具调用信息。当LLM决定调用工具时,在AIMessage 中就会包含这个属性,没有工具调用则为空。

usage_metadata :用量信息

python 复制代码
tool_calls=[
	{
		'name': 'get_weather',        # 应调用的工具名
		'args': {'city': '杭州'},     # 调用工具的参数
		'id': 'call_00_gIXYOD1Q1OkEXmdDBqXR1578',  # 工具调用的唯一标识ID
		'type': 'tool_call'
	},
	{
		'name': 'get_news',
		'args': {},
		'id': 'call_01_jD3phD5PEaIZf0mVLhKt0861',
		'type': 'tool_call'
	}
]
  • ToolMessage参数列表
    content :文件内容
    name :工具名称
    tool_call_id :工具调用唯一ID,ToolMessage必须紧邻匹配的AIMessage,和前者tool_calls中的id一致
python 复制代码
ToolMessage(
	content="<工具输出>",
	name="get_weather"
	tool_call_id="call_00_nUD2NC9QRN5Cg1GaoIkBJQ4s" # 一定要和AI消息中的调用ID匹配
)

工具调用举例(json格式)

python 复制代码
from langchain.chat_models import init_chat_model


def get_weather(city: str) -> str:
	return "不错哦~"
	
# 模拟模型绑定工具
model_with_tools = model.bind_tools([get_weather])

ai_message = {
	"role": "assistant",
	"content": "",
	"tool_calls": [{
		"name": "get_weather",
		"args": {"location": "北京"},
		"id": "call_00_nUD2NC9QRN5Cg1GaoIkBJQ4s"
	}]
}

tool_message = {
	"role": "tool",
	"content": "今天北京天气晴朗,万里无云~",
	"tool_call_id": "call_00_nUD2NC9QRN5Cg1GaoIkBJQ4s"
}

messages = [
	{"role": "user", "content": "北京天气如何"},
	ai_message,
	tool_message
]

response = model.invoke(messages)
print(response)

1.2 对话历史管理(聊天记忆)

每次对话都要在原有的消息列表中添加新消息,不可重新创建新的列表。
比如下面代码为每次对话都是重新创建新的列表,聊天不带记忆

python 复制代码
conversation = [{"role": "user", "content": "我叫张三"}]
response1 = model.invoke(conversation)

conversation = [{"role": "user", "content": "我叫什么?"}]   # 重新创建! 无上下文  AI 不记得!
response2 = model.invoke(conversation)                       # 丢失了历史

正确的做法应该保存历史消息

python 复制代码
conversation = []

# 第一次
conversation.append({"role": "user", "content": "我叫张三"})
response1 = model.invoke(conversation)

# 关键:保存 AI 回复
conversation.append({"role": "assistant", "content": response1.content})

# 第二次(传递完整历史)
conversation.append({"role": "user", "content": "我叫什么?"})   # 保留上下文
response2 = model.invoke(conversation)                           # AI 记得!

对话历史优化

对话历史会越来越长,消耗大量 tokens 和成本。可以只保留最近 N 轮对话

  • 总是保留 system 消息(定义角色)
  • 只保留最近 N 轮对话,丢弃更早的历史
python 复制代码
def keep_recent_messages(messages, max_pairs=3):
	"""
	保留最近的 N 轮对话
	max_pairs: 保留的对话轮数(每轮 = user + assistant)
	"""
	# 分离 system 和对话
	system_msgs = [m for m in messages if m.get("role") == "system"]
	conversation_msgs = [m for m in messages if m.get("role") != "system"]
	# 只保留最近的
	recent_msgs = conversation_msgs[-(max_pairs * 2):]
	# 返回:system + 最近对话
	return system_msgs + recent_msgs

long_conversation = [
	{"role": "system", "content": "你是 Python 导师"}
]

# 第 1 轮
long_conversation.append({"role": "user", "content": "什么是列表?用一句解释"})
r1 = model.invoke(long_conversation)
long_conversation.append({"role": "assistant", "content": r1.content})

# 第 2 轮
long_conversation.append({"role": "user", "content": "列表和元组有什么区别?用一句解释"})
r2 = model.invoke(long_conversation)
long_conversation.append({"role": "assistant", "content": r2.content})

# 第 3 轮
long_conversation.append({"role": "user", "content": "什么是字典呢?用一句解释"})
r3 = model.invoke(long_conversation)
long_conversation.append({"role": "assistant", "content": r3.content})
print(f"原始消息数: {len(long_conversation)}")

# 优化:只保留最近 2 轮
optimized = keep_recent_messages(long_conversation, max_pairs=2)
print(f"优化后消息数: {len(optimized)}")
print(f"保留的内容: system + 最近2轮对话")

# 添加新的用户问题
optimized.append({"role": "user", "content": "我第一个问题问的是什么?"})

# 使用优化后的历史
response = model.invoke(optimized)
print(f"\nAI 回复: {response.content}")

1.3 消息属性 content (字符串类型、字典列表)

消息的 content 可以理解为数据内容,它是弱类型的,支持字符串和列表(列表元素通常为字典)

  • 存储字符串:如果只是纯文本内容,直接传递字符串就好
python 复制代码
from LangChain.messages import HumanMessage

HumanMessage(content="你好啊")
  • 存储字典列表:如果需要发送的不只是文本,如多模态内容,需要传递一些图片等信息时,则需要 content 的字典列表形式
python 复制代码
import base64
from langchain.chat_models import init_chat_model
from langchain.messages import HumanMessage


def encode_image(img_path, img_type='jpeg'):
	"""将一张本地图片转换成 Base64 编码的 Data URI 字符串,方便在文本中嵌入图片数据"""
	with open(img_path, "rb") as img_file:
		return f"data:image/{img_type};base64,{base64.b64encode(img_file.read()).decode("utf-8")}"

# 图像路径
img_path = "image_test.png"
# 获取图像base64编码字符串
base64_image = encode_image(img_path)

response = model.invoke(
	[
		HumanMessage(
			content=[
				{
					'type': 'text', 
					'text': '这张图里有什么?'
				},
				{
					'type': 'image_url',
					"image_url": base64_image,
				}
			]
		)
	]
)
print(response.content)

1.4 消息属性 content_blocks(解决各供应商 API 格式差异问题)

content_blocks是消息对象(BaseMessage)的一项重大升级。它的核心目标是提供一种跨模型供应商、标准化的多模态数据结构
在处理图片、音频、甚至是模型生成的"思维链(Reasoning)"内容时,不同供应商(OpenAI,Anthropic, Google 等)的 API 格式各异,导致开发者需要写大量的适配代码。 content_blocks 的出现终结了这种混乱
在 LangChain 1.2 版本中,消息对象的 content 属性依然存在(为了向前兼容),但新增了content_blocks 属性,可以将 content 解析为标准、类型安全的表示。

  • 数据结构:它是一个 listTypedDict 。
  • 统一格式:每个 block 都有一个 type 字段,用于区分内容类型。
  • 支持类型:包括 text (文本)、 image (图片)、 audio (音频)、 video (视频)、tool_call (工具调用)以及 reasoning (推理/思维链)。
    对于复杂的对话(带图片或工具结果),建议使用 content_blocks 列表形式构建 HumanMessage 或 AIMessage 。

借助 content_blocks ,我们可以用一套标准代码,无缝地在不同厂商的模型之间切换。

python 复制代码
response = model.invoke(
	[
		HumanMessage(
			content_blocks=[
				{
					'type': 'text', 
					'text': '这张图里有什么?'
				},
				{
					'type': 'image',
					'base64': base64_image,
					'mime_type': 'image/png',
				}
			]
		)
	]
)

二、提示词模板

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

python 复制代码
# 字符串拼接
topic = "Python"
difficulty = "初学者"

# 难以维护,容易出错
prompt_str = f"你是一个{difficulty}级别的编程导师。请用简单易懂的语言解释{topic}。"

response = model.invoke(prompt_str)
print(f"AI 回复:{response.content}...\n")

使用PromptTemplate方式

python 复制代码
from langchain.prompts import PromptTemplate


template = PromptTemplate.from_template(
	"你是一个{difficulty}级别的编程导师。请用简单易懂的语言解释{topic}。"
)

# 使用模板生成提示词
prompt1 = template.format(difficulty="初学者", topic="Python")
prompt2 = template.format(difficulty="入门", topic="C++")

response1 = model.invoke(prompt1)
print(f"AI 回复:{response1.content}...\n")

response2 = model.invoke(prompt2)
print(f"AI 回复:{response2.content}...\n")

使用ChatPromptTemplate方式

python 复制代码
from langchain_core.prompts import ChatPromptTemplate

prompt_template = ChatPromptTemplate([
	("system", "你是一个AI开发工程师. 你的名字是 {name}."),
	("human", "{user_input}")
])

#调用format()方法,返回字符串
prompt = prompt_template.invoke({"name":"小谷AI", "user_input":"你能帮我做什么?"})
print(prompt)

提示词机制演进

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

  1. 旧时代:LLM + PromptTemplate (输入与输出均为字符串)
    ① 模型接口:对应于 LangChain 中的 LLM 类,主要面向早期的文本补全模型 。
    ② 工作方式:模型接受一个单一的字符串作为输人,基于此预测并生成后续的文本内容(文本补全)。
    ③ Prompt 工具:核心工具是 PromptTemplate 。它的职责是接收一组变量,并通过模板渲染,最终输出一个完整的字符串。
    ④ 局限性:当我们需要用这种方式模拟多轮聊天时,开发者必须在字符串中手动拼接和伪造对话角色。

这种方式不仅导致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 应用的首选工具

2.1 ChatPromptTemplate 的使用

在LangChain 1.0中,ChatPromptTemplate 是用于生成消息列表的核心组件。ChatPromptTemplate是创建聊天消息列表的提示模板。它比普通 PromptTemplate 更适合处理多角色、多轮次的对话场景。支持 System / Human / AI 等不同角色的消息模板。

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

两种实例化方式 :ChatPromptTemplate 可以通过初始化方法或 from_messages 方法来实例化提示词模板。实例化时需要传入 messages参数 。常见类型是:tuple构成的列表,参数类型

  • 方式1(推荐) :调用from_messages()。该方法允许传入一个由元组(Tuple)构成的列表,列表中的每一个元组都代表一条具有特定角色的消息。
python 复制代码
# 导入相关依赖
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":"你叫什么名字?"})
# 打印格式化后的聊天提示词模版内容
print(prompt)
  • 方式2:使用实例初始化方法
python 复制代码
from langchain_core.prompts import ChatPromptTemplate

# 参数类型这里使用的是tuple构成的list
prompt_template = ChatPromptTemplate([
	# 字符串 role + 字符串 content
	("system", "你是一个AI开发工程师. 你的名字是 {name}."),
	("human", "你能开发哪些AI应用?"),
	("ai", "我能开发很多AI应用, 比如聊天机器人, 图像识别, 自然语言处理等."),
	("human", "{user_input}")
])

#调用invoke()方法,返回ChatPromptValue
prompt = prompt_template.invoke({"name":"小明", "user_input":"你能帮我做什么?"})
print(prompt)

2.2 模板调用方式

  • 方式一 :使用 invoke(),返回ChatPromptValue
python 复制代码
from langchain_core.prompts import ChatPromptTemplate

#参数类型这里使用的是tuple构成的list
prompt_template = ChatPromptTemplate([
	# 字符串 role + 字符串 content
	("system", "你是一个AI开发工程师. 你的名字是 {name}."),
	("human", "你能开发哪些AI应用?"),
	("ai", "我能开发很多AI应用, 比如聊天机器人, 图像识别, 自然语言处理等."),
	("human", "{user_input}")
])

prompt = prompt_template.invoke({"name":"小明", "user_input":"你能帮我做什么?"})
print(type(prompt))
print(prompt)
print(len(prompt.messages))
  • 方式二 :使用format(),返回字符串
python 复制代码
from langchain_core.prompts import ChatPromptTemplate

#参数类型这里使用的是tuple构成的list
prompt_template = ChatPromptTemplate([
	# 字符串 role + 字符串 content
	("system", "你是一个AI开发工程师. 你的名字是 {name}."),
	("human", "你能开发哪些AI应用?"),
	("ai", "我能开发很多AI应用, 比如聊天机器人, 图像识别, 自然语言处理等."),
	("human", "{user_input}")
])

#方式1:调用format()方法,返回字符串
prompt = prompt_template.format(name="小明", user_input="你能帮我做什么?")
print(type(prompt))
print(prompt)

方式三 :使用format_messages(),返回消息列表

python 复制代码
from langchain_core.prompts import ChatPromptTemplate

prompt_template = ChatPromptTemplate([
	("system", "你是一个AI开发工程师. 你的名字是 {name}."),
	("human", "你能开发哪些AI应用?"),
	("ai", "我能开发很多AI应用, 比如聊天机器人, 图像识别, 自然语言处理等."),
	("human", "{user_input}")
])

#调用format_messages()方法,返回消息列表
prompt = prompt_template.format_messages(name="小谷AI", user_input="你能帮我做什么?")
print(type(prompt))
print(prompt)

结合LLM调用

python 复制代码
from langchain_core.prompts import ChatPromptTemplate
from langchain.chat_models import init_chat_model

######1、提供大模型######### 略 参考文章开头

######2、提供提示词#########
chat_prompt = ChatPromptTemplate.from_messages([
	("system", "你是一个数学家,你可以计算任何算式"),
	("human", "{text}"),
])

# 输入提示
prompt_value = chat_prompt.invoke({
	"text":"1 + 1 = ?"
})

######3、结合提示词,调用大模型#########
# 得到模型的输出
output = model.invoke(prompt_value)
# 打印输出内容
print(output.content)

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

前面讲了 ChatPromptTemplate 的两种创建方式。我们看到不管使用实例初始化方法,还是使用 from_messages(),参数类型都是列表类型 。列表中的元素可以是多种类型,前面我们主要测试了元组类型
结论:参数是列表类型,列表的元素可以是字符串、字典、字符串构成的元组、消息类型、提示词模板类型、消息提示词模板类型等

  • 类型一 :str列表类型,列表参数格式是str类型(不推荐),因为默认角色都是human
python 复制代码
#1.导入相关依赖
from langchain_core.prompts import ChatPromptTemplate

# 2.定义聊天提示词模版
chat_template = ChatPromptTemplate.from_messages([
	"Hello, {name}!" # 等价于 ("human", "Hello, {name}!")
])

# 3. 使用invoke执行
messages = chat_template.invoke({"name":"张三"})
# 4.打印格式化后的聊天提示词模版内容
print(messages)
  • 类型二 :tuple列表类型,列表参数格式是元组类型
python 复制代码
# 示例: 元组形式的消息
prompt = ChatPromptTemplate.from_messages([
	("system", "你的名字是{role}."),
	("human", "很高兴认识你"),
])
print(prompt.invoke({"role":"张三"}))
  • 类型三 :dict列表类型,列表参数格式是dict类型
python 复制代码
# 示例: 字典形式的消息
prompt = ChatPromptTemplate.from_messages([
	{"role": "system", "content": "你的名字是{role}."},
	{"role": "human", "content":"很高兴认识你"},
])
print(prompt.invoke({"role":"张三"}))
  • 类型四 :Message列表类型(注:在XxxMessage中不能有占位符)
python 复制代码
from langchain_core.messages import SystemMessage,HumanMessage

chat_prompt_template = ChatPromptTemplate.from_messages([
	SystemMessage(content="我是一个贴心的智能助手"),
	HumanMessage(content="你好")    # 不能使用类似 {word} 占位符,不能正确读取 word 替换
])

messages = chat_prompt_template.invoke({})
print(messages)
print(type(messages))
  • 类型五 :MessagePromptTemplate列表类型。LangChain提供不同类型的MessagePromptTemplate。最常用的是SystemMessagePromptTemplate 、HumanMessagePromptTemplate 和AIMessagePromptTemplate ,分别创建系统消息、人工消息和AI消息。

基本概念:HumanMessagePromptTemplate,专用于生成用户消息(HumanMessage) 的模板类

  • 模板化 :支持使用变量占位符,可以在运行时填充具体值
  • 格式化 :能够将模板与输入变量结合生成最终的聊天消息
  • 输出类型 :生成 HumanMessage 对象( content + role="human" )
  • 设计目的 :简化用户输入消息的模板化构造,避免重复定义角色
    SystemMessagePromptTemplate、AIMessagePromptTemplate类似,不再赘述
python 复制代码
# 导入聊天消息类模板
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":"1 + 1 = ?"})
print(formatted_messages)
  • 类型六 :BaseChatPromptTemplate列表类型。使用 BaseChatPromptTemplate,可以理解为ChatPromptTemplate里嵌套了ChatPromptTemplate。
python 复制代码
from langchain_core.prompts import ChatPromptTemplate

# 使用 BaseChatPromptTemplate(嵌套的 ChatPromptTemplate)
nested_prompt_template1 = ChatPromptTemplate.from_messages([
	("system", "我是一个人工智能助手,我的名字叫{name}")
])
nested_prompt_template2 = ChatPromptTemplate.from_messages([
	("human", "很高兴认识你,我的问题是{question}")
])
prompt_template = ChatPromptTemplate.from_messages([
	nested_prompt_template1, nested_prompt_template2
])

prompt_template.invoke({"name":"张三","question":"你是谁?"})  # 无参数时填入空字典  invoke({})

2.4 高级特性

2.4.1 partial(部分变量预填充)

预填充某些固定不变的变量,创建模板的变体。使用场景:

  • 某些变量在所有调用中都相同
  • 需要为不同用户/场景创建定制模板
    为不同部门创建专用模板
python 复制代码
# 原始模板
base_template = ChatPromptTemplate.from_messages([
	("system", "你是{department}的{role}"),
	("user", "{task}")
])

# 部分填充
# IT 部门
it_template = base_template.partial(
	department="IT 部门",
	role="技术支持"
)
# 销售部门
sales_template = base_template.partial(
	department="销售部门",
	role="销售顾问"
)

# 现在只需要提供 task
messages1 = it_template.invoke({"task":"出现了什么bug问题单"})
print(messages1)
messages2 = sales_template.invoke({"task":"为什么每年年底汽车会促销"})
print(messages2)

2.4.2 消息占位符

当你不确定消息提示模板使用什么角色,或者希望在格式化过程中插入消息列表时,这就需要使用消息占位符,负责在特定位置添加消息列表。在多轮对话系统存储历史消息以及Agent的中间步骤处理此功能非常有用。

  • 方式一:JSON形式
python 复制代码
from langchain_core.prompts import ChatPromptTemplate

template = ChatPromptTemplate.from_messages(
	[
		("system", "你是一个有用的AI助手"),
		("placeholder", "{conversation}"),
	]
)

prompt_value = template.invoke(
	{
		"conversation": [
			("human", "你好!"),
			("ai", "今天我能帮你做什么?"),
			("human", "你能给我做一个冰激凌吗?"),
			("ai", "抱歉,我没有这样的能力"),
		]
	}
)
print(prompt_value)
  • 方式二 :MessagesPlaceholder 对象形式
python 复制代码
from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder
from langchain_core.messages import HumanMessage

prompt_template = ChatPromptTemplate.from_messages([
	("system", "You are a helpful assistant"),
	MessagesPlaceholder("msgs")
])

prompt_template.invoke({"msgs": [HumanMessage(content="hi!")]})
# prompt_template.format_messages(msgs=[HumanMessage(content="hi!")])

存储对话历史内容

python 复制代码
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呢?"
	}
)

2.4.3 可复用模板库

在实际项目中,建议创建模板库。
templates.py 文件声明如下

python 复制代码
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```")
	])
	
	SUMMARIZER = ChatPromptTemplate.from_messages([
		("system", "你是内容摘要专家"),
		("user", "将以下内容总结为{num}个要点:\n{content}")
	])
	
	TUTOR = ChatPromptTemplate.from_messages([
		("system", "你是{subject}导师,学生水平:{level}"),
		("user", "{question}")
	])

其它文件中使用:

python 复制代码
from templates import PromptLibrary

messages = PromptLibrary.TRANSLATOR.format_messages(
	source_lang="英语",
	target_lang="中文",
	text="Hello World"
)

2.4.4 模板组合

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

  • 方法一:字符串组合
python 复制代码
# 定义可复用的部分
role_part = "你是一个{domain}专家。"
style_part = "回答风格:{style}。"
constraint_part = "限制:{constraint}。"

# 组合
full_system = role_part + style_part + constraint_part
template = ChatPromptTemplate.from_messages([
	("system", full_system),
	("user", "{question}")
])
  • 方法二:使用 + 运算符
python 复制代码
template1 = ChatPromptTemplate.from_messages([
	("system", "你是助手")
])
template2 = ChatPromptTemplate.from_messages([
	("user", "{input}")
])

# 组合(LangChain 1.0 支持)
combined = template1 + template2
相关推荐
CoderYanger30 分钟前
Java EE 进阶:11. SpringBoot 统一功能处理(第三弹):统一数据返回格式+统一异常处理
java·数据库·spring boot·后端·spring·java-ee·mybatis
飞奔的瓜牛36 分钟前
运维工程师 Redis 日常巡检清单与实战注意事项
运维·数据库·redis
龙腾AI白云1 小时前
视觉运动控制与灵巧抓取:具身智能手眼协调的学习
大数据·数据库·人工智能·机器学习·pygame
宝桥南山10 小时前
Visual Studio - 记录一个Visual Studio 2026(Insiders)的更新问题
windows·microsoft·微软·.net·.netcore·visual studio
多弗朗皮卡丘10 小时前
MySQL表的约束
数据库·mysql
Flynn Liang14 小时前
AI Agent Redis 生产踩坑实录:13 类故障的根因、复现与调优
数据库·人工智能·redis·缓存·ai agent·故障分析
SelectDB16 小时前
开源日志平台怎么选?ELK、Loki、ClickHouse、Apache Doris 四大方案对比与选型指南
数据库
SelectDB16 小时前
ELK 磁盘空间不足怎么办?Elasticsearch 存储膨胀原因、排查步骤与 3 种降本方案
数据库
满小满16 小时前
为什么我先 ANALYZE,而不是先加索引
数据库·dba