Elasticsearch:使用 Llamaindex 的 RAG 与 Elastic 和 Llama3

news2024/10/10 10:30:17

这篇文章是对之前的文章 “使用 Llama 3 开源和 Elastic 构建 RAG” 的一个补充。我们可以在本地部署 Elasticsearch,并进行展示。我们将一步一步地来进行配置并展示。你还可以参考我之前的另外一篇文章 “Elasticsearch:使用在本地计算机上运行的 LLM 以及 Ollama 和 Langchain 构建 RAG 应用程序”。

安装

 Elasticsearch 及 Kibana

 如果你还没有安装好自己的 Elasticsearch 及 Kibana,请参考如下的链接来进行安装:

  • 如何在 Linux,MacOS 及 Windows 上进行安装 Elasticsearch
  • Kibana:如何在 Linux,MacOS 及 Windows上安装 Elastic 栈中的 Kibana

在安装的时候,我们选择 Elastic Stack 8.x 来进行安装。特别值得指出的是:ES|QL 只在 Elastic Stack 8.11 及以后得版本中才有。你需要下载 Elastic Stack 8.11 及以后得版本来进行安装。

在首次启动 Elasticsearch 的时候,我们可以看到如下的输出:

在上面,我们可以看到 elastic 超级用户的密码。我们记下它,并将在下面的代码中进行使用。

我们还可以在安装 Elasticsearch 目录中找到 Elasticsearch 的访问证书:

$ pwd
/Users/liuxg/elastic/elasticsearch-8.14.1/config/certs
$ ls
http.p12      http_ca.crt   transport.p12

在上面,http_ca.crt 是我们需要用来访问 Elasticsearch 的证书。

 我们首先克隆已经写好的代码:

git clone https://github.com/liu-xiao-guo/elasticsearch-labs

我们然后进入到该项目的根目录下:

$ pwd
/Users/liuxg/python/elasticsearch-labs/notebooks/integrations/llama3
$ ls
README.md                      rag-elastic-llama3-elser.ipynb rag-elastic-llama3.ipynb

如上所示,rag-elastic-llama3.ipynb 就是我们今天想要工作的 notebook。

我们通过如下的命令来拷贝所需要的证书:

$ pwd
/Users/liuxg/python/elasticsearch-labs/notebooks/integrations/llama3
$ cp ~/elastic/elasticsearch-8.14.1/config/certs/http_ca.crt .
$ ls
README.md                      rag-elastic-llama3-elser.ipynb
http_ca.crt                    rag-elastic-llama3.ipynb

安装所需要的 python 依赖包

pip3 install llama-index llama-index-cli llama-index-core llama-index-embeddings-elasticsearch llama-index-embeddings-ollama llama-index-legacy llama-index-llms-ollama llama-index-readers-elasticsearch llama-index-readers-file llama-index-vector-stores-elasticsearch llamaindex-py-client python-dotenv

我们可以通过如下的命令来查看 elasticsearch 安装包的版本:

$ pip3 list | grep elasticsearch
elasticsearch                           8.14.0
llama-index-embeddings-elasticsearch    0.1.2
llama-index-readers-elasticsearch       0.1.4
llama-index-vector-stores-elasticsearch 0.2.0

创建环境变量

为了能够使得下面的应用顺利执行,在项目当前的目录下运行如下的命令:

export ES_ENDPOINT="localhost"
export ES_USER="elastic"
export ES_PASSWORD="uK+7WbkeXMzwk9YvP-H3"

 配置 Ollama 和 Llama3

由于我们使用 Llama 3 8B 参数大小模型,我们将使用 Ollama 运行该模型。按照以下步骤安装 Ollama。

  • 浏览到 URL https://ollama.com/download 以根据你的平台下载 Ollama 安装程序。

        在我的电脑上,我使用 macOS 来进行安装。你也可以仿照文章 “Elasticsearch:使用在本地计算机上运行的 LLM 以及 Ollama 和 Langchain 构建 RAG 应用程序” 在 docker 里进行安装。

  • 按照说明为你的操作系统安装和运行 Ollama。
  • 安装后,按照以下命令下载 Llama3 模型。

点击上面的 “Finish” 按钮,并按照上面的提示在 terminal 中运行:

这可能需要一些时间,具体取决于你的网络带宽。运行完成后,你将看到如上的界面。

要测试 Llama3,请从新终端运行以下命令或在提示符下输入文本。

    curl -X POST http://localhost:11434/api/generate -d '{ "model": "llama3", "prompt":"Why is the sky blue?" }'

在提示符下,输出如下所示。

我们现在使用 Ollama 在本地运行 Llama3。

下载数据集文档

我们可以使用如下的命令来下载文档:

wget https://raw.githubusercontent.com/elastic/elasticsearch-labs/main/datasets/workplace-documents.json
$ pwd
/Users/liuxg/python/elasticsearch-labs/notebooks/integrations/llama3
$ ls
README.md                      rag-elastic-llama3-elser.ipynb
http_ca.crt                    rag-elastic-llama3.ipynb
$ wget https://raw.githubusercontent.com/elastic/elasticsearch-labs/main/datasets/workplace-documents.json
--2024-06-25 10:54:01--  https://raw.githubusercontent.com/elastic/elasticsearch-labs/main/datasets/workplace-documents.json
Resolving raw.githubusercontent.com (raw.githubusercontent.com)... 185.199.110.133
Connecting to raw.githubusercontent.com (raw.githubusercontent.com)|185.199.110.133|:443... connected.
HTTP request sent, awaiting response... 200 OK
Length: 52136 (51K) [text/plain]
Saving to: ‘workplace-documents.json’

workplace-documents.jso 100%[=============================>]  50.91K   260KB/s    in 0.2s    

2024-06-25 10:54:02 (260 KB/s) - ‘workplace-documents.json’ saved [52136/52136]

$ ls
README.md                      rag-elastic-llama3-elser.ipynb workplace-documents.json
http_ca.crt                    rag-elastic-llama3.ipynb

展示

我们在项目当前的目录下打入如下的命令:

读入变量并连接到 Elasticsearch

from elasticsearch import Elasticsearch, AsyncElasticsearch, helpers
from dotenv import load_dotenv
import os

load_dotenv()
 
ES_USER = os.getenv("ES_USER")
ES_PASSWORD = os.getenv("ES_PASSWORD")
ES_ENDPOINT = os.getenv("ES_ENDPOINT")
COHERE_API_KEY = os.getenv("COHERE_API_KEY")
 
url = f"https://{ES_USER}:{ES_PASSWORD}@{ES_ENDPOINT}:9200"
print(url)
 
client = AsyncElasticsearch(url, ca_certs = "./http_ca.crt", verify_certs = True)
info = await client.info()
print(info)

从上面的输出中,我们可以看到已经成功地连接到 Elasticsearch 了。

注意:在上面我们使用了 AsyncElasticsearch 而不是 Elasticsearch。这个是由于下面的一个 Ollama 调用所需要的。详细情况,请参阅帖子。

准备文档以进行分块和提取

我们现在准备使用 Llamaindex 进行处理的 Document 类型的数据。我们先读入文件:

import json
# from urllib.request import urlopen
from llama_index.core import Document

# url = "https://raw.githubusercontent.com/elastic/elasticsearch-labs/main/datasets/workplace-documents.json"

# response = urlopen(url)
# workplace_docs = json.loads(response.read())

import json
 
# Load data into a JSON object
with open('workplace-documents.json') as f:
   workplace_docs = json.load(f)

# Building Document required by LlamaIndex.
documents = [
    Document(
        text=doc["content"],
        metadata={
            "name": doc["name"],
            "summary": doc["summary"],
            "rolePermissions": doc["rolePermissions"],
        },
    )
    for doc in workplace_docs
]

在 LlamaIndex 中定义 Elasticsearch 和提取管道以进行文档处理。使用 Llama3 生成嵌入。

我们现在使用所需的索引名称、文本字段及其相关嵌入来定义 Elasticsearchstore。我们使用 Llama3 生成嵌入。我们将在索引上运行语义搜索,以查找与用户提出的查询相关的文档。我们将使用 Llamaindex 提供的 SentenceSplitter 对文档进行分块。所有这些都作为 Llamaindex 框架提供的 IngestionPipeline 的一部分运行。

from llama_index.core.node_parser import SentenceSplitter
from llama_index.core.ingestion import IngestionPipeline
from llama_index.embeddings.ollama import OllamaEmbedding
from llama_index.vector_stores.elasticsearch import ElasticsearchStore

es_vector_store = ElasticsearchStore( 
                            index_name="workplace_index",
                            es_url = url, 
                            es_client = client,    
                            vector_field="content_vector",
                            text_field = "content",
                            es_user = ES_USER,
                            es_password = ES_PASSWORD)

# Embedding Model to do local embedding using Ollama.
ollama_embedding = OllamaEmbedding("llama3")
# LlamaIndex Pipeline configured to take care of chunking, embedding
# and storing the embeddings in the vector store.
pipeline = IngestionPipeline(
    transformations=[
        SentenceSplitter(chunk_size=512, chunk_overlap=100),
        ollama_embedding,
    ],
    vector_store=es_vector_store,
)

执行管道

这将对数据进行分块,使用 Llama3 生成嵌入并将其提取到 Elasticsearch 索引中,并将嵌入到密集向量字段中。

pipeline.run(show_progress=True, documents=documents)

嵌入存储在维度为 4096 的密集向量场中。维度大小来自于从 Llama3 生成的嵌入的大小。

定义 LLM 设置。

这将连接到您的本地 LLM。有关在本地运行 Llama3 的步骤的详细信息,请参阅 https://ollama.com/library/llama3。

如果你有足够的资源(至少 >64 GB 的 RAM 和 GPU 可用),那么你可以尝试 70B 参数版本的 Llama3

from llama_index.llms.ollama import Ollama
from llama_index.core import Settings

Settings.embed_model = ollama_embedding
local_llm = Ollama(model="llama3")

设置语义搜索并与 Llama3 集成

我们现在将 Elasticsearch 配置为 Llamaindex 查询引擎的向量存储。然后使用 Llama3 的查询引擎通过来自 Elasticsearch 的上下文相关数据回答你的问题。

from llama_index.core import VectorStoreIndex, QueryBundle

index = VectorStoreIndex.from_vector_store(es_vector_store)
query_engine = index.as_query_engine(local_llm, similarity_top_k=10)

# Customer Query
query = "What are the organizations sales goals?"
bundle = QueryBundle(
    query_str=query, embedding=Settings.embed_model.get_query_embedding(query=query)
)

response = query_engine.query(bundle)

print(response.response)

所有的代码可以在地址下载:elasticsearch-labs/notebooks/integrations/llama3/rag-elastic-llama3.ipynb at main · liu-xiao-guo/elasticsearch-labs · GitHub

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

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

相关文章

在线epub阅读器epub;在线图书阅读器;专门为epub定制的阅读器;免费在线电子图书epub阅读器

背景:不记得某时某刻了,就是当时想要使用电脑阅读epub图书,也找了好些个在线epub阅读器,但总有一些不如意的地方,如某些功能需要会员之类的,突发临想的就想到自己开发一个,就此,一个…

大模型RAG技术:构建高效、可信赖的知识检索系统

前言 LLM 问题 幻觉:在没有答案的情况下提供虚假信息。 过时:当用户需要特定的当前响应时,提供过时或通用的信息。 来源:从非权威来源创建响应。由于术语混淆,不同的培训来源使用相同的术语来谈论不同的事情&#…

C# Onnx Yolov8-OBB 旋转目标检测 行驶证副页条码+编号 检测,后续裁剪出图片并摆正显示

C# Onnx Yolov8-OBB 旋转目标检测 行驶证副页条码编号 检测,后续裁剪出图片并摆正显示 目录 效果 模型信息 项目 代码 下载 效果 模型信息 Model Properties ------------------------- date:2024-06-25T10:59:15.206586 description:…

第一课:SSH协议、SSHD守护进程、Openssh软件包

第一节课 6月12日 ssh协议 关键问题 一、ssh、sshd、openssh的概念和区别? 二、ssh是基于什么架构?B/S还是C/S? 三、用户远程连接服务器经历哪些过程? 四、如何查看openssh软件包是否安装? 五、rpm和yum的区别&#xf…

node带参数命令

不带参数命令示例: node /www/wwwroot/server 带参数命令示例: node /www/wwwroot/server arg1 arg2 arg3 在启动页进行参数处理: // 获取启动参数(除去前2个默认参数,示例:node /www/wwwroot/server arg1 arg2 …

SAP ABAP 之容器

文章目录 前言一、案例介绍/笔者需求二、自定义容器 a.实例化对象 b.自定义容器效果演示 c.Copy Code 三、自适应容器 a.常用 必须 参数理解 b.METRIC 度量单位 c.RATIO 百分比尺寸 d.STYLE 容器…

WMV 视频格式怎么转换?WMV 视频为什么不流行了?

目前有越来越多的视频格式类型,如常见的 MP4、FLV、AVI 等等,而技术的演变也逐渐让一些常见的视频格式变的越来越少了。 今天我们一起来聊下 WMV 这个视频格式,让我们看看它的发展以及为什么现在越来越少人使用了。 什么是 WMV 视频格式&…

微信营销自动化(朋友圈自动点赞工具):UIAutomation的解决方案

文章不用看, 是AI生成的, 请直接查看下载地址 http://www.aisisoft.top . 微信朋友圈自动点赞工具, 自动群发工具 在当今的数字化营销领域,自动化工具成为了提升工作效率、增强客户互动的关键。本文将详细介绍一款基于UIAutomation框架与Python语言构建的微信营销自…

数据容器(四)

目录 一、dict(字典、映射) 1.字典的定义 2.字典数据的获取 3.字典的嵌套 一、dict(字典、映射) 1.字典的定义 使用{},不过存储的元素是一个个的:键值对。 2.字典数据的获取 字典同集合一样&#xff…

PointCloudLib-滤波模块(Filtering)-使用统计异常值移除过滤器移除异常值

在本教程中,我们将学习如何消除噪声测量值,例如异常值, 使用统计分析技术的点云数据集。 背景 激光扫描通常会生成不同点密度的点云数据集。 此外,测量误差会导致稀疏异常值,从而破坏 结果更多。这使得本地点云的估计变得复杂 表面法线或曲率变化等特征,导致 错误的值,…

【WEB】关于react的WEB应用中使用React Developer Tools便捷快速查看元素数据

1、往扩展工具中添加React Developer Tools的扩展包 2、检查是否生效,如下图: 可以看到右上角多出来一个Components的tab选项,就是成功了

转运机器人:智能物流的得力助手

在物流行业,转运机器人已经成为提高转运效率、降低成本的重要工具。而富唯智能转运机器人凭借其出色的性能和智能化的设计,成为了众多企业的得力助手。 富唯智能转运机器人采用了先进的AMR控制系统,可以一体化控制移动机器人并实现与产线设备…

美国众议院通过ENFORCE ACT草案:AI领域的潜在冷战?

近日,美国众议院通过了“增强关键出口海外限制国家框架法案”(ENFORCE ACT),该法案旨在限制AI/ML技术和人才向中国的流动。这一举动引发了广泛讨论和担忧,许多人认为这将对在美从事AI相关工作的中国人造成重大影响。本…

【力扣】重排链表

🔥博客主页: 我要成为C领域大神 🎥系列专栏:【C核心编程】 【计算机网络】 【Linux编程】 【操作系统】 ❤️感谢大家点赞👍收藏⭐评论✍️ 本博客致力于分享知识,欢迎大家共同学习和交流。 给定一个单链表…

传媒行业采购堡垒机的必要性你知道吗?

随着互联网的快速发展,传媒行业也是发展速度。特别是近年来,自媒体行业的火热,如何保障网络安全,如何保障大家信息安全至关重要。虽然国家严格要求执行等保政策,但大家对于为什么传媒行业要采购堡垒机不是很了解。你知…

JDK16特性

JDK16特性 一、JAVA16概述 2021年3月16日正式发布,一共更新了17JEP https://openjdk.java.net/projects/jdk/16/ 二、语法层面变化 1.JEP 397:密封类(第二次预览) sealed class 第二次预览通过密封的类和接口来增强Java编程语言,这是新的预览特性,用于限制超类的使用密封…

Nuxt 3组件开发与管理

title: Nuxt 3组件开发与管理 date: 2024/6/20 updated: 2024/6/20 author: cmdragon excerpt: 摘要:本文深入探讨了Nuxt 3的组件开发与管理,从基础概念、安装配置、目录结构、组件分类与开发实践、生命周期与优化,到测试与维护策略。详细…

小程序注册

【 一 】小程序注册 微信公众平台 https://mp.weixin.qq.com/ https://mp.weixin.qq.com/注册 邮箱激活 小程序账户注册 微信小程序配置 微信小程序开发流程 添加项目成员 【 二 】云服务 lass 基础设施服务(组装机) 你买了一大堆的电脑配件&#x…

【AI编译器】triton学习:矩阵乘优化

Matrix Multiplication 主要内容: 块级矩阵乘法 多维指针算术 重新编排程序以提升L2缓存命 自动性能调整 Motivations 矩阵乘法是当今高性能计算系统的一个关键组件,在大多数情况下被用于构建硬件。由于该操作特别复杂,因此通常由软件提…

鸿蒙开发报错 -cppcrash happened

报错信息: cppcrash happened in ‘设备名’ 现象:打开应用就闪退,无论是模拟器还是真机都会闪退,预览器没有问题 报错原因,在入口页面添加了export, 页面是不需要导出的,只有组件需要导出&…