跳到主要內容
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

下一步

您現在已經學習如何將變數部分應用於您的提示範本。

接下來,查看本節中關於提示範本的其他操作指南,例如將少量範例新增至您的提示範本


此頁面是否有幫助?