在处理大量示例时,我们可能需要选择哪些示例要包含在提示中。Example Selector类正是负责执行这一任务的接口。以下是其基本接口定义:
from abc import ABC, abstractmethod
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"},
]
自定义示例选择器
下面编写一个示例选择器,该选择器根据单词长度来选择示例。
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):
new_word = input_variables["input"]
new_word_length = len(new_word)
best_match = None
smallest_diff = float("inf")
for example in self.examples:
current_diff = abs(len(example["input"]) - new_word_length)
if current_diff < smallest_diff:
smallest_diff = current_diff
best_match = example
return [best_match]
# 使用自定义示例选择器
example_selector = CustomExampleSelector(examples)
print(example_selector.select_examples({"input": "okay"}))
# 添加新示例
example_selector.add_example({"input": "hand", "output": "mano"})
print(example_selector.select_examples({"input": "okay"}))
运行以上代码,输出将是:
[{'input': 'bye', 'output': 'arrivederci'}]
[{'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}")
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 | 使用Max Marginal Relevance来选择示例。 |
Length | 基于示例符合一定长度选择示例。 |
Ngram | 使用n-gram重叠来选择示例。 |
如果遇到问题欢迎在评论区交流。