Skip to main content

提示管道化 Prompt Pipelining

提示管道化的想法是为组合不同部分的提示提供用户友好的界面。您可以使用字符串提示或聊天提示来实现这一点。以这种方式构建提示允许组件的轻松重用。

字符串提示管道化

在使用字符串提示时,每个模板都会连接在一起。您可以直接使用提示或字符串(列表中的第一个元素需要是提示)。

from langchain.prompts import PromptTemplate

API 参考:

/Users/harrisonchase/.pyenv/versions/3.9.1/envs/langchain/lib/python3.9/site-packages/deeplake/util/check_latest_version.py:32: UserWarning: A newer version of deeplake (3.6.12) is available. It's recommended that you update to the latest version using `pip install -U deeplake`.
warnings.warn(
prompt = (
PromptTemplate.from_template("Tell me a joke about {topic}")
+ ", make it funny"
+ "\n\nand in {language}"
)

prompt
PromptTemplate(input_variables=['language', 'topic'], output_parser=None, partial_variables={}, template='Tell me a joke about {topic}, make it funny\n\nand in {language}', template_format='f-string', validate_template=True)
prompt.format(topic="sports", language="spanish")
'Tell me a joke about sports, make it funny\n\nand in spanish'

您也可以像以前一样在 LLMChain 中使用它。

from langchain.chat_models import ChatOpenAI
from langchain.chains import LLMChain

API 参考:

model = ChatOpenAI()
chain = LLMChain(llm=model, prompt=prompt)
chain.run(topic="sports", language="spanish")
'¿Por qué el futbolista llevaba un paraguas al partido?\n\nPorque pronosticaban lluvia de goles.'

聊天提示管道化

聊天提示由消息列表组成。为了开发者体验,我们添加了一种方便的方式来创建这些提示。在这个管道中,每个新元素都是最终提示中的新消息。

from langchain.prompts import ChatPromptTemplate, HumanMessagePromptTemplate
from langchain.schema import HumanMessage, AIMessage, SystemMessage

API 参考:

/Users/harrisonchase/.pyenv/versions/3.9.1/envs/langchain/lib/python3.9/site-packages/deeplake/util/check_latest_version.py:32: UserWarning: A newer version of deeplake (3.6.10) is available. It's recommended that you update to the latest version using `pip install -U deeplake`.
warnings.warn(

首先,让我们使用系统消息初始化基本的 ChatPromptTemplate。它不一定要以系统消息开头,但这通常是一个好的做法。

prompt = SystemMessage(content="You are a nice pirate")

然后,您可以轻松地将其与其他消息或消息模板组合在一起。当没有要格式化的变量时,使用 Message,当有要格式化的变量时,使用 MessageTemplate。您也可以只使用字符串 -> 请注意,这将自动推断为 HumanMessagePromptTemplate。

new_prompt = (
prompt
+ HumanMessage(content="hi")
+ AIMessage(content="what?")
+ "{input}"
)

在幕后,这将创建 ChatPromptTemplate 类的一个实例,因此您可以像以前一样使用它!

new_prompt.format_messages(input="i said hi")
[SystemMessage(content='You are a nice pirate', additional_kwargs={}),
HumanMessage(content='hi', additional_kwargs={}, example=False),
AIMessage(content='what?', additional_kwargs={}, example=False),
HumanMessage(content='i said hi', additional_kwargs={}, example=False)]

您也可以像以前一样在 LLMChain 中使用它。

from langchain.chat_models import ChatOpenAI
from langchain.chains import LLMChain

API 参考:

model = ChatOpenAI()
chain = LLMChain(llm=model, prompt=new_prompt)
chain.run("i said hi")
'Oh, hello! How can I assist you today?'