自然语言处理从入门到应用——LangChain:提示(Prompts)-[示例选择器(Example Selectors)]

分类目录:《自然语言处理从入门到应用》总目录


如果我们拥有大量的示例,我们可能需要选择在提示中包含哪些示例。ExampleSelector是负责执行此操作的类。 其基本接口定义如下所示:

class BaseExampleSelector(ABC):"""Interface for selecting examples to include in prompts."""def select_examples(self, input_variables: Dict[str, str]) -> List[dict]:"""Select which examples to use based on the inputs."""

它只需要暴露一个select_examples方法,该方法接收输入变量并返回一个示例列表。具体如何选择这些示例取决于每个具体实现。

自定义示例选择器(Custom Example Selector)

自定义示例选择器从给定的示例的列表中选择固定个示例。一个ExampleSelector必须实现两个方法:

  • 一个add_example方法,它接受一个示例并将其添加到ExampleSelector
  • 一个select_examples方法,它接受输入变量(用户输入),并返回要在few-shot提示中使用的示例列表

让我们实现一个简单的自定义ExampleSelector,它只随机选择两个示例。

实现自定义示例选择器
from langchain.prompts.example_selector.base import BaseExampleSelector
from typing import Dict, List
import numpy as npclass CustomExampleSelector(BaseExampleSelector):def __init__(self, examples: List[Dict[str, str]]):self.examples = examplesdef add_example(self, example: Dict[str, str]) -> None:"""Add new example to store for a key."""self.examples.append(example)def select_examples(self, input_variables: Dict[str, str]) -> List[dict]:"""Select which examples to use based on the inputs."""return np.random.choice(self.examples, size=2, replace=False)
使用自定义示例选择器
examples = [{"foo": "1"},{"foo": "2"},{"foo": "3"}
]# 初始化示例选择器
example_selector = CustomExampleSelector(examples)# 选择示例
example_selector.select_examples({"foo": "foo"})
# -> [{'foo': '2'}, {'foo': '3'}]# 向示例集合添加新示例
example_selector.add_example({"foo": "4"})
example_selector.examples
# -> [{'foo': '1'}, {'foo': '2'}, {'foo': '3'}, {'foo': '4'}]# 选择示例
example_selector.select_examples({"foo": "foo"})
# -> [{'foo': '1'}, {'foo': '4'}]

基于长度的示例选择器(LengthBased ExampleSelector)

基于长度的示例选择器根据示例的长度来选择要使用的示例。当我们担心构建的提示内容超过上下文窗口的长度时这种示例选择器将非常有用。对于较长的输入,它会选择较少的示例进行包含,而对于较短的输入,它会选择更多的示例。

from langchain.prompts import PromptTemplate
from langchain.prompts import FewShotPromptTemplate
from langchain.prompts.example_selector import LengthBasedExampleSelector# These are a lot of examples of a pretend task of creating antonyms.
examples = [{"input": "happy", "output": "sad"},{"input": "tall", "output": "short"},{"input": "energetic", "output": "lethargic"},{"input": "sunny", "output": "gloomy"},{"input": "windy", "output": "calm"},
]example_prompt = PromptTemplate(input_variables=["input", "output"],template="Input: {input}\nOutput: {output}",
)example_selector = LengthBasedExampleSelector(# These are the examples it has available to choose from.examples=examples, # This is the PromptTemplate being used to format the examples.example_prompt=example_prompt, # This is the maximum length that the formatted examples should be.# Length is measured by the get_text_length function below.max_length=25,# This is the function used to get the length of a string, which is used# to determine which examples to include. It is commented out because# it is provided as a default value if none is specified.# get_text_length: Callable[[str], int] = lambda x: len(re.split("\n| ", x))
)dynamic_prompt = FewShotPromptTemplate(# We provide an ExampleSelector instead of examples.example_selector=example_selector,example_prompt=example_prompt,prefix="Give the antonym of every input",suffix="Input: {adjective}\nOutput:", input_variables=["adjective"],
)
# An example with small input, so it selects all examples.
print(dynamic_prompt.format(adjective="big"))

输出:

Give the antonym of every inputInput: happy
Output: sadInput: tall
Output: shortInput: energetic
Output: lethargicInput: sunny
Output: gloomyInput: windy
Output: calmInput: big
Output:

当输入较长时:

# An example with long input, so it selects only one example.
long_string = "big and huge and massive and large and gigantic and tall and much much much much much bigger than everything else"
print(dynamic_prompt.format(adjective=long_string))
Give the antonym of every input

输出:

Input: happy
Output: sadInput: big and huge and massive and large and gigantic and tall and much much much much much bigger than everything else
Output:

我们还可以新增一个示例:

# You can add an example to an example selector as well.
new_example = {"input": "big", "output": "small"}
dynamic_prompt.example_selector.add_example(new_example)
print(dynamic_prompt.format(adjective="enthusiastic"))

输出:

Give the antonym of every inputInput: happy
Output: sadInput: tall
Output: shortInput: energetic
Output: lethargicInput: sunny
Output: gloomyInput: windy
Output: calmInput: big
Output: smallInput: enthusiastic
Output:

最大边际相关性示例选择器(Maximal Marginal Relevance ExampleSelector)

最大边际相关性示例选择器根据示例与输入的相似度以及多样性进行选择。它通过找到与输入具有最大余弦相似度的示例的嵌入,然后迭代地添加它们,同时对它们与已选择示例的接近程度进行惩罚,来实现这一目标。

from langchain.prompts.example_selector import MaxMarginalRelevanceExampleSelector, SemanticSimilarityExampleSelector
from langchain.vectorstores import FAISS
from langchain.embeddings import OpenAIEmbeddings
from langchain.prompts import FewShotPromptTemplate, PromptTemplateexample_prompt = PromptTemplate(input_variables=["input", "output"],template="Input: {input}\nOutput: {output}",
)# 这些是一个虚构任务创建反义词的许多示例。
examples = [{"input": "happy", "output": "sad"},{"input": "tall", "output": "short"},{"input": "energetic", "output": "lethargic"},{"input": "sunny", "output": "gloomy"},{"input": "windy", "output": "calm"},
]
example_selector = MaxMarginalRelevanceExampleSelector.from_examples(# 这是可供选择的示例列表。examples,# 这是用于生成嵌入向量以测量语义相似性的嵌入类。OpenAIEmbeddings(),# 这是用于存储嵌入向量并进行相似性搜索的 VectorStore 类。FAISS,# 这是要生成的示例数量。k=2
)
mmr_prompt = FewShotPromptTemplate(# 我们提供一个 ExampleSelector 而不是示例列表。example_selector=example_selector,example_prompt=example_prompt,prefix="给出每个输入的反义词",suffix="输入:{adjective}\n输出:",input_variables=["adjective"],
)
# 输入是一个情感,因此应该选择 happy/sad 示例作为第一个示例
print(mmr_prompt.format(adjective="worried"))

输出:

Give the antonym of every inputInput: happy
Output: sadInput: windy
Output: calmInput: worried
Output:

我们还可以与仅基于相似性进行选择的情况进行比较:

# 使用 SemanticSimilarityExampleSelector 而不是 MaxMarginalRelevanceExampleSelector。
example_selector = SemanticSimilarityExampleSelector.from_examples(# 这是可供选择的示例列表。examples,# 这是用于生成嵌入向量以测量语义相似性的嵌入类。OpenAIEmbeddings(),# 这是用于存储嵌入向量并进行相似性搜索的 VectorStore 类。FAISS,# 这是要生成的示例数量。k=2
)
similar_prompt = FewShotPromptTemplate(# 我们提供一个 ExampleSelector 而不是示例列表。example_selector=example_selector,example_prompt=example_prompt,prefix="给出每个输入的反义词",suffix="输入:{adjective}\n输出:",input_variables=["adjective"],
)
print(similar_prompt.format(adjective="worried"))

输出:

Give the antonym of every inputInput: happy
Output: sadInput: sunny
Output: gloomyInput: worried
Output:

N-Gram重叠示例选择器(N-Gram Overlap ExampleSelector)

NGramOverlapExampleSelector根据示例与输入之间的n-gram重叠得分选择和排序示例。n-gram重叠得分是一个介于0.0和1.0之间的浮点数。该选择器允许设置一个阈值分数。n-gram 重叠得分小于或等于阈值的示例将被排除。默认情况下,阈值设置为-1.0,因此不会排除任何示例,只会重新排序它们。将阈值设置为0.0将排除与输入没有n-gram重叠的示例。

from langchain.prompts import PromptTemplate
from langchain.prompts.example_selector.ngram_overlap import NGramOverlapExampleSelector
from langchain.prompts import FewShotPromptTemplate, PromptTemplateexample_prompt = PromptTemplate(input_variables=["input", "output"],template="Input: {input}\nOutput: {output}",
)# 这是一个假设任务(创建反义词)的许多示例。
examples = [{"input": "happy", "output": "sad"},{"input": "tall", "output": "short"},{"input": "energetic", "output": "lethargic"},{"input": "sunny", "output": "gloomy"},{"input": "windy", "output": "calm"},
]
# 这些是虚构的翻译任务的示例。
examples = [{"input": "See Spot run.", "output": "Ver correr a Spot."},{"input": "My dog barks.", "output": "Mi perro ladra."},{"input": "Spot can run.", "output": "Spot puede correr."},
]example_prompt = PromptTemplate(input_variables=["input", "output"],template="Input: {input}\nOutput: {output}",
)example_selector = NGramOverlapExampleSelector(# 这些是可供选择的示例。examples=examples, # 用于格式化示例的 PromptTemplate。example_prompt=example_prompt, # 选择器停止的阈值分数。# 默认值为 -1.0。threshold=-1.0,# 对于负阈值:# 选择器按照 ngram 重叠得分对示例进行排序,不排除任何示例。# 对于大于 1.0 的阈值:# 选择器排除所有示例,并返回一个空列表。# 对于等于 0.0 的阈值:# 选择器根据 ngram 重叠得分对示例进行排序,# 并排除与输入没有 ngram 重叠的示例。
)
dynamic_prompt = FewShotPromptTemplate(# 我们提供 ExampleSelector 而不是示例。example_selector=example_selector,example_prompt=example_prompt,prefix="给出每个输入的西班牙语翻译",suffix="输入:{sentence}\n输出:", input_variables=["sentence"],
)# 一个与“Spot can run.”有较大ngram重叠的示例输入
# 与“My dog barks.”没有重叠
print(dynamic_prompt.format(sentence="Spot can run fast."))

输出:

Give the Spanish translation of every inputInput: Spot can run.
Output: Spot puede correr.Input: See Spot run.
Output: Ver correr a Spot.Input: My dog barks.
Output: Mi perro ladra.Input: Spot can run fast.
Output:

我们还可以向NGramOverlapExampleSelector添加示例:

new_example = {"input": "Spot plays fetch.", "output": "Spot juega a buscar."}example_selector.add_example(new_example)
print(dynamic_prompt.format(sentence="Spot can run fast."))

输出:

Give the Spanish translation of every inputInput: Spot can run.
Output: Spot puede correr.Input: See Spot run.
Output: Ver correr a Spot.Input: Spot plays fetch.
Output: Spot juega a buscar.Input: My dog barks.
Output: Mi perro ladra.Input: Spot can run fast.
Output:

我们还以设置一个阈值,决定哪些示例会被排除:

# 例如,将阈值设为0.0
# 会排除与输入没有ngram重叠的示例。
# 因为"My dog barks.""Spot can run fast."没有ngram重叠,
# 所以它被排除在外。
example_selector.threshold=0.0
print(dynamic_prompt.format(sentence="Spot can run fast."))

输出:

Give the Spanish translation of every inputInput: Spot can run.
Output: Spot puede correr.Input: See Spot run.
Output: Ver correr a Spot.Input: Spot plays fetch.
Output: Spot juega a buscar.Input: Spot can run fast.
Output:

我们也可以设置一个小的非零阈值:

example_selector.threshold=0.09
print(dynamic_prompt.format(sentence="Spot can play fetch."))

输出:

Give the Spanish translation of every inputInput: Spot can run.
Output: Spot puede correr.Input: Spot plays fetch.
Output: Spot juega a buscar.Input: Spot can play fetch.
Output:

我们再尝试设置大于1.0的阈值:

example_selector.threshold=1.0+1e-9
print(dynamic_prompt.format(sentence="Spot can play fetch."))
Give the Spanish translation of every input

输出:

Input: Spot can play fetch.
Output:

相似性示例选择器

语义相似性示例选择器根据输入与示例的相似性选择示例,它通过找到具有最大余弦相似度的嵌入的示例来实现这一点:

from langchain.prompts.example_selector import SemanticSimilarityExampleSelector
from langchain.vectorstores import Chroma
from langchain.embeddings import OpenAIEmbeddings
from langchain.prompts import FewShotPromptTemplate, PromptTemplateexample_prompt = PromptTemplate(input_variables=["input", "output"],template="Input: {input}\nOutput: {output}",
)

以下是一个虚构任务的许多示例,用于创建反义词:

examples = [{"input": "happy", "output": "sad"},{"input": "tall", "output": "short"},{"input": "energetic", "output": "lethargic"},{"input": "sunny", "output": "gloomy"},{"input": "windy", "output": "calm"},
]

使用这些示例,可以创建一个语义相似性示例选择器:

example_selector = SemanticSimilarityExampleSelector.from_examples(# 这是可供选择的示例列表。examples,# 这是用于生成嵌入的嵌入类,用于衡量语义相似性。OpenAIEmbeddings(),# 这是用于存储嵌入并进行相似性搜索的VectorStore类。Chroma,# 这是要生成的示例数量。k=1
)similar_prompt = FewShotPromptTemplate(# 我们提供了一个ExampleSelector而不是示例列表。example_selector=example_selector,example_prompt=example_prompt,prefix="给出每个词的反义词",suffix="输入:{adjective}\n输出:",input_variables=["adjective"],
)

通过使用这个示例选择器,我们可以根据输入的相似性来选择示例,并将其应用于生成反义词的问题:

Running Chroma using direct local API.
Using DuckDB in-memory for database. Data will be transient.

输入worried是一种情感,因此应选择happy/sad示例:

print(similar_prompt.format(adjective="worried"))

输出:

给出每个词的反义词输入:happy
输出:sad输入:worried
输出:

输入fat是一种度量,因此应选择tall/short示例:

print(similar_prompt.format(adjective="fat"))

输出:

给出每个词的反义词输入:happy
输出:sad输入:fat
输出:

我们还可以将新示例添加到SemanticSimilarityExampleSelector中:

similar_prompt.example_selector.add_example({"input": "enthusiastic", "output": "apathetic"})
print(similar_prompt.format(adjective="joyful"))

输出:

给出每个词的反义词输入:happy
输出:sad输入:joyful
输出:

参考文献:
[1] LangChain官方网站:https://www.langchain.com/
[2] LangChain 🦜️🔗 中文网,跟着LangChain一起学LLM/GPT开发:https://www.langchain.com.cn/
[3] LangChain中文网 - LangChain 是一个用于开发由语言模型驱动的应用程序的框架:http://www.cnlangchain.com/

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/25189.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

爬虫获取电影数据----以沈腾参演电影为例

数据可视化&分析实战 1.1 沈腾参演电影数据获取 文章目录 数据可视化&分析实战前言1. 网页分析2. 构建数据获取函数2.1 网页数据获取函数2.2 网页照片获取函数 3. 获取参演影视作品基本数据4. 电影详细数据获取4.1 导演、演员、描述、类型、投票人数、评分信息、电影海…

Wisej.NET Crack,Wisej.NET的核心功能

Wisej.NET Crack,Wisej.NET的核心功能 Wisej.NET是一个跨平台的web框架,用于使用.NET和C#/VB.NET而不是HTML和JavaScript构建现代HTML5应用程序。它包含创建任务关键型web应用程序所需的一切,包括UI组件、会话处理、状态管理和后端集成。借助…

单元测试之 - Spring框架提供的单元/集成测试注解

Spring框架提供了很多注解来辅助完成单元测试和集成测试(备注:这里的集成测试指容器内部的集成测试,非系统间的集成测试),先看看Spring框架提供了哪些注解以及对应的作用。RunWith(SpringRunner.class) / ExtendWith(SpringExtension.class)&…

设计模式行为型——备忘录模式

目录 什么是备忘录模式 备忘录模式的实现 备忘录模式角色 备忘录模式类图 备忘录模式举例 备忘录模式代码实现 备忘录模式的特点 优点 缺点 使用场景 注意事项 实际应用 什么是备忘录模式 备忘录模式(Memento Pattern)又叫做快照模式&#x…

高并发负载均衡---LVS

目录 前言 一:负载均衡概述 二:为啥负载均衡服务器这么快呢? ​编辑 2.1 七层应用程序慢的原因 2.2 四层负载均衡器LVS快的原因 三:LVS负载均衡器的三种模式 3.1 NAT模式 3.1.1 什么是NAT模式 3.1.2 NAT模式实现LVS的缺点…

openwr折腾记7-Frpc使用自主域名解析透传本地服务免费不断线的探索

Frpc使用自主域名解析透传本地服务 综述frp透传http服务结构流程 第一部分openwrt-frpc客户端配置和使用指定服务器指定规则在自己的域名运营商处添加域名解析 第二部分shell编码实现frp自由切换服务器并更新dns解析获取切换服务器参数脚本实现切换脚本更新DNS解析打开openwrt计…

MySQL — InnoDB事务

文章目录 事务定义事务特性事务隔离级别READ UNCOMMITTEDREPEATABLE READREAD COMMITTEDSERIALIZABLE 事务存在的问题脏读(Dirty Read)不可重复读(Non-repeatable Read)幻读(Phantom Read) 事务定义 数据库…

Android Handler 的基本使用

1.前言 https://developer.android.google.cn/reference/android/os/Handler.html Handler 是 Android 中线程通信的常用方式,文档如是说: A Handler allows you to send and process Message and Runnable objects associated with a threads Message…

(十三)大数据实战——hadoop集群之YARN高可用实现自动故障转移

前言 本节内容是关于hadoop集群下yarn服务的高可用搭建,以及其发生故障转移的处理,同样需要依赖zookeeper集群的实现,实现该集群搭建时,我们要预先保证zookeeper集群是启动状态。yarn的高可用同样依赖zookeeper的临时节点及监控&…

构建器/建造者/构建者模式(C++)

定义 将一个复杂对象的构建与其表示相分离,使得同样的构建过程(稳定)可以创建不同的表示(变化)。 应用场景 在软件系统中,有时候面临着“一个复杂对象”的创建工作,其通常由各个部分的子对象用一定的算法构成;由于需求的变化,这个复杂对象…

淘宝API开发(一)简单介绍淘宝API功能接口作用

前一阵子按照上级指示,根据淘宝API开发符合自已应用的系统,比如批量上传,批量修改名称,价格等功能什么的,在此就将我的开发历程写一写,为自己前段时间的工作做个总结。 淘宝开发平台(淘宝网 - 淘&#xff…

Android应用开发(6)TextView进阶用法

Android应用开发学习笔记——目录索引 上一章Android应用开发(5)文本视图(TextView)介绍了文本视图(TextView)设置文本内容、设置文本大小、设置文本显示颜色。 TextView是最基础的文本显示控件&#xff…

PHP正则绕过解析

正则绕过 正则表达式PHP正则回溯PHP中的NULL和false回溯案例案例1案例2 正则表达式 在正则中有许多特殊的字符,不能直接使用,需要使用转义符\。如:$,(,),*,,.,?,[,,^,{。 这里大家会有疑问:为啥小括号(),这个就需要两个来转义&a…

Linux 下设置开机自启动的方法

文章目录 事先准备对于普通的 Linux对于 RedHat Enterprise Linux 9 笔者的运行环境: 设置成功过的 Linux: RedHat Enterprise Linux 9 x86_64 CentOS 8 x86_64 事先准备 进行这个教程之前,必须要先安装好一个 Linux 操作系统。这个 Linux…

JavaWeb 手写Tomcat底层机制

目录 一、Tomcat底层整体架构 1.简介 : 2.分析图 : 3.基于Socket开发服务端的流程 : 4.打通服务器端和客户端的数据通道 : 二、多线程模型的实现 1.思路分析 : 2.处理HTTP请求 : 3.自定义Tomcat : 三、自定义Servlet规范 1. HTTP请求和响应 : 1 CyanServletRequest …

《面试1v1》ElasticSearch基础

🍅 作者简介:王哥,CSDN2022博客总榜Top100🏆、博客专家💪 🍅 技术交流:定期更新Java硬核干货,不定期送书活动 🍅 王哥多年工作总结:Java学习路线总结&#xf…

工厂方法模式

工厂模式(Factory Pattern)是一种创建型设计模式,它提供了一种统一的接口来创建对象,但将对象的实例化延迟到子类中。工厂模式主要解决了对象的创建过程与使用客户端代码的解耦,使得客户端代码不需要知道具体的对象创建…

Kafka的配置和使用

目录 1.服务器用docker安装kafka 2.springboot集成kafka实现生产者和消费者 1.服务器用docker安装kafka ①、安装docker(docker类似于linux的软件商店,下载所有应用都能从docker去下载) a、自动安装 curl -fsSL https://get.docker.com | b…

Visual Studio配置PCL库

Visual Studio配置PCL库 Debug和Release配置新建项目配置属性表测试参考 Debug和Release Debug和Release的配置过程一模一样,唯一区别就在于最后一步插入的附加依赖项不同,因此下面以debug为例。 配置新建项目 1、新建一个C空项目,模式设置…

Linux文本三剑客之awk

目录 前言 awk 1.认识awk 2.使用awk 2.1语法 2.2常用命令选项 2.3awk变量 2.3.1内置变量 2.3.2自定义变量 2.4printf命令 awk例题 前言 awk、grep、sed是linux操作文本的三大利器,合称文本三剑客,也是必须掌握的linux命令之一。三者的功能都是…