如何部分格式化提示模板
先决条件
本指南假定您熟悉以下概念:
就像将参数部分绑定到函数一样,“部分”提示模板也是有意义的 - 例如,传入所需值的子集,以创建一个仅期望剩余值子集的新提示模板。
LangChain 通过两种方式支持此功能:
- 使用字符串值进行部分格式化。
- 使用返回字符串值的函数进行部分格式化。
在下面的示例中,我们将介绍这两种用例的动机,以及如何在 LangChain 中执行此作。
带字符串的 Partial
想要对提示模板进行部分分配的一个常见用例是,如果您在其他变量之前访问提示中的某些变量。例如,假设您有一个需要两个变量foo和baz.如果您获取foovalue 的bazvalue 之后,将两个变量完全传递到链中可能会很不方便。相反,您可以使用foo值,然后传递 partialed prompt 模板并使用它。下面是执行此作的示例:
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
您也可以只使用 partialed 变量初始化提示。
prompt = PromptTemplate(
template="{foo}{bar}", input_variables=["bar"], partial_variables={"foo": "foo"}
)
print(prompt.format(bar="baz"))
foobaz
Partial with 函数
另一个常见用法是 partial with 函数。这样做的用例是,当你有一个变量时,你知道你总是希望以一种常见的方式获取。一个典型的例子是日期或时间。假设您有一个提示,您始终希望显示当前日期。你不能在 prompt 中对它进行硬编码,并且它与其他 input 变量一起传递很不方便。在这种情况下,能够使用始终返回当前日期的函数对提示进行部分设置非常方便。
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
您也可以只使用 partialed 变量初始化提示,这在此工作流程中通常更有意义。
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
后续步骤
您现在已经学习了如何将变量部分应用于提示模板。
接下来,查看本节中关于提示模板的其他操作指南,例如向提示模板添加少量示例。