跳到主要内容
Open In ColabOpen on GitHub

如何部分格式化提示词模板

先决条件

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

就像将参数部分绑定到函数一样,对提示词模板进行“部分”操作也很有意义 - 例如,传入所需值的一个子集,以创建一个新的提示词模板,该模板仅期望剩余的值子集。

LangChain 通过两种方式支持此操作

  1. 使用字符串值进行部分格式化。
  2. 使用返回字符串值的函数进行部分格式化。

在下面的示例中,我们将介绍两种用例的动机以及如何在 LangChain 中执行此操作。

使用字符串进行部分格式化

想要部分格式化提示词模板的一个常见用例是,如果您在其他变量之前访问提示中的某些变量。例如,假设您有一个提示词模板,需要两个变量 foobaz。如果您在链的早期获得 foo 值,但在稍后获得 baz 值,则将两个变量都传递到链中可能很不方便。相反,您可以使用 foo 值部分格式化提示词模板,然后传递部分格式化的提示词模板并仅使用它。以下是执行此操作的示例

from langchain_core.prompts import PromptTemplate

prompt = PromptTemplate.from_template("{foo}{bar}")
partial_prompt = prompt.partial(foo="foo")
print(partial_prompt.format(bar="baz"))
API 参考:PromptTemplate
foobaz

您也可以仅使用部分格式化的变量初始化提示。

prompt = PromptTemplate(
template="{foo}{bar}", input_variables=["bar"], partial_variables={"foo": "foo"}
)
print(prompt.format(bar="baz"))
foobaz

使用函数进行部分格式化

另一个常见的用例是使用函数进行部分格式化。这种情况的用例是,当您有一个变量,您知道您总是想以通用的方式获取它时。日期或时间是这方面的一个典型例子。想象一下,您有一个提示,您总是希望其中包含当前日期。您无法将其硬编码在提示中,并且与其他输入变量一起传递它很不方便。在这种情况下,能够使用始终返回当前日期的函数部分格式化提示会很方便。

from datetime import datetime


def _get_datetime():
now = datetime.now()
return now.strftime("%m/%d/%Y, %H:%M:%S")


prompt = PromptTemplate(
template="Tell me a {adjective} joke about the day {date}",
input_variables=["adjective", "date"],
)
partial_prompt = prompt.partial(date=_get_datetime)
print(partial_prompt.format(adjective="funny"))
Tell me a funny joke about the day 04/21/2024, 19:43:57

您也可以仅使用部分格式化的变量初始化提示,这在这种工作流程中通常更有意义。

prompt = PromptTemplate(
template="Tell me a {adjective} joke about the day {date}",
input_variables=["adjective"],
partial_variables={"date": _get_datetime},
)
print(prompt.format(adjective="funny"))
Tell me a funny joke about the day 04/21/2024, 19:43:57

下一步

您现在已经学会了如何将变量部分应用于您的提示词模板。

接下来,查看本节中有关提示词模板的其他操作指南,例如向您的提示词模板添加少量示例


此页面是否对您有帮助?