如何使用示例选择器
如果你有大量的示例,你可能需要选择要包含在提示中的示例。示例选择器 就是负责这项工作的类。
基本接口定义如下:
class BaseExampleSelector(ABC):
"""用于选择要包含在提示中的示例的接口。"""
@abstractmethod
def select_examples(self, input_variables: Dict[str, str]) -> List[dict]:
"""根据输入选择要使用的示例。"""
@abstractmethod
def add_example(self, example: Dict[str, str]) -> Any:
"""向存储中添加新示例。"""
唯一需要定义的方法是 select_examples。它接收输入变量,然后返回一个示例列表。具体如何选择示例由每个特定的实现决定。
LangChain 有几种不同类型的示例选择器。有关所有这些类型的概述,请参阅下表。
在本指南中,我们将介绍如何创建一个自定义示例选择器。
示例
为了使用示例选择器,我们需要创建一个示例列表。这些通常应该是示例输入和输出。为了演示目的,让我们假设我们正在选择如何将英语翻译成意大利语的示例。
examples = [
{"input": "hi", "output": "ciao"},
{"input": "bye", "output": "arrivederci"},
{"input": "soccer", "output": "calcio"},
]
自定义示例选择器
让我们来写一个示例选择器,它根据单词的长度来选择要 Pick 的示例。
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 Reference: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'}]
在 Prompt 中使用
我们现在可以在 prompt 中使用这个示例选择器
from langchain_core.prompts.few_shot import FewShotPromptTemplate
from langchain_core.prompts.prompt import PromptTemplate
example_prompt = PromptTemplate.from_template("Input: {input} -> Output: {output}")
API Reference:FewShotPromptTemplate | PromptTemplate
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:
范例选择器类型
| 名称 | 描述 |
|---|---|
| Similarity | 使用输入与范例之间的语义相似度来决定选择哪些范例。 |
| MMR | 使用输入与范例之间的最大边际相关性来决定选择哪些范例。 |
| Length | 根据能放入特定长度的范例数量来选择范例。 |
| Ngram | 使用输入与范例之间的 ngram 重叠来决定选择哪些范例。 |