在处理大量示例时,我们可能需要选择哪些示例应该包含在提示(prompt)中。示例选择器(Example Selector)就是负责完成这一任务的类。
示例选择器的基本接口定义如下:
pythonfrom abc import ABC, abstractmethod
from typing import Dict, List, Any
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
:根据输入变量选择示例。add_example
:向示例存储中添加新示例。为了使用示例选择器,我们首先需要创建一个示例列表。这些示例通常是输入和输出的组合。假设我们要选择一些将英语翻译成意大利语的示例:
pythonexamples = [
{"input": "hi", "output": "ciao"},
{"input": "bye", "output": "arrivederci"},
{"input": "soccer", "output": "calcio"},
]
我们可以编写一个自定义的示例选择器,根据单词的长度来选择示例。
pythonfrom 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):
# 假设输入中会有一个 'input' 键
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]
我们可以使用这个自定义的示例选择器来选择示例:
pythonexample_selector = CustomExampleSelector(examples)
# 选择与 "okay" 长度最接近的示例
selected_examples = example_selector.select_examples({"input": "okay"})
print(selected_examples) # 输出: [{'input': 'bye', 'output': 'arrivederci'}]
# 添加一个新示例
example_selector.add_example({"input": "hand", "output": "mano"})
# 再次选择与 "okay" 长度最接近的示例
selected_examples = example_selector.select_examples({"input": "okay"})
print(selected_examples) # 输出: [{'input': 'hand', 'output': 'mano'}]
我们可以将这个示例选择器用在提示模板中:
pythonfrom langchain_core.prompts.few_shot import FewShotPromptTemplate
from langchain_core.prompts.prompt import PromptTemplate
# 定义示例提示模板
example_prompt = PromptTemplate.from_template("Input: {input} -> Output: {output}")
# 定义 FewShotPromptTemplate
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"],
)
# 格式化提示
formatted_prompt = prompt.format(input="word")
print(formatted_prompt)
输出结果:
Translate the following words from English to Italian: Input: hand -> Output: mano Input: word -> Output:
LangChain 提供了几种不同类型的示例选择器:
名称 | 描述 |
---|---|
Similarity | 使用输入和示例之间的语义相似度来选择示例。 |
MMR | 使用最大边际相关性(Max Marginal Relevance)来选择示例。 |
Length | 根据示例的长度选择示例,确保它们能适应一定的长度限制。 |
Ngram | 使用输入和示例之间的 ngram 重叠来选择示例。 |
通过自定义示例选择器,我们可以根据特定的逻辑(如单词长度)来选择最合适的示例。然后,我们可以将这些示例应用到提示模板中,生成最终的提示。LangChain 提供了多种示例选择器类型,可以根据具体需求选择合适的类型。
本文作者:yowayimono
本文链接:
版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!