跳到主要內容
Open In ColabOpen on GitHub

如何使用範例選擇器

如果您有大量的範例,您可能需要選擇要在提示中包含哪些範例。 範例選擇器是負責執行此操作的類別。

基本介面定義如下

class BaseExampleSelector(ABC):
"""Interface for selecting examples to include in prompts."""

@abstractmethod
def select_examples(self, input_variables: Dict[str, str]) -> List[dict]:
"""Select which examples to use based on the inputs."""

@abstractmethod
def add_example(self, example: Dict[str, str]) -> Any:
"""Add new example to store."""

它需要定義的唯一方法是 `select_examples` 方法。 這會接收輸入變數,然後返回範例列表。 如何選擇這些範例取決於每個特定的實作。

LangChain 有幾種不同類型的範例選擇器。 有關所有這些類型的概述,請參見下表。

在本指南中,我們將逐步介紹如何建立自訂範例選擇器。

範例

為了使用範例選擇器,我們需要建立範例列表。 這些通常應該是範例輸入和輸出。 為了演示目的,讓我們想像一下我們正在選擇如何將英語翻譯成義大利語的範例。

examples = [
{"input": "hi", "output": "ciao"},
{"input": "bye", "output": "arrivederci"},
{"input": "soccer", "output": "calcio"},
]

自訂範例選擇器

讓我們編寫一個範例選擇器,該選擇器根據單字的長度選擇要選擇哪個範例。

from langchain_core.example_selectors.base import BaseExampleSelector


class CustomExampleSelector(BaseExampleSelector):
def __init__(self, examples):
self.examples = examples

def add_example(self, example):
self.examples.append(example)

def select_examples(self, input_variables):
# This assumes knowledge that part of the input will be a 'text' key
new_word = input_variables["input"]
new_word_length = len(new_word)

# Initialize variables to store the best match and its length difference
best_match = None
smallest_diff = float("inf")

# Iterate through each example
for example in self.examples:
# Calculate the length difference with the first word of the example
current_diff = abs(len(example["input"]) - new_word_length)

# Update the best match if the current one is closer in length
if current_diff < smallest_diff:
smallest_diff = current_diff
best_match = example

return [best_match]
API 參考:BaseExampleSelector
example_selector = CustomExampleSelector(examples)
example_selector.select_examples({"input": "okay"})
[{'input': 'bye', 'output': 'arrivederci'}]
example_selector.add_example({"input": "hand", "output": "mano"})
example_selector.select_examples({"input": "okay"})
[{'input': 'hand', 'output': 'mano'}]

在提示中使用

我們現在可以在提示中使用此範例選擇器

from langchain_core.prompts.few_shot import FewShotPromptTemplate
from langchain_core.prompts.prompt import PromptTemplate

example_prompt = PromptTemplate.from_template("Input: {input} -> Output: {output}")
prompt = FewShotPromptTemplate(
example_selector=example_selector,
example_prompt=example_prompt,
suffix="Input: {input} -> Output:",
prefix="Translate the following words from English to Italian:",
input_variables=["input"],
)

print(prompt.format(input="word"))
Translate the following words from English to Italian:

Input: hand -> Output: mano

Input: word -> Output:

範例選擇器類型

名稱描述
相似度使用輸入和範例之間的語意相似度來決定選擇哪些範例。
MMR使用輸入和範例之間的最大邊際相關性來決定選擇哪些範例。
長度根據可以在特定長度內容納多少範例來選擇範例
N-gram使用輸入和範例之間的 n-gram 重疊來決定選擇哪些範例。

此頁面是否有幫助?