使用 Elastic 和 Mistral 构建多语言 RAG(二)

news2024/9/21 2:46:54

这篇文章是之前的文章 “使用 Elastic 和 Mistral 构建多语言 RAG(一)” 的续篇。在这篇文章中,我将展示如何在本地部署中完成在那篇文章中的实现。

注意:由于 semantic text 从 8.15 版本开始提供,你需要至少 8.15 及以上的版本才可以运行下面的代码。

安装

 Elasticsearch 及 Kibana

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

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

在安装的时候,我们选择 Elastic Stack 8.x 来进行安装。在首次启动 Elasticsearch 的时候,我们可以看到如下的输出:

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

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

$ pwd
/Users/liuxg/elastic/elasticsearch-8.15.0/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/supporting-blog-content/building-multilingual-rag-with-elastic-and-mistral
$ ls
building_multilingual_rag_with_elastic_and_mistral.ipynb

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

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

$ pwd
/Users/liuxg/python/elasticsearch-labs/supporting-blog-content/building-multilingual-rag-with-elastic-and-mistral
$ cp ~/elastic/elasticsearch-8.15.0/config/certs/http_ca.crt .
$ ls
building_multilingual_rag_with_elastic_and_mistral.ipynb
http_ca.crt

启动白金试用

我们的演示中需要使用到版权。我们按照下面的步骤来启动白金试用:

这样我们就完成了白金试用的功能。

添加 ES 模型做多语言向量化

我们在 DevTools 中打入如下的命令:

PUT _inference/text_embedding/multilingual-embeddings
 {
    "service": "elasticsearch",
    "service_settings": {
        "model_id": ".multilingual-e5-small",
        "num_allocations": 1 ,
        "num_threads": 1
    }
}

整个的过程需要一定的时间来完成。

我们接下来去机器学习界面查看:

我们需要等一定的时间来完成上面的下载。

我们还可以直接通过如下的方法来进行下载:

上面显示 E5 已经部署成功了。

安装所需要的 python 依赖包

pip3 install python-dotenv elasticsearch==8.14 mistralai

我们可以使用如下的方法来查看 elasticsearch 的版本:

$ pip3 list | grep elasticsearch
elasticsearch                           8.14.0

创建环境变量

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

export ES_ENDPOINT="localhost"
export ES_USER="elastic"
export ES_PASSWORD="YourPassword"
export MISTRAL_API_KEY="YourKey"

你需要根据自己的 Elasticsearch 的配置进行相应的修改。你可以在地址申请 Mistral API key。前提是你需要注册一个账号。

使用 Elastic 和 Mistral 构建 RAG

我们接下来运行 Python notebook。我们在当前的目录下打入如下的命令:

jupyter notebook building_multilingual_rag_with_elastic_and_mistral.ipynb

安装软件包并导入必要的模块

# install packages
!python3 -m pip install python-dotenv elasticsearch==8.14 mistralai

# import modules
from mistralai.client import MistralClient
from mistralai.models.chat_completion import ChatMessage
from elasticsearch import Elasticsearch, exceptions
from elasticsearch.helpers import bulk
from getpass import getpass
import json

读入变量

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")
MISTRAL_API_KEY = os.getenv("MISTRAL_API_KEY")

实例化 Elasticsearch 客户端

# Create the client instance
url = f"https://{ES_USER}:{ES_PASSWORD}@{ES_ENDPOINT}:9200"
print(url)

es_client = Elasticsearch(url, ca_certs = "./http_ca.crt", verify_certs = True)
print(es_client.info())

上面显示我们的客户端成功连接到 Elasticsearch。

创建嵌入端点

try:
    es_client.options(
        request_timeout=60, max_retries=3, retry_on_timeout=True
    ).inference.put_model(
        task_type="text_embedding",
        inference_id="multilingual_embeddings",
        body={
            "service": "elasticsearch",
            "service_settings": {
                "model_id": ".multilingual-e5-small",
                "num_allocations": 1,
                "num_threads": 1,
            },
        },
    )

    print("Embedding endpoint created successfully.")
except exceptions.BadRequestError as e:
    if e.error == "resource_already_exists_exception":
        print("Embedding endpoint already created.")
    else:
        raise e

上面运行的输出结果为:

Embedding endpoint created successfully.

我们可以通过如下的命令来查看已经创建的 embedding endpoint:

GET /_inference/multilingual_embeddings

创建映射

try:
    es_client.indices.create(
        index="multilingual-mistral",
        body={
            "mappings": {
                "properties": {
                    "super_body": {
                        "type": "semantic_text",
                        "inference_id": "multilingual-embeddings",
                    }
                }
            }
        },
    )
except exceptions.RequestError as e:
    if e.error == "resource_already_exists_exception":
        print("Index already exists.")
    else:
        raise e

写入文档

# Support tickets to add to the index
support_tickets = [
    """
        _Support Ticket #EN1234_
        **Subject**: Calendar sync not working with Google Calendar

        **Description**:
        I'm having trouble syncing my project deadlines with Google Calendar. Whenever I try to sync, I get an error message saying "Unable to connect to external calendar service."

        **Resolution**:
        The issue was resolved by following these steps:
        1. Go to Settings > Integrations
        2. Disconnect the Google Calendar integration
        3. Clear browser cache and cookies
        4. Reconnect the Google Calendar integration
        5. Authorize the app again in Google's security settings

        The sync should now work correctly. If problems persist, ensure that third-party cookies are enabled in your browser settings.
    """,
    """
        _Support-Ticket #DE5678_
        **Betreff**: Datei-Upload funktioniert nicht

        **Beschreibung**:
        Ich kann keine Dateien mehr in meine Projekte hochladen. Jedes Mal, wenn ich es versuche, bleibt der Ladebalken bei 99% stehen und dann erscheint eine Fehlermeldung.

        **Lösung**:
        Das Problem wurde durch folgende Schritte gelöst:
        1. Überprüfen Sie die Dateigröße. Die maximale Uploadgröße beträgt 100 MB.
        2. Deaktivieren Sie vorübergehend den Virenschutz oder die Firewall.
        3. Versuchen Sie, die Datei im Inkognito-Modus hochzuladen.
        4. Wenn das nicht funktioniert, leeren Sie den Browser-Cache und die Cookies.
        5. Als letzten Ausweg, versuchen Sie einen anderen Browser zu verwenden.

        In den meisten Fällen lag das Problem an zu großen Dateien oder an Interferenzen durch Sicherheitssoftware. Nach Anwendung dieser Schritte sollte der Upload funktionieren.
    """,
    """
        _Q3 Marketing Campaign Ideas_

        1. Social media contest: "Share Your Productivity Hack"
        - Users share tips using our software, best entry wins a premium subscription

        2. Webinar series: "Mastering Project Management"
        - Invite industry experts to share insights using our tool

        3. Email campaign: "Unlock Hidden Features"
        - Series of emails highlighting lesser-known but powerful features

        4. Partner with a productivity podcast for sponsored content

        5. Create a "Project Management Memes" social media account for lighter, shareable content
    """,
    """
        _Mitarbeiter des Monats: Juli 2023_

        Wir freuen uns, bekannt zu geben, dass Sarah Schmidt zur Mitarbeiterin des Monats Juli gewählt wurde!

        Sarah hat außergewöhnliche Leistungen in folgenden Bereichen gezeigt:
        - Kundenbetreuung: Sarah hat durchschnittlich 95% positive Bewertungen erhalten.
        - Teamarbeit: Sie hat maßgeblich zur Verbesserung unseres internen Wissensmanagementsystems beigetragen.
        - Innovation: Sarah hat eine neue Methode zur Priorisierung von Support-Tickets vorgeschlagen, die unsere Reaktionszeiten um 20% verbessert hat.

        Bitte gratulieren Sie Sarah zu dieser wohlverdienten Anerkennung!
    """,
]
# This function will create a bulk object for the given id and body
def build_bulk_obj(id, body):
    return {
        "_index": "multilingual-mistral",
        "_id": id,
        "_source": {"super_body": body},
    }
data = []

# Constructing bulk object for each detail
for i, details in enumerate(support_tickets):
    data.append(build_bulk_obj(i + 1, details))

try:
    # Using the bulk API to index the data
    bulk(es_client, data)
    print("Data indexed successfully.")
except exceptions.RequestError as e:
    print("Error indexing data.")
    print(e)

我们可以看到如下的结果:

Data indexed successfully.

在 Kibana 里,我们可以通过如下的命令来进行查看:

GET multilingual-mistral/_search

我们可以看到有 4 个文档:

检索文档

response = es_client.search(
    index="multilingual-mistral",
    body={
        "size": 2,
        "_source": {"excludes": ["*embeddings", "*chunks"]},
        "query": {
            "semantic": {
                "field": "super_body",
                "query": "Hola, estoy teniendo problemas para ocupar su aplicación, estoy teniendo problemas para sincronizar mi calendario, y encima al intentar subir un archivo me da error.",
            }
        },
    },
)

# Print results
formatted_json = json.dumps(response.body, indent=4)

print(formatted_json)

回答问题

现在我们将使用 Mistral 来回答这个问题。

# Joining the Elasticsearch retrieve context
elastic_context = []

for r in response.body["hits"]["hits"]:
    elastic_context.append(r["_source"]["super_body"]["text"])

context_str = "\n".join(elastic_context)
client = MistralClient(api_key=MISTRAL_API_KEY)

system_message = "You are a helpful multilingual agent that help users with their problems. You have access to a knowledge base on different languages and you must answer in the same language the question was asked."
user_message = f"""
    ## Question:

    Hola, estoy teniendo problemas para ocupar su aplicación, estoy teniendo problemas para sincronizar mi calendario, y encima al intentar subir un archivo me da error.

    ## Related knowledge:

    {context_str}
"""

messages = [
    ChatMessage(role="system", content=system_message),
    ChatMessage(role="user", content=user_message),
]

model = "open-mixtral-8x22b"

chat_response = client.chat(
    model=model,
    messages=messages,
)
print(chat_response.choices[0].message.content)
¡Hola! Lamento que estés teniendo problemas con nuestra aplicación. Parece que hay dos problemas distintos aquí.

En primer lugar, respecto a la sincronización del calendario, sigue los pasos que se indicaron en el ticket de soporte #EN1234:

1. Ve a Ajustes > Integraciones
2. Desconecta la integración de Google Calendar
3. Borra la caché y las cookies del navegador
4. Vuelve a conectar la integración de Google Calendar
5. Autoriza de nuevo la aplicación en los ajustes de seguridad de Google

Si sigues teniendo problemas, asegúrate de que las cookies de terceros estén habilitadas en los ajustes de tu navegador.

En segundo lugar, sobre el error al subir un archivo, puedes seguir los pasos que se indicaron en el ticket de soporte #DE5678:

1. Comprueba el tamaño del archivo. El tamaño máximo de subida es de 100 MB.
2. Desactiva temporalmente el antivirus o el firewall.
3. Intenta subir el archivo en modo incógnito.
4. Si eso no funciona, borra la caché y las cookies del navegador.
5. Como último recurso, prueba a utilizar un navegador diferente.

En la mayoría de los casos, el problema estaba causado por archivos demasiado grandes o por interferencias de software de seguridad. Después de seguir estos pasos, el proceso de subida debería funcionar correctamente.

删除所使用的资源

最后,我们可以删除所使用的资源,以防止它们消耗资源。

# Cleanup - Delete Index
es_client.indices.delete(index="multilingual-mistral", ignore=[400, 404])

# Cleanup - Delete Embeddings Endpoint
es_client.inference.delete_model(
    inference_id="multilingual_embeddings", ignore=[400, 404]
)
ObjectApiResponse({'acknowledged': True, 'pipelines': []})

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

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

相关文章

Go框架选战:Gin、Echo、Fiber的终极较量

Gin 优点: 高性能: 优化以处理高并发和低延迟请求。易于上手: 对于熟悉 Go 的开发者来说,API 设计直观,学习曲线低。社区支持强: 广泛使用,有大量第三方中间件和教程。 缺点: 相比于其他框架如 Echo,Gin缺乏内置的验证支持Gin…

万字长文揭秘高性能架构

从零开始学架构系列文章: 从零开始学架构——概念和基础 从零开始学架构——万字长文揭秘高性能架构 从零开始学架构——高可用架构 从零开始学架构——可扩展架构 高性能存储 关系数据库 互联网业务兴起之后,海量用户加上海量数据的特点&#xff0…

无人机之民用无人机用途分类篇

一、航拍无人机 用于航拍摄影和电影制作,提供空中视角的拍摄服务。可用于电影制作、广告拍摄、房地产销售等。 二、物流无人机 用于快递和货物运输,提高物流效率,可以到达传统配送方式难以覆盖的地区,在突发事件如自然灾害、疫…

keepalived工作原理和使用方式

keepalived是什么 keepalived是集群管理中保证集群高可用的一个服务软件,用来防止单点故障。 keepalived主要有三个模块 分别是core、check和vrrp。core模块为keepalived的核心,负责主进程的启动、维护以及全局配置文件的加载和解析。check负责健康检…

怎么根据企业特点提供个性化的六西格玛培训?

近年来,六西格玛作为一种强大的质量管理方法,以其数据驱动、流程优化和减少缺陷为核心,被众多企业视为提升竞争力的关键工具。然而,并非所有企业都能直接套用标准的六西格玛培训体系,因为每个企业的文化、行业特性、发…

顺序队列和链式队列的基本操作

顺序队列 函数说明😃: InitStack( &s):初始化栈 StackEmpty(s):判断一个栈是否为空 Push(& s, x):进栈 Pop(&s, &x):出栈 GetTop(s,&x):读栈顶元素 show(s):读出…

Vue3项目框架搭建

前言 大多时候是在别人搭建好的项目上开发需求,突然要自己从新项目搭建开始,纯纯赶鸭子上架,参考一些项目,试着搭建的,记录一下历程,主要怕忘了。有些地方本该贴上代码截图更好,但是我此刻手头…

Vue引入使用iconfont字体图标

由于element-ui或element-plus提供的图标有时候并不能满足日常需求,所以这篇介绍一下前端引入阿里巴巴矢量图标库使用,不止是vue使用,不限于vue2、vue3,html或是其他框架也是同样的道理,只要引入都是同样可以使用的。 1. 首先进入阿里巴巴矢量图标库官网 官网:https://…

弱智吧:大模型变聪明,有我一份贡献【大模型VS弱智吧,谁聪明?谁弱智?】

「被门夹过的核桃,还能补脑吗?」 在中文网络上流传着这样一段话:弱智吧里没有弱智。 百度「弱智吧」是个神奇的地方,在这里人人都说自己是弱智,但大多聪明得有点过了头。最近几年,弱智吧的年度总结文章都可…

算法——决策树

简介:个人学习分享,如有错误,欢迎批评指正。 一、什么是决策树? 决策树(decision tree):决策树是一种树形结构的监督学习算法,广泛应用于分类任务和回归任务中。它通过递归地将数据…

豆瓣的ip地址怎样修改:探索显示机制与实用操作

在数字化时代,网络空间成为了我们日常生活不可或缺的一部分。豆瓣,作为一个集书籍、电影、音乐评论及社交功能于一体的综合性平台,其用户遍布全球。然而,有时我们可能因为隐私保护、网络限制或特定需求而希望修改在豆瓣上显示的IP…

【STM32 FreeRTOS】任务

使用 RTOS 的实时应用程序可以被构建为一组独立的任务。每个任务在自己的上下文中执行,不依赖于系统内的其他任务或 RTOS 调度器本身。在任何时间点,应用程序中只能执行一个任务,实时 RTOS 调度器负责决定所要执行的任务。因此, R…

Figure 02 机器人发布:未来AI的巅峰还是泡沫中的救命稻草?

引言 近日,Figure AI 公司发布了其最新的机器人产品 Figure 02,引发了广泛关注。作为 Figure AI 的第二代人形机器人,Figure 02 的推出引发了关于它是否是“地表最强”机器人的讨论。同时,由于 OpenAI 的技术支持,这款…

Java Web —— 第三天(Ajax+组件)

Ajax 概念: Asynchronous JavaScript And XML,异步的JavaScript和XML。 作用: 数据交换:通过Aiax可以给服务器发送请求,并获服务器响应的数据 异步交互:可以在不重新加载整个页面的情况下,服务器交换数据并更新部分网页的技术&#xff0c…

Java开发笔记--通用基础数据校验的设计

最近在开发一个功能,对排水管网的基础数据(包括管井、管道、泵站,雨水口,雨水口线,泵站,污水处理厂,排口等)的导入进行校验。 以字段为纬度,考虑二个方面的校验:数据库唯一&#xf…

RHCA III之路---EX436-9

RHCA III之路---EX436-9 1. 题目2. 解题2.1 安装apache2.2 配置页面2.3 配置selinux和防火墙2.4 创建资源 3. 确认 1. 题目 2. 解题 考试时会给你个url,从url下载index.html并放入默认目录 2.1 安装apache 3个节点分别安装 yum install -y httpd2.2 配置页面 nodea上执行 …

VIVADO IP核之DDS直接数字频率合成器使用详解

VIVADO IP核之DDS直接数字频率合成器使用详解 目录 前言 一、DDS基本知识 二、DDS IP核使用之SIN COS LUT only 三、DDS IP核之SIN COS LUT only仿真 四、DDS IP核使用之Phase Generator and SIN COS LUT 五、DDS IP核之Phase Generator and SIN COS LUT仿真 总结 前言 …

js 深入理解原型(prototype)及如何创建对象

目录 1. 概述2. 工厂模式3. 构造函数模式3.1 创建的格式3.2 JS内部执行步骤3.3 constructor 构造器3.4 构造函数也是函数3.5 构造函数的问题 4. 原型模式 prototype4.1 理解原型本质4.2 原型层级(访问一个属性,查询的次序)4.2.1 查询次序:实例…

电动工具研讨会展商阵容揭晓,您的元器件选型指南!

导语 面对日益激烈的市场竞争,如何让您的电动工具脱颖而出?PI、MPS等多家知名元器件厂商将带来最新产品,覆盖MCU、电源管理芯片、功率器件等多个领域,助您一站式选型! 在智能制造浪潮的推动下,电动工具正快…

谷粒商城实战笔记-145-性能压测-性能监控-jvisualvm使用-解决插件不能安装

文章目录 jvisualvm的作用安装查看gc相关信息的插件解决jvisualvm不能正常安装插件的问题1,查看java版本2,打开网址3,修改jvisualvm的设置 jvisualvm的作用 JVisualVM是一个集成在Java Development Kit (JDK) 中的多功能工具,它提…