LangChain学习之 Question And Answer的操作

1. 学习背景

在LangChain for LLM应用程序开发中课程中,学习了LangChain框架扩展应用程序开发中语言模型的用例和功能的基本技能,遂做整理为后面的应用做准备。视频地址:基于LangChain的大语言模型应用开发+构建和评估。

2. Q&A的作用

基于文档的问答系统是LLM的典型应用,给定一段可能从PDF文件、网页或某公司的内部文档库中提取的文本,可以使用LLM检索文档对问题进行回答。以下代码基于jupyternotebook运行。

1.导入环境

import osfrom dotenv import load_dotenv, find_dotenv
_ = load_dotenv(find_dotenv()) # read local .env file
from langchain.chains import RetrievalQA
from langchain.chat_models import ChatOpenAI
from langchain.document_loaders import CSVLoader
from langchain.vectorstores import DocArrayInMemorySearch
from IPython.display import display, Markdown

2.2 读取数据进行查询

from langchain.indexes import VectorstoreIndexCreator
# 没有docarray环境需要安装。命令:!pip install docarray# 要用到的数据文件
file = 'OutdoorClothingCatalog_1000.csv'
loader = CSVLoader(file_path=file, encoding='utf-8')# 此处我们已完成了文档的向量存储
index = VectorstoreIndexCreator(vectorstore_cls=DocArrayInMemorySearch).from_loaders([loader])# 创建提问语句
query ="Please list all your shirts with sun protection in a table in markdown and summarize each one."# 传入query内容,使用index生成响应
response = index.query(query)# 以markdown方式进行呈现,注意LLM生成的样式可能存在差异
display(Markdown(response))

输出如下:

NameDescriptionSun Protection Rating
Men’s Tropical Plaid Short-Sleeve ShirtMade of 100% polyester, UPF 50+ rating, front and back cape venting, two front bellows pocketsSPF 50+, blocks 98% of harmful UV rays
Men’s Plaid Tropic Shirt, Short-SleeveMade of 52% polyester and 48% nylon, UPF 50+ rating, front and back cape venting, two front bellows pocketsSPF 50+, blocks 98% of harmful UV rays
Men’s TropicVibe Shirt, Short-SleeveMade of 71% nylon and 29% polyester, UPF 50+ rating, front and back cape venting, two front bellows pocketsSPF 50+, blocks 98% of harmful UV rays
Sun Shield ShirtMade of 78% nylon and 22% Lycra Xtra Life fiber, UPF 50+ rating, wicks moisture, abrasion resistantSPF 50+, blocks 98% of harmful UV rays

All four shirts provide UPF 50+ sun protection, blocking 98% of the sun’s harmful rays. The Men’s Tropical Plaid Short-Sleeve Shirt is made of 100% polyester and is wrinkle-resistant。

至此,内容已经查出来了,并生成了一小段总结的话。那么底层的原理又是什么呢?

2.3 底层原理

2.3.1向量化

一般的大模型一次只能接收几千个单词,如图:
在这里插入图片描述
如果有个很大的文档,我们要怎样让LLM对文档进行问答呢?这里就需要Embedding和向量存储发挥作用了。
在这里插入图片描述
什么是Embedding?Embedding将一段文本转换成数字,用一组数字表示这段文本。这组数字捕捉了它所代表的文字片段的肉容含义。内容相似的文本片段会有相似的向量值,这样我们可以在向量空间中比较文本片段。例如,我们有三段话:

  1. My dog Rover likes to chase squirrels.
  2. Fluffy, my cat, refuses to eat from a can.
  3. The Chevy Bolt accelerates to 60 mph in 6.7 seconds.

三段话前两个描述宠物,第三个描述汽车,向量化后如图:
在这里插入图片描述
如果我们观察数值空间中的表示,可以看到当我们比较关于两个关于宠物的句子的向量时,它们相似度非常高。将其与汽车相关的语句进行比对,可以看到相关程度非常低。利用向量可以很轻松的让我们找出哪些片段是相似的。利用这种技术,我们可以从文档中找出与提问相似的片段,传递给LLM进行解答。

2.3.2向量数据库

在这里插入图片描述
向量数据库是一种存储方法,可以存储我们在前面创建的那种矢量数字数组。往向量数据库中新建数据的方式,就是将文档拆分成块,每块生成Embedding,然后把Embedding和原始块一起存储到数据库中。

因为有些大文档无法整个传给文档,因此要先切块,然后只把最相关的内容存入,然后,把每个文本块生成一个Embedding,然后将这些Embedding存储在向量数据库中。如图:
在这里插入图片描述
当查询过来,我们先将查询内容embedding,得到一个数组,然后将这个数字数组与向量数据库中的所有向量进行比较,选择最相似的前若干个文本块。

拿到这些文本块后,将这些文本块和原始的查询内容一起传递给语言模型,这样可以让语言模型根据检索出来的文档内容生成最终答案。

2.4 再了解底层原理

loader = CSVLoader(file_path=file, encoding='utf-8')
docs = loader.load()
docs[0]

输出如下:

Document(page_content=": 0\nname: Women's Campside Oxfords\ndescription: This ultracomfortable lace-to-toe Oxford boasts a super-soft canvas, thick cushioning, and quality construction for a broken-in feel from the first time you put them on. \n\nSize & Fit: Order regular shoe size. For half sizes not offered, order up to next whole size. \n\nSpecs: Approx. weight: 1 lb.1 oz. per pair. \n\nConstruction: Soft canvas material for a broken-in feel and look. Comfortable EVA innersole with Cleansport NXT® antimicrobial odor control. Vintage hunt, fish and camping motif on innersole. Moderate arch contour of innersole. EVA foam midsole for cushioning and support. Chain-tread-inspired molded rubber outsole with modified chain-tread pattern. Imported. \n\nQuestions? Please contact us for any inquiries.", metadata={'source': 'OutdoorClothingCatalog_1000.csv', 'row': 0})

接着

# 使用OpenAIEmbeddings完成embedding
from langchain.embeddings import OpenAIEmbeddings
embeddings = OpenAIEmbeddings()
#使用embed_query模拟生成embeddings向量
embed = embeddings.embed_query("Hi my name is Harrison")
print(len(embed))
print(embed[:5])

输出如下:

1536[-0.021900920197367668, 0.006746490020304918, -0.018175246194005013, -0.039119575172662735, -0.014097143895924091]

可以看到,embedding向量的长度为1536,数组的前五个向量如上。

# 接着我们将刚刚加载的所有文本片段生成Embedding,并将它们存储在一个向量数据库中
db = DocArrayInMemorySearch.from_documents(docs, embeddings
)
# 创建对话查询语句
query = "Please suggest a shirt with sunblocking"
# 向量数据库中使用similarity_search方法得到查询的文档列表
docs = db.similarity_search(query)
print(len(docs))
print(docs[0])

输出如下:

4
Document(page_content=': 255\nname: Sun Shield Shirt by\ndescription: "Block the sun, not the fun – our high-performance sun shirt is guaranteed to protect from harmful UV rays. \n\nSize & Fit: Slightly Fitted: Softly shapes the body. Falls at hip.\n\nFabric & Care: 78% nylon, 22% Lycra Xtra Life fiber. UPF 50+ rated – the highest rated sun protection possible. Handwash, line dry.\n\nAdditional Features: Wicks moisture for quick-drying comfort. Fits comfortably over your favorite swimsuit. Abrasion resistant for season after season of wear. Imported.\n\nSun Protection That Won\'t Wear Off\nOur high-performance fabric provides SPF 50+ sun protection, blocking 98% of the sun\'s harmful rays. This fabric is recommended by The Skin Cancer Foundation as an effective UV protectant.', metadata={'source': 'OutdoorClothingCatalog_1000.csv', 'row': 255})

可以看到,得到了4个相关的文档列表内容,第一个内容如上所示。

2.5 如何利用这个来回答得到提问的结果

# 首先,需要从这个向量存储器创建一个检索器(Retriever)
retriever = db.as_retriever()
# 定义一个LLM模型
llm = ChatOpenAI(temperature = 0.0)
# 手动将检索出来的内容合并成一段话
qdocs = "".join([docs[i].page_content for i in range(len(docs))])
# 将提问和检索出来的内容一起交给LLM,并让其生成一段摘要
response = llm.call_as_llm(f"{qdocs} Question: Please list all your \
shirts with sun protection in a table in markdown and summarize each one.") 
display(Markdown(response))

输出如下:

NameDescription
Sun Shield ShirtHigh-performance sun shirt with UPF 50+ sun protection, moisture-wicking, and abrasion-resistant fabric. Fits comfortably over swimsuits. Recommended by The Skin Cancer Foundation.
Men’s Plaid Tropic ShirtUltracomfortable shirt with UPF 50+ sun protection, wrinkle-free fabric, and front/back cape venting. Made with 52% polyester and 48% nylon.
Men’s TropicVibe ShirtMen’s sun-protection shirt with built-in UPF 50+ and front/back cape venting. Made with 71% nylon and 29% polyester.
Men’s Tropical Plaid Short-Sleeve ShirtLightest hot-weather shirt with UPF 50+ sun protection, front/back cape venting, and two front bellows pockets. Made with 100% polyester and is wrinkle-resistant.

All of these shirts provide UPF 50+ sun protection, blocking 98% of the sun’s harmful rays. They are made with high-performance fabrics that are moisture-wicking, abrasion-resistant, and/or wrinkle-free. Some have front/back cape venting for added comfort in hot weather. The Sun Shield Shirt is recommended by The Skin Cancer Foundation.

2.6使用langchain进行封装运行

qa_stuff = RetrievalQA.from_chain_type(llm=llm, chain_type="stuff", retriever=retriever, verbose=True
)
query =  "Please list all your shirts with sun protection in a table in markdown and summarize each one."
response = qa_stuff.run(query)

输出如下:

Shirt NameDescription
Men’s Tropical Plaid Short-Sleeve ShirtRated UPF 50+ for superior protection from the sun’s UV rays. Made of 100% polyester and is wrinkle-resistant. With front and back cape venting that lets in cool breezes and two front bellows pockets. Provides the highest rated sun protection possible.
Men’s Plaid Tropic Shirt, Short-SleeveRated to UPF 50+, helping you stay cool and dry. Made with 52% polyester and 48% nylon, this shirt is machine washable and dryable. Additional features include front and back cape venting, two front bellows pockets and an imported design. With UPF 50+ coverage, you can limit sun exposure and feel secure with the highest rated sun protection available.
Men’s TropicVibe Shirt, Short-SleeveBuilt-in UPF 50+ has the lightweight feel you want and the coverage you need when the air is hot and the UV rays are strong. Made with Shell: 71% Nylon, 29% Polyester. Lining: 100% Polyester knit mesh. Wrinkle resistant. Front and back cape venting lets in cool breezes. Two front bellows pockets. Imported.
Sun Shield ShirtHigh-performance sun shirt is guaranteed to protect from harmful UV rays. Made with 78% nylon, 22% Lycra Xtra Life fiber. Fits comfortably over your favorite swimsuit. Abrasion resistant for season after season of wear.

All of the shirts listed have sun protection with a UPF rating of 50+ and block 98% of the sun’s harmful rays. The Men’s Tropical Plaid Short-Sleeve Shirt is made of 100% polyester and has front and back cape venting and two front bellows pockets. The Men’s Plaid Tropic Shirt, Short-Sleeve is made with 52% polyester and 48% nylon and has front and back cape venting and two front bellows pockets. The Men’s TropicVibe Shirt, Short-Sleeve is made with Shell: 71% Nylon, 29% Polyester. Lining: 100% Polyester knit mesh and has front and back cape venting and two front bellows pockets. The Sun Shield Shirt is made with 78% nylon, 22% Lycra Xtra Life fiber and fits comfortably over your favorite swimsuit.

同样的,我们尝试用index.query也会得到同样的内容。

response = index.query(query, llm=llm)

输出结果和之前的一致

3.总结

Q&A可以用一行代码完成,也可以把它分成五个详细的步骤,可以查看每一步的详细结果。五个步骤可以详细的让我们理解到它底层到底是如何执行的。此外,chain_type="stuff" 参数还有其他三种,可以根据实际情况选取合适的参数,另外三种如图,有需要可以根据实际情况选取合适的参数进行实验。
在这里插入图片描述

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

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

相关文章

07-使用 JavaScript Promise 并行处理多个请求

使用 JavaScript Promise 并行处理多个请求 笔记分享 在现代Web开发中,处理多个异步请求并行是一个常见需求。JavaScript中的Promise提供了一种强大的机制来管理这些并行操作。本文将详细介绍如何使用Promise.all和Promise.allSettled来实现这一点,并提…

Echarts 中type是value的X轴在设置了interval间隔后没有展示

文章目录 问题分析问题 Echarts中type是value的X轴在设置了interval间隔后没有展示 分析 之前代码是这样写的:axisLabel 属性中设置了 interval ,但未起作用,原因如下 在 ECharts 中,interval 属性是用于类目型(category)轴的刻度间隔设置,并不适用于数值型(value)…

音视频视频点播

视频点播是集音视频采集,编辑,上传,自动化转码处理,媒体资源管理,高效云剪辑处理,分发加速,视频播放于一体的一站式音视频点播解决方案 阿里云视频点播基于阿里云强大的基础设施服务&#xff0c…

解决 clickhouse jdbc 偶现 failed to respond 问题

背景 Clickhouse集群版本为 Github Clickhouse 22.3.5.5, clickhouse-jdbc 版本为 0.2.4。 问题表现 随着业务需求的扩展,基于Clickhouse 需要支持更多任务在期望的时效内完成,于是将业务系统和Clickhouse交互的部分都提交给可动态调整核心…

【西瓜书】1.绪论

1.基本术语 (1)数据集不带最后一列:样本/示例/特征向量 带最后一列:样例 (2)表头不带最后一列:属性/特征,属性空间/特征空间/样本空间/输入空间 表头最后一列:标记/输出…

windows上安装MongoDB,springboot整合MongoDB

上一篇文章已经通过在Ubuntu上安装MongoDB详细介绍了MongoDB的各种命令用法。 Ubuntu上安装、使用MongoDB详细教程https://blog.csdn.net/heyl163_/article/details/133781878 这篇文章介绍一下在windows上安装MongoDB,并通过在springboot项目中使用MongoDB记录用户…

Go语言交叉编译

Golang 支持交叉编译, 在一个平台上生成然后再另外一个平台去执行。 以下面代码为例 build ├── main.go ├── go.mod main.go内容 package mainimport "fmt"func main() {fmt.Println("hello world") }windows系统上操作 1.cmd窗口编译…

java新特性--03-1--Stream---Collectors工具类

提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档 文章目录 1.stream 收集Collectors工具类注意区分 Collections工具类 练习1:查找工资大于6000的员工,结果返回为一个List练习2:查找年龄小…

【含项目亮点】小免鲜项目总结

【含项目亮点】小兔鲜项目总结 基础总结 vue3的优势 组合式API,更好的支持TS。速度提高,diff算法重写。按需引入,更好的treeshaking,体积小。数据式响应更优,使用js的proxy替代Object.defineProperty数据响应式系统,更灵活。 vue3使用的是vue-create脚手架工具,vue2使用…

【设计模式】结构型-组合模式

前言 在软件开发中,设计模式是一种被广泛应用的解决问题的方法论。其中,结构性设计模式是一类特别重要的模式,它们用于处理类或对象之间的组合关系,其中之一就是组合模式。组合模式允许客户端统一对待单个对象和对象的组合&#…

结构体(2),链表,共用体

链式数据结构 -- 链表 定义: struct Node { int data; //数据域 --存储要处理的数据 struct Node *next; //指针域,保存地址-- 指向下一个节点 }; //数据域指针域 //节点类型 struct Node n1; struct Node n2; struct Node n3; s1--&…

DeepSort整体流程梳理及匈牙利算法解析

文章目录 算法原理一、主要步骤二、算法流程:三、匈牙利算法:3.1 举例说明匈牙利匹配过程:3.2匈牙利算法中代价矩阵的计算(距离)卡尔曼滤波后面更新。 算法原理 DeepSort核心在于其对目标的外观特征和运动特征的联合使用,以及对目标匹配问题的优化处理。该算法通过融合目…

【前端技术】 ES6 介绍及常用语法说明

😄 19年之后由于某些原因断更了三年,23年重新扬帆起航,推出更多优质博文,希望大家多多支持~ 🌷 古之立大事者,不惟有超世之才,亦必有坚忍不拔之志 🎐 个人CSND主页——Mi…

使用wheelnav.js构建酷炫的动态导航菜单

目录 前言 一、WheelNav是什么 1、项目地址 2、关于开源协议 3、相关目录介绍 二、如何使用wheelnav.js 1、新建html页面 2、设置style样式 3、创建展示元素实现动态导航 三、参数即方法介绍 1、参数列表 2、运行方法 3、实际成果 四、总结 前言 用户体验永远是一…

玩转盲盒潮流:从0到1搭建小程序平台

玩转盲盒潮流并搭建一个从0到1的小程序平台来创作内容是一个充满挑战但有趣的过程。以下是一个步骤指南,帮助你实现这一目标: 1. 市场调研与定位 了解盲盒市场:研究当前盲盒市场的趋势、消费者喜好和成功案例。确定目标用户:明确…

android-jni2

详细的jni调用说明:Android学习--JNI_android jni-CSDN博客 jclass clazz;index;LOGE("开始:%d", "begin");clazz (*env).FindClass("com/changan/incalleventservice/input/NativeAction");//找到对应的java文件jfieldID instanc…

docker-compose 部署rabbitmq 15672打不开

docker-compose 部署rabbitmq 15672打不开 如果docker-compose的rabbitmq镜像后缀不是-management如:3.7.4-management,则需要进入容器中手动启动插件 部署rabbitmq后需要启动插件的命令: rabbitmq-plugins enable rabbitmq_management 一…

软件质量保障——三、四

三、黑盒测试 1.黑盒测试概述 1.1 如何理解黑盒测试? 1.2 黑盒测试有什么特点? 1.3 如何实施黑盒测试? 2. 黑盒测试用例设计和生成方法(这里还是要自己找题做) 2.1 等价类划分法 步骤: 1.选择划分准…

解释JDBC的作用和连接数据库的步骤

JDBC(Java Database Connectivity)是Java编程语言中用来执行SQL语句的API。它的主要作用是为Java程序提供连接各种关系型数据库的能力,使得Java开发者能够编写出与数据库进行交互的应用程序。JDBC的作用具体体现在以下几个方面: 数…

在多支付渠道中这个设计模式无敌好用!

假设我们有一个电商平台,需要支持多种支付方式。 通过策略模式来实现,管理不同的支付方式,并根据需求快速添加新的支付方式。 定义支付策略接口及其实现类: // 支付策略接口 public interface PaymentStrategy { void pay(int …