ChatPromptTemplate 应用场景用于生成与LLM进行对话式交互的提示。用于构建聊天机器人、进行持续的对话管理或处理连续的文本交互任务。它特别适合需要考虑上下文连续性和历史对话信息的场景。
它扩展了 PromptTemplate 的功能,加入了对话历史的管理和引用能力。这意味着它可以在生成提示时考虑之前的交互内容,使得生成的文本能够更自然地融入到对话流程中。
如下为OpenAI 的 Chat Model 中的各种消息角色。
import openaiopenai.ChatCompletion.create(model="gpt-3.5-turbo",messages=[{"role": "system", "content": "You are a helpful assistant."},{"role": "user", "content": "Who won the world series in 2020?"},{"role": "assistant", "content": "The Los Angeles Dodgers won the World Series in 2020."},{"role": "user", "content": "Where was it played?"}])
如下为OpenAI 对传输到 gpt-3.5-turbo 和 GPT-4 的 messsage 格式说明。
消息必须是消息对象的数组,其中每个对象都有一个角色(系统、用户或助理)和内容。对话可以短至一条消息,也可以来回多次。
通常,对话首先由系统消息格式化,然后是交替的用户消息和助理消息。
系统消息有助于设置助手的行为。例如,你可以修改助手的个性或提供有关其在整个对话过程中应如何表现的具体说明。但请注意,系统消息是可选的,并且没有系统消息的模型的行为可能类似于使用通用消息,例如“你是一个有用的助手”。
用户消息提供助理响应的请求或评论。
助理消息存储以前的助理响应,但也可以由你编写以给出所需行为的示例。
ChatPromptTemplate 这一些列的模版,就是根据如上OpenAI对聊天模型的规定而设计的。
主要方法概览
| 方法名称 | 介绍 | 返回类型 | 参数介绍 |
|---|---|---|---|
| init | 构造方法 | ChatPromptTemplate | - inputvariables (List[str], 必需):这是一个字符串列表,指定了模板中期望的变量名。这些变量是在模板字符串中被格式化时需要提供值的占位符。 - input_types (Dict[str, Any], 可选): 一个字典,映射模板中每个变量的名称到其期望的类型。这有助于在处理模板之前验证输入数据的类型。 - messages (_List[MessageLike], 必需):由消息提示模板或消息组成的消息列表。 - partial_variables (Mapping[str, Union[str, Callable[[], str]]], 可选):一个映射,为模板中的一些变量提供部分或默认值。这些值可以是字符串或返回字符串的函数。在此处赋值的变量就不需要在input_variables中体现了 - output_parser (Optional[BaseOutputParser], 可选, 默认为None):一个输出解析器对象,用于解析调用语言模型后返回的输出。这允许对模型输出进行自定义处理。 - validate_template (bool, 可选, 默认为False):指定是否在实例化时验证模板字符串。启用验证可以确保模板字符串符合预期的格式,但可能会增加额外的性能开销。 |
| from_messages | 类方法,从多种消息格式创建聊天提示模板。 | ChatPromptTemplate | messages (Sequence[Union[BaseMessagePromptTemplate, BaseMessage, BaseChatPromptTemplate, Tuple[str, str], Tuple[Type, str], str]], 必需): 消息列表,列表的每一项可以是BaseMessagePromptTemplate, BaseMessage, 元组(消息类型, 模板), 字符串等。 |
| from_template | 类方法,从单一的模板字符串创建聊天提示模板。 | ChatPromptTemplate | template (str, 必需): 一个包含占位符的字符串,属于human消息类型,占位符将在调用format方法时被实际的值替换。 |
| format | 将聊天模板格式化为字符串。 | str | kwargs (Any, 必需): 给提示模板中的参数赋值。 |
| format_messages | 将聊天模板格式化为最终消息列表。 | List[BaseMessage] | - kwargs (Any, 必需):给提示模板中的参数赋值。 |
| format_prompt | 格式化提示,返回一个PromptValue。 | PromptValue | - kwargs (Any, 必需): 给提示模板中的参数赋值。 |
| partial | 创建一个新的ChatPromptTemplate实例,为部分变量先赋值。 | ChatPromptTemplate | - kwargs (Union[str, Callable[[], str]], 必需): 给提示模板中的参数赋值。 |
使用构造方法创建聊天提示
- 利用诸如SystemMessage角色消息创建聊天模版
from langchain.schema import AIMessage, HumanMessage, SystemMessage# SystemMessage、HumanMessage、AIMessage# 这种类型组成的message,content赋值只能是字符串,不能是模版messages = [SystemMessage(content='秋水札记,定位于 LangChain AI 编程推广,分享 LangChain 商业与技术。'),HumanMessage(content='帮我列出几个AI商业案例?')]#构造方法创建提示模版prompt = ChatPromptTemplate(messages=messages)# 格式化模板formatted_prompt_message = prompt.format_messages()print("format_messages()执行后返回List[BaseMessage] 对象:")print(formatted_prompt_message)print("\n每一个BaseMessage 对象:")for msg in formatted_prompt_message:print(msg.content)formatted_prompt = prompt.format()print("\nformat()执行后返回字符串:")print(formatted_prompt)formatted_format_prompt = prompt.format_prompt()print("\nformat_prompt()执行后返回PromptValue 对象:")print(formatted_format_prompt)'''代码执行后输出内容如下:format_messages()执行后返回List[BaseMessage] 对象:[SystemMessage(content='秋水札记,定位于 LangChain AI 编程推广,分享 LangChain 商业与技术。'), HumanMessage(content='帮我列出几个AI商业案例?')]每一个BaseMessage 对象:秋水札记,定位于 LangChain AI 编程推广,分享 LangChain 商业与技术。帮我列出几个AI商业案例?format()执行后返回字符串:System: 秋水札记,定位于 LangChain AI 编程推广,分享 LangChain 商业与技术。Human: 帮我列出几个AI商业案例?format_prompt()执行后返回PromptValue 对象:messages=[SystemMessage(content='秋水札记,定位于 LangChain AI 编程推广,分享 LangChain 商业与技术。'), HumanMessage(content='帮我列出几个AI商业案例?')]'''
使用 SystemMessage、HumanMessage、AIMessage 角色消息创建聊天提示时,在具体的提示字符串中不能设置变量,如果需要设置变量则需要将这三种消息类型换成消息模版SystemMessagePromptTemplate、HumanMessagePromptTemplate、AIMessagePromptTemplate。
SystemMessage 对应的是前面讲的ChatGPT三种主要角色中的SYSTEM。
HumanMessage 对应的是USER,就是用户输入的问题内容。
AIMessage 对应的是ASSISTANT,就是AI大模型的回复内容。
SystemMessage、HumanMessage、AIMessage角色消息,不是提示模版,不支持在提示中设置变量。
- 利用诸如SystemMessagePromptTemplate角色消息模版创建聊天模版
# 定义变量brand = "秋水札记"product_promotion = "LangChain"business_case = "AI商业案例"# 使用构造函数创建提示模板# 这里的 messages 列表直接使用了字符串格式的消息,# 但同样可以根据需要扩展为更复杂的消息提示模板messages = [SystemMessagePromptTemplate(prompt = PromptTemplate(input_variables=[],template='{brand},定位于 LangChain AI 编程推广,分享 {product_promotion} 商业与技术。')),HumanMessagePromptTemplate(prompt = PromptTemplate(input_variables=[],template='帮我列出几个{business_case}'))]prompt = ChatPromptTemplate(input_variables=[], messages=messages)# 格式化并输出模板formatted_prompt = prompt.format_messages(brand=brand, product_promotion=product_promotion, business_case=business_case)print("format_messages()执行后返回List[BaseMessage] 对象:")print(formatted_prompt)'''代码执行后输出内容如下:format_messages()执行后返回List[BaseMessage] 对象:[SystemMessage(content='秋水札记,定位于 LangChain AI 编程推广,分享 LangChain 商业与技术。'), HumanMessage(content='帮我列出几个AI商业案例?')]'''
使用SystemMessagePromptTemplate、HumanMessagePromptTemplate、AIMessagePromptTemplate创建聊天提示,这三个角色提示模版的构造方法的重要参数就是prompt,它要求传入PromptTemplate对像。
使用from_messages创建聊天提示
template = ChatPromptTemplate.from_messages([("system", "{brand},定位于 LangChain AI 编程推广,分享 {product_promotion} 商业与技术。"),HumanMessagePromptTemplate(prompt = PromptTemplate(input_variables=[],template='帮我列出几个{business_case}')),AIMessage(content='语音助手、聊天机器人和对话式AI。')])messages = template.format_messages(brand="秋水札记",product_promotion="LangChain",business_case="AI商业案例")print(messages)'''代码执行后输出内容如下:[SystemMessage(content='秋水札记,定位于 LangChain AI 编程推广,分享 LangChain 商业与技术。'), HumanMessage(content='帮我列出几个AI商业案例'), AIMessage(content='语音助手、聊天机器人和对话式AI')]'''
这种创建聊天提示的方式,在from_messages方法中参数值传入可以是多种形式,可以是一个包含 tuple 元组的 list 列表,也可以是AIMessage对象,也可以是HumanMessagePromptTemplate对象,可以根据具体使用情况灵活使用。
1、from_messages方法中参数值传入可以是多种形式,可以是一个包含 tuple 元组的 list 列表,也可以是AIMessage对象,也可以是HumanMessagePromptTemplate对象
2、如果采用from_template方法创建聊天提示,则传入的模版对应的角色只能是human。
3、在类ChatPromptTemplate也存在partial方法,用法与类PromptTemplate中一样。
ChatPromptTemplate相关类介绍
创建聊天提示的主要是ChatPromptTemplate类,聊天提示除了可以用字符串创建以外,绝大多数情况下会用SystemMessagePromptTemplate、HumanMessagePromptTemplate、AIMessagePromptTemplate三个消息模版类组合创建,或者用角色消息SystemMessage、HumanMessage、AIMessage三个消息类组合创建。
消息模版类的操作使用与PromptTemplate基本一样。
