如何使用示例选择器
如果您有大量的示例,可能需要选择哪些示例包含在提示中。示例选择器(Example Selector)是负责执行此操作的类。
其基本接口定义如下:
class BaseExampleSelector {
addExample(example: Example): Promise<void | string>;
selectExamples(inputVariables: Example): Promise<Example[]>;
}
它需要定义的唯一方法是 selectExamples
方法。该方法接收输入变量,并返回示例列表。具体如何选择这些示例,由每个特定的实现决定。
LangChain 提供了几种不同类型的示例选择器。有关所有这些类型的概述,请参见下表。
在本指南中,我们将演示如何创建一个自定义的示例选择器。
示例
要使用示例选择器,我们需要创建一个示例列表。这些示例通常应包含输入和输出的示例。为了演示的目的,我们来设想一个如何将英语翻译成意大利语的示例选择器。
const examples = [
{ input: "hi", output: "ciao" },
{ input: "bye", output: "arrivaderci" },
{ input: "soccer", output: "calcio" },
];
自定义示例选择器
让我们编写一个示例选择器,根据单词长度选择应使用的示例。
import { BaseExampleSelector } from "@langchain/core/example_selectors";
import { Example } from "@langchain/core/prompts";
class CustomExampleSelector extends BaseExampleSelector {
private examples: Example[];
constructor(examples: Example[]) {
super();
this.examples = examples;
}
async addExample(example: Example): Promise<void | string> {
this.examples.push(example);
return;
}
async selectExamples(inputVariables: Example): Promise<Example[]> {
// This assumes knowledge that part of the input will be a 'text' key
const newWord = inputVariables.input;
const newWordLength = newWord.length;
// Initialize variables to store the best match and its length difference
let bestMatch: Example | null = null;
let smallestDiff = Infinity;
// Iterate through each example
for (const example of this.examples) {
// Calculate the length difference with the first word of the example
const currentDiff = Math.abs(example.input.length - newWordLength);
// Update the best match if the current one is closer in length
if (currentDiff < smallestDiff) {
smallestDiff = currentDiff;
bestMatch = example;
}
}
return bestMatch ? [bestMatch] : [];
}
}
const exampleSelector = new CustomExampleSelector(examples);
await exampleSelector.selectExamples({ input: "okay" });
[ { input: "bye", output: "arrivaderci" } ]
await exampleSelector.addExample({ input: "hand", output: "mano" });
await exampleSelector.selectExamples({ input: "okay" });
[ { input: "hand", output: "mano" } ]
在提示中使用
我们现在可以在提示中使用此示例选择器
import { PromptTemplate, FewShotPromptTemplate } from "@langchain/core/prompts";
const examplePrompt = PromptTemplate.fromTemplate(
"Input: {input} -> Output: {output}"
);
const prompt = new FewShotPromptTemplate({
exampleSelector,
examplePrompt,
suffix: "Input: {input} -> Output:",
prefix: "Translate the following words from English to Italian:",
inputVariables: ["input"],
});
console.log(await prompt.format({ input: "word" }));
Translate the following words from English to Italian:
Input: hand -> Output: mano
Input: word -> Output:
示例选择器类型
| 名称 | 描述 |
|---|---|
| 相似性 | 使用输入与示例之间的语义相似性来决定选择哪些示例。 |
| 长度 | 根据能够在特定长度内容纳多少示例来选择示例 |
下一步
您现在已经了解了一些关于使用示例选择器进行少量样本 LLM 的知识。
接下来,请查看一些关于其他示例选择技术的指南: