跳到主要內容
Open In ColabOpen on GitHub

如何組合提示詞

先決條件

本指南假設您熟悉以下概念

LangChain 提供了一個使用者友善的介面,用於將 提示詞的不同部分組合在一起。您可以使用字串提示詞或聊天提示詞來完成此操作。以這種方式建構提示詞可以輕鬆重複使用組件。

字串提示詞組合

當使用字串提示詞時,每個範本都會被連接在一起。您可以直接使用提示詞或字串(列表中的第一個元素需要是提示詞)。

from langchain_core.prompts import PromptTemplate

prompt = (
PromptTemplate.from_template("Tell me a joke about {topic}")
+ ", make it funny"
+ "\n\nand in {language}"
)

prompt
API 參考:PromptTemplate
PromptTemplate(input_variables=['language', 'topic'], template='Tell me a joke about {topic}, make it funny\n\nand in {language}')
prompt.format(topic="sports", language="spanish")
'Tell me a joke about sports, make it funny\n\nand in spanish'

聊天提示詞組合

聊天提示詞由訊息列表組成。與上面的範例類似,我們可以串聯聊天提示詞範本。每個新元素都是最終提示詞中的新訊息。

首先,讓我們使用 SystemMessage 初始化 ChatPromptTemplate

from langchain_core.messages import AIMessage, HumanMessage, SystemMessage

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'),
HumanMessage(content='hi'),
AIMessage(content='what?'),
HumanMessage(content='i said hi')]

使用 PipelinePrompt

LangChain 包含一個名為 PipelinePromptTemplate 的類別,當您想要重複使用提示詞的部分內容時,它會很有用。 PipelinePrompt 由兩個主要部分組成

  • 最終提示詞:返回的最終提示詞
  • 管道提示詞:一個元組列表,由字串名稱和提示詞範本組成。每個提示詞範本都將被格式化,然後作為具有相同名稱的變數傳遞給未來的提示詞範本。
from langchain_core.prompts import PipelinePromptTemplate, PromptTemplate

full_template = """{introduction}

{example}

{start}"""
full_prompt = PromptTemplate.from_template(full_template)

introduction_template = """You are impersonating {person}."""
introduction_prompt = PromptTemplate.from_template(introduction_template)

example_template = """Here's an example of an interaction:

Q: {example_q}
A: {example_a}"""
example_prompt = PromptTemplate.from_template(example_template)

start_template = """Now, do this for real!

Q: {input}
A:"""
start_prompt = PromptTemplate.from_template(start_template)

input_prompts = [
("introduction", introduction_prompt),
("example", example_prompt),
("start", start_prompt),
]
pipeline_prompt = PipelinePromptTemplate(
final_prompt=full_prompt, pipeline_prompts=input_prompts
)

pipeline_prompt.input_variables
['person', 'example_a', 'example_q', 'input']
print(
pipeline_prompt.format(
person="Elon Musk",
example_q="What's your favorite car?",
example_a="Tesla",
input="What's your favorite social media site?",
)
)
You are impersonating Elon Musk.

Here's an example of an interaction:

Q: What's your favorite car?
A: Tesla

Now, do this for real!

Q: What's your favorite social media site?
A:

下一步

您現在已經學會如何組合提示詞。

接下來,查看本節中關於提示詞範本的其他操作指南,例如將少量樣本範例添加到您的提示詞範本


此頁面是否對您有幫助?