LangChain检索链

环境搭建

下载:https://ollama.com/download

双击安装,一直下一步即可。

启动:

ollama run llama2

在这一步的时候,如果本地没有这个模型,可能会联网下载模型。模型一般都比较大,要根据自己的电脑实际配置去选择模型。

安装依赖

创建虚拟环境

创建虚拟环境:

conda create --name zdppy_langchainx python==3.11.7

激活虚拟环境:

conda activate zdppy_langchainx

安装Langchain

使用conda安装:

conda install langchain -c conda-forge

实现检索链

To properly answer the original question (“how can langsmith help with testing?”), we need to provide additional context to the LLM. We can do this via retrieval. Retrieval is useful when you have too much data to pass to the LLM directly. You can then use a retriever to fetch only the most relevant pieces and pass those in.

为了正确回答最初的问题(“langsmith如何帮助测试?”),我们需要为LLM提供额外的背景。我们可以通过检索来实现。当您有太多的数据需要直接传递给LLM时,检索非常有用。然后,您可以使用检索器只获取最相关的部分并将它们传递进去。

In this process, we will look up relevant documents from a Retriever and then pass them into the prompt. A Retriever can be backed by anything - a SQL table, the internet, etc - but in this instance we will populate a vector store and use that as a retriever. For more information on vectorstores, see this documentation.

在这个过程中,我们将从猎犬中查找相关文档,然后将它们传递给提示符。检索器可以由任何东西支持——SQL表、互联网等——但在本例中,我们将填充一个向量存储并将其用作检索器。有关vectorstores的更多信息,请参阅本文档。

First, we need to load the data that we want to index. To do this, we will use the WebBaseLoader. This requires installing BeautifulSoup:

首先,我们需要加载要建立索引的数据。为此,我们将使用WebBaseLoader。这需要安装BeautifulSoup:

pip install beautifulsoup4

After that, we can import and use WebBaseLoader.

之后,我们可以导入和使用WebBaseLoader。

from langchain_community.document_loaders import WebBaseLoader
loader = WebBaseLoader("https://docs.smith.langchain.com/user_guide")

docs = loader.load()

WebBaseLoader API接口文档:https://api.python.langchain.com/en/latest/document_loaders/langchain_community.document_loaders.web_base.WebBaseLoader.html

Next, we need to index it into a vectorstore. This requires a few components, namely an embedding model and a vectorstore.

接下来,我们需要将其索引到vectorstore中。这需要一些组件,即嵌入模型和vectorstore。

For embedding models, we once again provide examples for accessing via API or by running local models.

对于嵌入模型,我们再次提供了通过API或运行本地模型进行访问的示例。

Make sure you have Ollama running (same set up as with the LLM).

确保Ollama正在运行(与LLM的设置相同)。

from langchain_community.embeddings import OllamaEmbeddings

embeddings = OllamaEmbeddings()

OllamaEmbeddings API接口文档:https://api.python.langchain.com/en/latest/embeddings/langchain_community.embeddings.ollama.OllamaEmbeddings.html

Now, we can use this embedding model to ingest documents into a vectorstore. We will use a simple local vectorstore, FAISS, for simplicity’s sake.

现在,我们可以使用这个嵌入模型将文档摄取到vectorstore中。为了简单起见,我们将使用一个简单的本地向量库FAISS。

First we need to install the required packages for that:

首先,我们需要安装所需的软件包:

pip install faiss-cpu

Then we can build our index:

然后我们可以建立索引:

from langchain_community.vectorstores import FAISS
from langchain_text_splitters import RecursiveCharacterTextSplitter


text_splitter = RecursiveCharacterTextSplitter()
documents = text_splitter.split_documents(docs)
vector = FAISS.from_documents(documents, embeddings)

FAISS 接口文档:https://api.python.langchain.com/en/latest/vectorstores/langchain_community.vectorstores.faiss.FAISS.html

RecursiveCharacterTextSplitter 接口文档:https://api.python.langchain.com/en/latest/character/langchain_text_splitters.character.RecursiveCharacterTextSplitter.html

Now that we have this data indexed in a vectorstore, we will create a retrieval chain. This chain will take an incoming question, look up relevant documents, then pass those documents along with the original question into an LLM and ask it to answer the original question.

现在我们已经在vectorstore中为这些数据建立了索引,我们将创建一个检索链。该链将接收传入的问题,查找相关文档,然后将这些文档与原始问题一起传递给LLM,并要求它回答原始问题。

First, let’s set up the chain that takes a question and the retrieved documents and generates an answer.

首先,让我们设置接受问题和检索文档并生成答案的链。

from langchain.chains.combine_documents import create_stuff_documents_chain

prompt = ChatPromptTemplate.from_template("""Answer the following question based only on the provided context:

<context>
{context}
</context>

Question: {input}""")

document_chain = create_stuff_documents_chain(llm, prompt)

If we wanted to, we could run this ourselves by passing in documents directly:

如果我们愿意,我们可以通过直接传入文档来运行它:

from langchain_core.documents import Document

document_chain.invoke({
    "input": "how can langsmith help with testing?",
    "context": [Document(page_content="langsmith can let you visualize test results")]
})

此时的完整代码如下:

from langchain_core.prompts import ChatPromptTemplate
from langchain.chains.combine_documents import create_stuff_documents_chain
from langchain_core.output_parsers import StrOutputParser
from langchain_community.llms import Ollama
from langchain_community.document_loaders import WebBaseLoader
from langchain_community.embeddings import OllamaEmbeddings
from langchain_community.vectorstores import FAISS
from langchain_text_splitters import RecursiveCharacterTextSplitter
from langchain_core.documents import Document

"""
Github: https://github.com/zhangdapeng520/zdppy_langchainx
file: study/official_doc/c04_retraivel_chain.py
"""

# 创建模型对象
llm = Ollama(model="llama2")

# 构建提示词
prompt = ChatPromptTemplate.from_template("""Answer the following question based only on the provided context:

<context>
{context}
</context>

Question: {input}""")

# 将结果解析为字符串
output_parser = StrOutputParser()

# 构建web加载器对象
loader = WebBaseLoader("https://docs.smith.langchain.com/user_guide")
docs = loader.load()

# 创建嵌入对象
embeddings = OllamaEmbeddings()

# 建立索引
text_splitter = RecursiveCharacterTextSplitter()
documents = text_splitter.split_documents(docs)
vector = FAISS.from_documents(documents, embeddings)

# 构建链条
document_chain = create_stuff_documents_chain(llm, prompt)

# 接着,使用链条和大模型聊天
response = document_chain.invoke({
    "input": "how can langsmith help with testing?",
    "context": [Document(page_content="langsmith can let you visualize test results")]
})
print(response)

However, we want the documents to first come from the retriever we just set up. That way, we can use the retriever to dynamically select the most relevant documents and pass those in for a given question.

但是,我们希望文档首先来自我们刚刚设置的检索器。这样,我们就可以使用检索器动态地选择最相关的文档,并为给定的问题传递这些文档。

from langchain.chains import create_retrieval_chain

retriever = vector.as_retriever()
retrieval_chain = create_retrieval_chain(retriever, document_chain)

We can now invoke this chain. This returns a dictionary - the response from the LLM is in the answer key

现在我们可以调用这个链。这将返回一个字典——LLM的响应在’ answer '键中

response = retrieval_chain.invoke({"input": "how can langsmith help with testing?"})
print(response["answer"])

# LangSmith offers several features that can help with testing:...

This answer should be much more accurate!

这个答案应该准确得多!

此时的完整代码如下:

from langchain_core.prompts import ChatPromptTemplate
from langchain.chains.combine_documents import create_stuff_documents_chain
from langchain.chains import create_retrieval_chain
from langchain_core.output_parsers import StrOutputParser
from langchain_community.llms import Ollama
from langchain_community.document_loaders import WebBaseLoader
from langchain_community.embeddings import OllamaEmbeddings
from langchain_community.vectorstores import FAISS
from langchain_text_splitters import RecursiveCharacterTextSplitter

"""
Github: https://github.com/zhangdapeng520/zdppy_langchainx
file: study/official_doc/c04_retraivel_chain.py
"""

# 创建模型对象
llm = Ollama(model="llama2")

# 构建提示词
prompt = ChatPromptTemplate.from_template("""Answer the following question based only on the provided context:

<context>
{context}
</context>

Question: {input}""")

# 将结果解析为字符串
output_parser = StrOutputParser()

# 构建web加载器对象
loader = WebBaseLoader("https://docs.smith.langchain.com/user_guide")
docs = loader.load()

# 创建嵌入对象
embeddings = OllamaEmbeddings()

# 建立索引
text_splitter = RecursiveCharacterTextSplitter()
documents = text_splitter.split_documents(docs)
vector = FAISS.from_documents(documents, embeddings)

# 构建链条
document_chain = create_stuff_documents_chain(llm, prompt)

# 设置检索器
retriever = vector.as_retriever()
retrieval_chain = create_retrieval_chain(retriever, document_chain)

# 调用
response = retrieval_chain.invoke({"input": "how can langsmith help with testing?"})
print(response["answer"])

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

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

提升工作效率,用ONLYOFFICE打造高效团队协作环境

作为一名深耕技术领域已有六七年的开发者&#xff0c;同时又是断断续续进行技术创作将近六年的一个小小作者&#xff0c;我在工作和日常生活中&#xff0c;使用过各色各样的软件。 而在最近几年&#xff0c;一款名为ONLYOFFICE的开源办公套件逐渐走进并融入我的工作与生活&…

使用Vue连接Mqtt实现主题的订阅及消息发布

效果如下&#xff1a; 直接贴代码&#xff0c;本地创建一个html文件将以下内容贴入即可 <!DOCTYPE html> <html lang"zh-CN"> <head><meta charset"UTF-8"><meta name"viewport" content"widthdevice-width, …

为什么职场关系越来越冷漠?

不知道从什么时候开始&#xff0c;我们的职场关系变得越来越冷漠了。 早上上班打卡的时候&#xff0c;一个个都低着头&#xff0c;眼神紧紧盯着手机&#xff0c;生怕错过什么重要的信息&#xff1b; 下班后大家一哄而散&#xff0c;各自抱着手机“享受”生活&#xff0c;谁也…

如何添加、编辑、调整WordPress菜单

我们最近在使用WordPress建站建设公司网站。我们是使用的hostease的主机产品建设的WordPress网站。在建设网站使用遇到了一些WordPress菜单使用方面的问题。好在hostease提供了不少帮助。 下面把WordPress菜单使用心得分享一下。 本文将详细介绍WordPress菜单的各种功能&#x…

Total Store Orderand(TSO) the x86 MemoryModel

一种广泛实现的内存一致性模型是总store顺序 (total store order, TSO)。 TSO 最早由 SPARC 引入&#xff0c;更重要的是&#xff0c;它似乎与广泛使用的 x86 架构的内存一致性模型相匹配。RISC-V 还支持 TSO 扩展 RVTSO&#xff0c;部分是为了帮助移植最初为 x86 或 SPARC 架…

1-3ARM_GD32点亮LED灯

简介&#xff1a; 最多可支持 112 个通用 I/O 引脚(GPIO)&#xff0c;分别为 PA0 ~ PA15&#xff0c;PB0 ~ PB15&#xff0c;PC0 ~ PC15&#xff0c;PD0 ~ PD15&#xff0c;PE0 ~ PE15&#xff0c;PF0 ~ PF15 和 PG0 ~ PG15&#xff0c;各片上设备用其来实现逻辑输入/输出功能。…

使用DBeaver连接postgreSql提示缺少驱动

重新安装电脑之后用dbeaver链接数据库的时候&#xff0c;链接PG库一直提示缺少驱动&#xff0c;当选择下载驱动的时候又非常非常慢经常失败&#xff0c;尝试了一下更改源然后下载库驱动就非常快了&#xff0c;当然也包括dbeaver的自动更新。 方法&#xff1a;点击菜单栏【窗口…

霸榜!近期不容错过的3个AI开源项目,来了

在人工智能领域的迅速发展下&#xff0c;各种AI开源项目如雨后春笋般涌现&#xff0c;今天就来为大家介绍近期三个热门的AI开源项目&#xff0c;它们不仅技术前沿&#xff0c;而且非常实用&#xff0c;对于技术爱好者和业界专家来说&#xff0c;绝对不容错过。 一键创作漫画和视…

基于无监督学习算法的滑坡易发性评价的实施(k聚类、谱聚类、Hier聚类)

基于无监督学习算法的滑坡易发性评价的实施 1. k均值聚类2. 谱聚类3. Hier聚类4. 基于上述聚类方法的易发性实施本研究中的数据集和代码可从以下链接下载: 数据集实施代码1. k均值聚类 K-Means 聚类是一种矢量量化方法,最初来自信号处理,旨在将 N 个观测值划分为 K 个聚类,…

生信分析进阶2 - 利用GC含量的Loess回归矫正reads数量

在NGS数据比对后&#xff0c;需要矫正GC偏好引起的reads数量误差可用loess回归算法&#xff0c;使用R语言对封装的loess算法实现。 在NIPT中&#xff0c;GC矫正对检测结果准确性非常重要&#xff0c;具体研究参考以下文章。 Noninvasive Prenatal Diagnosis of Fetal Trisomy…

向量数据库:PGVector

一、PGVector 介绍 PGVector 是一个基于 PostgreSQL 的扩展插件&#xff0c;为用户提供了一套强大的向量存储和查询的功能&#xff1a; 精确和近似最近邻搜索单精度&#xff08;Single-precision&#xff09;、半精度&#xff08;Half-precision&#xff09;、二进制&#xff…

【代码随想录——栈与队列】

1.栈和队列理论基础 栈和队列的原理大家应该很熟悉了&#xff0c;队列是先进先出&#xff0c;栈是先进后出。 2.用栈实现队列 type MyQueue struct {head []intheadSize intstore []intstoreSize int }func Constructor() MyQueue {return MyQueue{head : make([]int,100),h…

AI智剪新风尚:一键操作,批量视频剪辑轻松入门

随着科技的飞速进步&#xff0c;人工智能(AI)已逐渐渗透到我们生活的各个领域&#xff0c;其中&#xff0c;AI视频剪辑技术的出现&#xff0c;为视频制作带来了革命性的变革。如今&#xff0c;一键操作、批量处理的AI智剪正成为视频剪辑的新风尚&#xff0c;让剪辑工作变得前所…

品牌舆情监测工作要怎么做?

一个负面舆论的传播&#xff0c;可能在短时间内对企业品牌形象造成巨大损害&#xff0c;甚至引发舆情危机。因此&#xff0c;如何有效地进行品牌舆情监测&#xff0c;成为企业不可忽视的问题。伯乐网络传媒多年网络公关、舆情监测经验&#xff0c;今天就来给大家分享一下。 一、…

【半个月我拿下了软考证】软件设计师高频考点--系统化教学-网络安全

&#x1f468;‍&#x1f4bb; 收录于专栏&#xff1a;软件设计师考点暴击 ⭐&#x1f170;️进入狂砍分⭐ ⭐软件设计师高频考点文档&#xff0c; ⭐软件设计师高频考点专栏 ⭐软件设计师高频考点⭐ &#x1f3b6;&#xff08;A) 考点1&#xff0c;网络攻击 理解记忆 &#…

Kubernetes——基础认识

目录 一、简介 1.Kubernetes是什么 2.Kubernetes特性 2.1自我修复 2.2弹性伸缩 2.3自动部署和回滚 2.4服务发现和负载均衡 2.5机密和配置管理 2.6存储编排 2.7批量处理 二、Kubernetes架构与组件 1.Master 1.1Kube-ApiServer 1.2Kube-Scheduler调度器 1.3Kube-C…

机器学习(二) ----------K近邻算法(KNN)+特征预处理+交叉验证网格搜索

目录 1 核心思想 1.1样本相似性 1.2欧氏距离&#xff08;Euclidean Distance&#xff09; 1.3其他距离 1.3.1 曼哈顿距离&#xff08;Manhattan Distance&#xff09; 1.3.2 切比雪夫距离&#xff08;Chebyshev distance&#xff09; 1.3.3 闵式距离&#xff08;也称为闵…

OpenHarmony 4.0 实战开发——分布式任务调度浅析

1 概述 OpenHarmony 分布式任务调度是一种基于分布式软总线、分布式数据管理、分布式 Profile 等技术特性的任务调度方式。它通过构建一种统一的分布式服务管理机制&#xff0c;包括服务发现、同步、注册和调用等环节&#xff0c;实现了对跨设备的应用进行远程启动、远程调用、…

ChatPPT开启高效办公新时代,AI赋能PPT创作

目录 一、前言二、ChatPPT的几种用法1、通过在线生成2、通过插件生成演讲者模式最终成品遇到问题改进建议 三、ChatPPT其他功能 一、前言 想想以前啊&#xff0c;为了做个PPT&#xff0c;我得去网上找各种模板&#xff0c;有时候还得在某宝上花钱买。结果一做PPT&#xff0c;经…

拼多多投产比怎么逐步调高

提高拼多多的投产比&#xff08;ROI&#xff09;需要综合考虑多个因素&#xff0c;包括点击量、转化率、客单价以及点击花费。以下是一些有效的方法&#xff1a; 拼多多推广可以使用3an推客。3an推客&#xff08;CPS模式&#xff09;给商家提供的营销工具&#xff0c;由商家自…
最新文章