ChatPromptTemplate 应用场景用于生成与LLM进行对话式交互的提示。用于构建聊天机器人、进行持续的对话管理或处理连续的文本交互任务。它特别适合需要考虑上下文连续性和历史对话信息的场景。
它扩展了 PromptTemplate 的功能,加入了对话历史的管理和引用能力。这意味着它可以在生成提示时考虑之前的交互内容,使得生成的文本能够更自然地融入到对话流程中。
如下为OpenAI 的 Chat Model 中的各种消息角色。

  1. import openai
  2. openai.ChatCompletion.create(
  3. model="gpt-3.5-turbo",
  4. messages=[
  5. {"role": "system", "content": "You are a helpful assistant."},
  6. {"role": "user", "content": "Who won the world series in 2020?"},
  7. {"role": "assistant", "content": "The Los Angeles Dodgers won the World Series in 2020."},
  8. {"role": "user", "content": "Where was it played?"}
  9. ]
  10. )

如下为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角色消息创建聊天模版
  1. from langchain.schema import AIMessage, HumanMessage, SystemMessage
  2. # SystemMessage、HumanMessage、AIMessage
  3. # 这种类型组成的message,content赋值只能是字符串,不能是模版
  4. messages = [
  5. SystemMessage(content='秋水札记,定位于 LangChain AI 编程推广,分享 LangChain 商业与技术。'),
  6. HumanMessage(content='帮我列出几个AI商业案例?')
  7. ]
  8. #构造方法创建提示模版
  9. prompt = ChatPromptTemplate(messages=messages)
  10. # 格式化模板
  11. formatted_prompt_message = prompt.format_messages()
  12. print("format_messages()执行后返回List[BaseMessage] 对象:")
  13. print(formatted_prompt_message)
  14. print("\n每一个BaseMessage 对象:")
  15. for msg in formatted_prompt_message:
  16. print(msg.content)
  17. formatted_prompt = prompt.format()
  18. print("\nformat()执行后返回字符串:")
  19. print(formatted_prompt)
  20. formatted_format_prompt = prompt.format_prompt()
  21. print("\nformat_prompt()执行后返回PromptValue 对象:")
  22. print(formatted_format_prompt)
  23. '''
  24. 代码执行后输出内容如下:
  25. format_messages()执行后返回List[BaseMessage] 对象:
  26. [SystemMessage(content='秋水札记,定位于 LangChain AI 编程推广,分享 LangChain 商业与技术。'), HumanMessage(content='帮我列出几个AI商业案例?')]
  27. 每一个BaseMessage 对象:
  28. 秋水札记,定位于 LangChain AI 编程推广,分享 LangChain 商业与技术。
  29. 帮我列出几个AI商业案例?
  30. format()执行后返回字符串:
  31. System: 秋水札记,定位于 LangChain AI 编程推广,分享 LangChain 商业与技术。
  32. Human: 帮我列出几个AI商业案例?
  33. format_prompt()执行后返回PromptValue 对象:
  34. messages=[SystemMessage(content='秋水札记,定位于 LangChain AI 编程推广,分享 LangChain 商业与技术。'), HumanMessage(content='帮我列出几个AI商业案例?')]
  35. '''

使用 SystemMessage、HumanMessage、AIMessage 角色消息创建聊天提示时,在具体的提示字符串中不能设置变量,如果需要设置变量则需要将这三种消息类型换成消息模版SystemMessagePromptTemplate、HumanMessagePromptTemplate、AIMessagePromptTemplate。
SystemMessage 对应的是前面讲的ChatGPT三种主要角色中的SYSTEM。
HumanMessage 对应的是USER,就是用户输入的问题内容。
AIMessage 对应的是ASSISTANT,就是AI大模型的回复内容。
SystemMessage、HumanMessage、AIMessage角色消息,不是提示模版,不支持在提示中设置变量。

  • 利用诸如SystemMessagePromptTemplate角色消息模版创建聊天模版
  1. # 定义变量
  2. brand = "秋水札记"
  3. product_promotion = "LangChain"
  4. business_case = "AI商业案例"
  5. # 使用构造函数创建提示模板
  6. # 这里的 messages 列表直接使用了字符串格式的消息,
  7. # 但同样可以根据需要扩展为更复杂的消息提示模板
  8. messages = [
  9. SystemMessagePromptTemplate(
  10. prompt = PromptTemplate(input_variables=[],
  11. template='{brand},定位于 LangChain AI 编程推广,分享 {product_promotion} 商业与技术。')
  12. ),HumanMessagePromptTemplate(
  13. prompt = PromptTemplate(input_variables=[],
  14. template='帮我列出几个{business_case}')
  15. )
  16. ]
  17. prompt = ChatPromptTemplate(input_variables=[], messages=messages)
  18. # 格式化并输出模板
  19. formatted_prompt = prompt.format_messages(brand=brand, product_promotion=product_promotion, business_case=business_case)print("format_messages()执行后返回List[BaseMessage] 对象:")
  20. print(formatted_prompt)
  21. '''
  22. 代码执行后输出内容如下:
  23. format_messages()执行后返回List[BaseMessage] 对象:
  24. [SystemMessage(content='秋水札记,定位于 LangChain AI 编程推广,分享 LangChain 商业与技术。'), HumanMessage(content='帮我列出几个AI商业案例?')]
  25. '''

使用SystemMessagePromptTemplate、HumanMessagePromptTemplate、AIMessagePromptTemplate创建聊天提示,这三个角色提示模版的构造方法的重要参数就是prompt,它要求传入PromptTemplate对像。

使用from_messages创建聊天提示

  1. template = ChatPromptTemplate.from_messages([
  2. ("system", "{brand},定位于 LangChain AI 编程推广,分享 {product_promotion} 商业与技术。"),
  3. HumanMessagePromptTemplate(
  4. prompt = PromptTemplate(input_variables=[],
  5. template='帮我列出几个{business_case}')
  6. ),
  7. AIMessage(content='语音助手、聊天机器人和对话式AI。')
  8. ])
  9. messages = template.format_messages(
  10. brand="秋水札记",
  11. product_promotion="LangChain",
  12. business_case="AI商业案例"
  13. )
  14. print(messages)
  15. '''
  16. 代码执行后输出内容如下:
  17. [SystemMessage(content='秋水札记,定位于 LangChain AI 编程推广,分享 LangChain 商业与技术。'), HumanMessage(content='帮我列出几个AI商业案例'), AIMessage(content='语音助手、聊天机器人和对话式AI')]
  18. '''

这种创建聊天提示的方式,在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基本一样。