Prompt templates
https://python.langchain.com/docs/concepts/#prompt-templates
提示模板帮助将用户输入和参数转换为语言模型的指令。它可以用来引导模型的响应,帮助其理解上下文,并生成相关且连贯的语言输出。
提示模板接受一个字典作为输入,其中每个键代表提示模板中需要填充的变量。
提示模板输出一个 PromptValue。这个 PromptValue 可以传递给 LLM 或 ChatModel,也可以转换为字符串或消息列表。之所以有 PromptValue,是为了方便在字符串和消息之间切换。
提示模板有几种不同类型:
String PromptTemplates
这些提示模板用于格式化单个字符串,通常用于较简单的输入。例如,构建和使用 PromptTemplate 的常见方式如下:
from langchain_core.prompts import PromptTemplate
prompt_template = PromptTemplate.from_template("Tell me a joke about {topic}")
prompt_template.invoke({"topic": "cats"})API Reference: PromptTemplate
ChatPromptTemplates
这些提示模板用于格式化消息列表。这些“模板”本身由多个模板组成。例如,构建和使用 ChatPromptTemplate 的常见方式如下:
from langchain_core.prompts import ChatPromptTemplate
prompt_template = ChatPromptTemplate.from_messages([
("system", "You are a helpful assistant"),
("user", "Tell me a joke about {topic}")
])
prompt_template.invoke({"topic": "cats"})API Reference: ChatPromptTemplate
在上述示例中,当调用该 ChatPromptTemplate 时,它将构建两条消息。第一条是系统消息,不包含需要格式化的变量。第二条是 HumanMessage,将通过用户传入的 topic 变量进行格式化。
MessagesPlaceholder
MessagesPlaceholder 用于在特定位置插入消息列表。在上面的 ChatPromptTemplate 示例中,我们看到了如何格式化两条消息,每条都是一个字符串。但是如果我们希望用户传入一个消息列表,并将其插入到特定位置,该怎么做呢?这就是 MessagesPlaceholder 的用途。
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!")]})API Reference: ChatPromptTemplate | MessagesPlaceholder | HumanMessage
这将生成两条消息,第一条是系统消息,第二条是我们传入的 HumanMessage。如果我们传入了 5 条消息,则总共会生成 6 条消息(系统消息加上传入的 5 条消息)。这对于将一组消息插入特定位置非常有用。
另一种无需显式使用 MessagesPlaceholder 类来实现相同效果的方法是:
prompt_template = ChatPromptTemplate.from_messages([
("system", "You are a helpful assistant"),
("placeholder", "{msgs}") # <-- This is the changed part
])有关如何使用提示模板的具体说明,请参阅此处的相关操作指南。