「LangChain」ChatPromptTemplate学习笔记

使用说明

ChatPromptTemplate是创建聊天消息列表的模版,比PromptTemplate更适合处理多角色、多轮次的对话场景

特点

  • 支持System/AI/Human等不同角色的消息模板
  • 历史对话的维护

参数类型

参数:

  • role-角色
  • content-消息内容

列表参数格式是tuple类型(role :str content :str 组合最常用)

元组的格式为:(role: str | type, content: str | list[dict] | list[object])

其中role是:字符串(常用:"system"、"human"、"ai")

实例化方法

1.构造方法
python 复制代码
from langchain_core.prompts import ChatPromptTemplate

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


# <class 'langchain_core.prompt_values.ChatPromptValue'>
print(prompt.invoke({"name":"小智", "user_input":"介绍一下自然语言处理"}))
print(type(prompt.invoke({"name":"小智", "user_input":"介绍一下自然语言处理"})))

//输出结果
messages=[SystemMessage(content='你是一个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={})]
<class 'langchain_core.prompt_values.ChatPromptValue'>
2.调用from_messages()
python 复制代码
from langchain_core.prompts import ChatPromptTemplate

promptMessage = ChatPromptTemplate.from_messages([
     ("system", "你是一个AI开发工程师. 你的名字是 {name}."),
    ("human", "你能开发哪些AI应用?"),
    ("ai", "我能开发很多AI应用, 比如聊天机器人, 图像识别, 自然语言处理等."),
    ("human", "{user_input}")
])
promptMsg = promptMessage.invoke(input={"name": "小智", "user_input": "描述一下图像识别技术"})
print(promptMsg)
print(type(promptMsg))

//输出
messages=[SystemMessage(content='你是一个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={})]
<class 'langchain_core.prompt_values.ChatPromptValue'>

上面两种实例化方法经过invoke()方法调用均获得ChatPromptValue类型的实例,但又是传给AI的希望是个对话历史,希望以消息列表的方法传递给AI,所以创建好Template后,可以使用不同的方法获取不同的数据类型,(当然可以通过方法转换获取不同的数据类型),下面就讲一下四个常用的模板调用的方法

模板调用的四种方式

  • 方式1:invoke() -> ChatPromptValue
python 复制代码
from langchain_core.prompts import ChatPromptTemplate

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

# <class 'langchain_core.prompt_values.ChatPromptValue'>
print(prompt.invoke({"name": "小智", "user_input": "介绍一下自然语言处理"}))
print(type(prompt.invoke({"name": "小智", "user_input": "介绍一下自然语言处理"})))

//输出
messages=[SystemMessage(content='你是一个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={})]
<class 'langchain_core.prompt_values.ChatPromptValue'>
  • 方式2:format() -> str
python 复制代码
from langchain_core.prompts import ChatPromptTemplate

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

# <class 'str'>
print(prompt.format(name="小智", user_input="测试测试"))
print(type(prompt.format(name="小智", user_input="测试测试")))

//输出
System: 你是一个AI开发工程师. 你的名字是 小智.
Human: 你能开发哪些AI应用?
AI: 我能开发很多AI应用, 比如聊天机器人, 图像识别, 自然语言处理等.
Human: 测试测试
<class 'str'>
  • 方式3:format_messages() -> List<BaseMessage>
python 复制代码
from langchain_core.prompts import ChatPromptTemplate

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

# <class 'list'>
print(prompt.format_messages(name="小智", user_input="测试format_messages方法"))
print(type(prompt.format_messages(name="小智", user_input="测试format_messages方法")))

//输出
[SystemMessage(content='你是一个AI开发工程师. 你的名字是 小智.', additional_kwargs={}, response_metadata={}), HumanMessage(content='你能开发哪些AI应用?', additional_kwargs={}, response_metadata={}), AIMessage(content='我能开发很多AI应用, 比如聊天机器人, 图像识别, 自然语言处理等.', additional_kwargs={}, response_metadata={}), HumanMessage(content='测试format_messages方法', additional_kwargs={}, response_metadata={})]
<class 'list'>
  • 方式4:format_prompt() -> ChatPromptValue
python 复制代码
from langchain_core.prompts import ChatPromptTemplate

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

# <class 'langchain_core.prompt_values.ChatPromptValue'>
print(prompt.format_prompt(name="小智", user_input="测试format_prompt方法"))
print(type(prompt.format_prompt(name="小智", user_input="测试format_prompt方法")))

//输出
messages=[SystemMessage(content='你是一个AI开发工程师. 你的名字是 小智.', additional_kwargs={}, response_metadata={}), HumanMessage(content='你能开发哪些AI应用?', additional_kwargs={}, response_metadata={}), AIMessage(content='我能开发很多AI应用, 比如聊天机器人, 图像识别, 自然语言处理等.', additional_kwargs={}, response_metadata={}), HumanMessage(content='测试format_prompt方法', additional_kwargs={}, response_metadata={})]
<class 'langchain_core.prompt_values.ChatPromptValue'>

结论:给占位符赋值,针对于ChatPromptTemplate,推荐使用 format_messages() 方法,返回消息列表。

丰富的实例化参数类型

前面讲了ChatPromptTemplate的两种创建方式。我们看到不管使用构造方法,还是使用from_messages(),参数类型都是列表类型。其实列表中的元素可以是多种类型,前面我们只是主要测试了元组类型。

接下来举几个例子吧

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

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

# 3.1格式化聊天提示词模版中的变量(自己提供的)
messages = chat_template.format_messages(name="小谷AI")

# 3.2 使用invoke执行
messages=chat_template.invoke({"name":"小谷AI"})
# 4.打印格式化后的聊天提示词模版内容
print(messages)
  • 类型2:dict类型
python 复制代码
# 示例: 字典形式的消息
prompt = ChatPromptTemplate.from_messages([
{"role": "system", "content": "你是一个{role}."},
{"role": "human", "content": ["复杂内容", {"type": "text"}]},
])
print(prompt.format_messages(role="教师"))
  • 类型3:BaseMessagePromptTemplate类型 -> List<BaseMessage>

使用LangChain中常见的SystemMessagePromptTemplate、HumamMessagePromptTemplate、AIMessagePromptTemplate,分别创建系统消息、人工消息和AI消息,它们是ChatMessagePromptTemplate的特定角色子类。

python 复制代码
from langchain_core.prompts import SystemMessagePromptTemplate, HumanMessagePromptTemplate, \
    ChatMessagePromptTemplate  # 1.导入先关包

# 用角色MessagePromptTemplate
system_template = "你是一个{role}专家"
system_message_prompt = SystemMessagePromptTemplate.from_template(system_template)
human_template = "给我解释{concept},用浅显易懂的语言"
human_message_prompt = HumanMessagePromptTemplate.from_template(human_template)

chatMessage = ChatPromptTemplate.from_messages([
    system_message_prompt,
    human_message_prompt
])
print(chatMessage.format_messages(role="医生", concept="口腔溃疡的生成"))
print(type(chatMessage.format_messages(role="医生", concept="口腔溃疡的生成")))

//输出
[SystemMessage(content='你是一个医生专家', additional_kwargs={}, response_metadata={}), HumanMessage(content='给我解释口腔溃疡的生成,用浅显易懂的语言', additional_kwargs={}, response_metadata={})]
<class 'list'>
  • 类型4:ChatMessagePromptTemplate类型 -> List<BaseMessage>

ChatMessagePromptTemplate,用于构建聊天消息的模板。它允许你创建可重用的消息模板,这些模板可以动态地插入变量值来生成最终的聊天消息

1.角色指定 :可以为每条消息指定角色(如 "system"、"human"、"ai") 等,角色灵活。

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

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

python 复制代码
from langchain_core.prompts import ChatMessagePromptTemplate  # 1.导入先关包

# 使用ChatMessagePromptTemplate
customChatMessageTemplate = ChatMessagePromptTemplate.from_template(
    role="医生",
    template=human_template
)
print(customChatMessageTemplate.format_messages(concept="口腔溃疡的生成"))
print(type(customChatMessageTemplate.format_messages(concept="口腔溃疡的生成")))
// 输出
[ChatMessage(content='给我解释口腔溃疡的生成,用浅显易懂的语言', additional_kwargs={}, response_metadata={}, role='医生')]
<class 'list'>

提示:在编写ChatMessagePromptTemplate时发现总会把from_template()和format_message()方法混淆不清,所以在此进行强调两者具体用途:

from_template():该方法主要用来创建MessageTemplate消息模板;

format_message():该方法主要用来填充消息模板中的变量值来生成对应的Message实例

插入消息列表:MessagesPlaceholder的使用

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

举例:

python 复制代码
# 1.导入相关包
from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder, SystemMessagePromptTemplate, HumanMessagePromptTemplate
from langchain_core.messages.system import SystemMessage

# 2.定义消息模板
prompt = ChatPromptTemplate.from_messages([
    SystemMessagePromptTemplate.from_template("你是{role}"),
    MessagesPlaceholder(variable_name="intermediate_steps"),
    HumanMessagePromptTemplate.from_template("{query}")
])

# 3.定义消息对象
intermediate_steps = [
    SystemMessage(name="search", content="杭州:晴,25℃")
]

# 4.格式化聊天消息提示词模板
promptMessage = prompt.format_messages(
    role="天气预报员",
    intermediate_steps=intermediate_steps,
    query="今天天气如何?"
)

print(promptMessage)
//输出
[SystemMessage(content='你是天气预报员', additional_kwargs={}, response_metadata={}), SystemMessage(content='杭州:晴,25℃', additional_kwargs={}, response_metadata={}, name='search'), HumanMessage(content='今天天气如何?', additional_kwargs={}, response_metadata={})]

个人感觉这个MessagePlaceHolder后续还可以用于一些需要AI借助其他工具,或者网络查询获取相关信息时的占位符,获取到专业信息后再进行填入传递给AI,用于更加专业性的信息处理场景

相关推荐
Hello.Reader2 小时前
Flink ML OneHotEncoder 把类别索引变成稀疏 one-hot 向量
python·机器学习·flink
阿正的梦工坊2 小时前
WebArena:一个真实的网页环境,用于构建更强大的自主智能体
人工智能·深度学习·机器学习·大模型·llm
薛不痒2 小时前
机器学习算法之SVM
算法·机器学习·支持向量机
qijiabao41132 小时前
深度学习|可变形卷积DCNv3编译安装
人工智能·python·深度学习·机器学习·cuda
小鸡吃米…2 小时前
机器学习所需技能
人工智能·机器学习
淡酒交魂3 小时前
「LangChain学习」ChatPromptTemplate学习笔记
机器学习·langchain
Biehmltym3 小时前
【AI】04AI Aent:十分钟跑通LangGraph项目:调用llm+agent开发+langSmith使用
java·人工智能·langchain·langgraph
大模型真好玩4 小时前
LangGraph智能体开发设计模式(二)——协调器-工作者模式、评估器-优化器模式
人工智能·langchain·agent
Lauren_Blueblue4 小时前
【OPEN MLSYS】机器学习系统:设计和实现-基础篇
神经网络·机器学习·框架·机器学习原理