ToB企服应用市场:ToB评测及商务社交产业平台

标题: 重新审阅 ChatGPT 和 Elasticsearch:RAG 真正将应用程序紧密结合在一起 [打印本页]

作者: 大连密封材料    时间: 2024-8-31 15:33
标题: 重新审阅 ChatGPT 和 Elasticsearch:RAG 真正将应用程序紧密结合在一起
作者:来自 Elastic Jeff Vestal

关注博客 ChatGPT 和 Elasticsearch:OpenAI 遇到私家数据。
在此博客中,你将相识怎样:

如果你想直接进入代码,可以在此处查察随附的 Jupyter Notebook。

2023 年 4 月

自从我编写最初的《ChatGPT 和 Elasticsearch:OpenAI 遇到了私家数据》 以来,许多事变都发生了变化:。大多数人只是在玩 ChatGPT,如果他们真的尝试过的话。而且每个技术会议的每个展位都没有出现 “AI” 字母(无论它是否有用)。

2024 年 8 月

从那时起,Elastic 就致力于成为一个功能齐备的向量数据库,并投入了大量的工程努力,使其成为任何构建搜索应用程序的人的最佳向量数据库选项。为了制止花几页纸来批评 Elasticsearch 的全部增强功能,下面是一个不分先后顺序的非细致列表:

随着全部这些变化以及更多变化,原始博客需要重写。让我们开始吧。

更新流程

此更新流程的计划如下:

设置


Elasticsearch Serverless 项目

我们将为我们的聊天呆板人使用 Elastic Serverless 项目。Serverless 消除了运行 Elasticsearch 集群的大部分复杂性,让你专注于现实使用和从数据中获取价值。在此处阅读有关 serverless 架构的更多信息。
如果你没有 Elastic Cloud 帐户,你可以在 elastic.co 创建为期两周的免费试用版(Serverless 定价在此处提供)。如果你已经有一个,你只需登录即可。
登录后,你需要创建一个云 API 密钥。

注意:在下面的步骤中,我将展示 Python 代码的相关部分。为了简便起见,我不会展示导入所需库、等候步骤完成、捕获错误等的完备代码。
如需运行更强大的代码,请参阅随附的 Jypyter 笔记本!

创建 serverless 项目

我们将使用新创建的 API 密钥执行接下来的设置步骤。
起首,创建一个新的 Elasticsearch 项目。
  1. url = "https://api.elastic-cloud.com/api/v1/serverless/projects/elasticsearch"
  2. project_data = {
  3.     "name": "The RAG Really Tied the App Together",
  4.     "region_id": "aws-us-east-1",
  5.     "optimized_for": "vector"
  6. }
  7. auth_header = f"ApiKey {api_key}"  # seeing what a comment lokos like with pound
  8. headers = {
  9.     "Content-Type": "application/json",
  10.     "Authorization": auth_header
  11. }
  12. es_project = requests.post(url, json=project_data, headers=headers)  :four:
复制代码


创建 Elasticsearch Python 客户端

创建程序化项目标一大长处是,你将得到与其交互所需的连接信息和根据!
  1. es = Elasticsearch(es_project_keys['endpoints']['elasticsearch'],
  2.                    basic_auth=(es_project_keys['credentials']['username'],
  3.                               es_project_keys['credentials']['password']
  4.                               )
  5.                    )
复制代码

ELSER 嵌入 API

项目创建完成后(通常只需几分钟),我们就可以准备处置惩罚实验室的数据。
第一步是配置用于嵌入的推理 API。我们将使用 Elastic Learned Sparse Encoder (ELSER)。

  1. model_config = {
  2.     "service": "elser",
  3.     "service_settings": {
  4.         "num_allocations": 8,
  5.         "num_threads": 1
  6.     }
  7. }
  8. inference_id = "my-elser-model"
  9. create_endpoint = es.inference.put_model(
  10.     inference_id=inference_id,
  11.     task_type="sparse_embedding",
  12.     body=model_config
  13. )
复制代码

此单个命令将触发 Elasticsearch 执行几个任务:


索引映射

创建 ELSER API 后,我们将创建索引模板。
  1. template_body = {
  2.     "index_patterns": ["elastic-labs*"],
  3.     "template": {
  4.         "mappings": {
  5.             "properties": {
  6.                 "body": {
  7.                     "type": "text",
  8.                     "copy_to": "semantic_body"
  9.                 },
  10.                 "semantic_body": {
  11.                     "type": "semantic_text",
  12.                     "inference_id": "my-elser-model"
  13.                 },
  14.                 "headings": {
  15.                     "type": "text"
  16.                 },
  17.                 "id": {
  18.                     "type": "keyword"
  19.                 },
  20.                 "meta_description": {
  21.                     "type": "text"
  22.                 },
  23.                 "title": {
  24.                     "type": "text"
  25.                 }
  26.             }
  27.         }
  28.     }
  29. }
  30. template_resp = es.indices.put_index_template(  :eight:
  31.     name="labs_template",
  32.     body=template_body
  33. )
复制代码

其他字段将被索引但自动映射。我们重点在模板中预定义的字段不需要同时是关键字和文本范例,否则会自动定义。
最紧张的是,对于本指南,我们必须定义我们的 semantic_text 字段并使用 copy_to 设置要从中复制的源字段。在这种情况下,我们有兴趣对文本正文执行语义搜索,爬虫会将其索引到 body 中。

爬取全部实验室!

我们如今可以安装和配置爬虫程序来爬取 Elastic * 实验室。我们将大抵遵循 Open Crawler 发布的优秀指南,该指南发布于技术预览版 Search Labs 博客。
以下步骤将使用 docker 并在 MacBook Pro 上运行。要使用差别的设置运行此程序,请查阅 Open Crawler Github readme。

克隆 repo

打开你选择的命令行工具。我将使用 Iterm2。将 crawler repo 克隆到你的呆板上。
  1. ~/repos
  2. ❯ git clone git@github.com:elastic/crawler.git
  3. Cloning into 'crawler'...
  4. remote: Enumerating objects: 1944, done.
  5. remote: Counting objects: 100% (418/418), done.
  6. remote: Compressing objects: 100% (243/243), done.
  7. remote: Total 1944 (delta 237), reused 238 (delta 170), pack-reused 1526
  8. Receiving objects: 100% (1944/1944), 84.85 MiB | 31.32 MiB/s, done.
  9. Resolving deltas: 100% (727/727), done.
复制代码

构建爬虫容器

运行以下命令来构建并运行爬虫。
  1. docker build -t crawler-image . && docker run -i -d --name crawler crawler-image
复制代码
  1. ~/repos ❯ cd crawler~/repos/crawler main ❯ docker build -t crawler-image . && docker run -i -d --name crawler crawler-image[+] Building 66.9s (6/10)                                                                                                                                                                docker:desktop-linux => [internal] load build definition from Dockerfile                                        0.0s => => transferring dockerfile: 333B                                                        0.0s => [internal] load .dockerignore                                                        0.0s => => transferring context: 2B                                                                0.0s => [internal] load metadata for docker.io/library/jruby:9.4.7.0-jdk21                1.7s => [auth] library/jruby:pull token for registry-1.docker.io                        0.0s...... => [5/5] RUN make clean install                                                                50.7s => exporting to image                                                                        0.9s => => exporting layers                                                                        0.9s => => writing image sha256:6b3f4000a121e76aba76fdbbf11b53f53a3fabba61c0b7cf3fdcdb21e244f1d8        0.0s => => naming to docker.io/library/crawler-image                                        0.0scc6c16941de04355c050ef5f5fd0041ee7f3505b8cf8448c7223f0d2e80b5498
复制代码

配置爬虫

在你最喜好的编辑器(vim)中创建一个新的 YAML:
  1. ~/repos/crawler main
  2. ❯ vim config/elastic-labs.yml
复制代码
我们想要抓取这三个实验室网站上的全部文档,但由于这些网站上的博客和教程往往会链接到 elastic.co 的其他部分,因此我们需要设置频频运行来限制范围。我们将答应抓取我们网站的三个路径,然后拒绝其他任何路径。
将以下内容粘贴到文件中并保存
  1. domains:
  2.   - url: https://www.elastic.co
  3.     seed_urls:
  4.       - https://www.elastic.co/search-labs
  5.       - https://www.elastic.co/observability-labs
  6.       - https://www.elastic.co/security-labs
  7.     crawl_rules:
  8.       - policy: allow
  9.         type: begins
  10.         pattern: /search-labs
  11.       - policy: allow
  12.         type: begins
  13.         pattern: /observability-labs
  14.       - policy: allow
  15.         type: begins
  16.         pattern: /security-labs
  17.       - policy:deny
  18.         type: regex
  19.         pattern: .*/author/.*
  20.       - policy: deny
  21.         type: regex
  22.         pattern: .*
  23. output_sink: elasticsearch
  24. output_index: elastic-labs
  25. max_crawl_depth: 2
  26. elasticsearch:
  27.   host: "https://<your_serverless_project>.es.<region>.aws.elastic.cloud"
  28.   port: "443"
  29.   api_key: "<API Key generated above>"
复制代码
将配置复制到 Docker 容器中:
  1. ~/repos/crawler main ⇣
  2. ❯ docker cp config/elastic-labs.yml crawler:/app/config/elastic-labs.yml
  3. Successfully copied 2.05kB to crawler:/app/config/elastic-labs.yml
复制代码

验证域

通过运行以下命令确保配置文件没有题目:
  1. ❯ docker exec -it crawler bin/crawler validate config/elastic-labs.yml
  2. Domain https://www.elastic.co is valid
复制代码

启动爬虫

首次运行爬虫时,处置惩罚三个实验室网站上的全部文章大概需要几分钟。
  1. docker exec -it crawler bin/crawler crawl config/elastic-labs.yml
复制代码
  1. ~/repos/crawler/config main ⇣
  2. ❯ docker exec -it crawler bin/crawler crawl config/elastic-labs.yml
  3. [crawl:6692c3b584f98612e3a465ce] [primary] Initialized an in-memory URL queue for up to 10000 URLs
  4. [crawl:6692c3b584f98612e3a465ce] [primary] ES connections will be authorized with configured API key
  5. [crawl:6692c3b584f98612e3a465ce] [primary] ES connections will use SSL without ca_fingerprint
  6. [crawl:6692c3b584f98612e3a465ce] [primary] Elasticsearch sink initialized for index [elastic-labs] with pipeline [ent-search-generic-ingestion]
  7. [crawl:6692c3b584f98612e3a465ce] [primary] Starting the crawl with up to 10 parallel thread(s)...
  8. [crawl:6692c3b584f98612e3a465ce] [primary] Crawl status: queue_size=11, pages_visited=1, urls_allowed=12, urls_denied={}, crawl_duration_msec=847, crawling_time_msec=635.0, avg_response_time_msec=635.0, active_threads=1, http_client={:max_connections=>100, :used_connections=>1}, status_codes={"200"=>1}
复制代码

确认文章已被索引

我们将通过两种方式举行确认。
起首,我们将查察示例文档以确保已生成 ELSER 嵌入。我们只想查察任何文档,这样我们就可以在没有任何参数的情况下举行搜索:
  1. GET elastic-labs/_search
复制代码
确保你得到结果,然后查抄字段 body 是否包含文本以及 semantic_body.inference.chunks.0.embeddings 是否包含标记。
  1.     "hits": [
  2.       {
  3.         "_index": "elastic-labs",
  4. ...
  5.         "_source": {
  6.           "body": "Tutorials Integrations Blog Start Free Trial Contact Sales Open navigation menu Overview ...
  7.           "semantic_body": {
  8.             "inference": {
  9.               "inference_id": "my-elser-model",
  10.               "model_settings": {
  11.                 "task_type": "sparse_embedding"
  12.               },
  13.               "chunks": [
  14.                 {
  15.                   "text": "Tutorials Integrations Blog Start Free Trial Contact Sales Open navigation menu Overview ...
  16.                   "embeddings": {
  17.                     "##her": 2.1016746,
  18.                     "elastic": 2.084594,
  19.                     "##ai": 1.6336359,
  20.                     "dock": 1.5765089,
  21.                     ...
复制代码
我们可以通过 terms 聚合来查抄我们是否从三个站点分别收集数据:
  1. GET elastic-labs/_search
  2. {
  3.   "size": 0,
  4.   "aggs": {
  5.     "url_path_dir1": {
  6.       "terms": {
  7.         "field": "url_path_dir1.keyword"
  8.       }
  9.     }
  10.   }
  11. }
复制代码
你应该会看到以我们的三个站点路径之一开头的结果。
  1.       "buckets": [
  2.         {
  3.           "key": "security-labs",
  4.           "doc_count": 37
  5.         },
  6.         {
  7.           "key": "observability-labs",
  8.           "doc_count": 30
  9.         },
  10.         {
  11.           "key": "search-labs",
  12.           "doc_count": 6
  13.         }
  14.       ]
复制代码

前往 Playground!

通过提取、分块和推理数据,我们可以开始编写将与 RAG 应用程序的 LLM 交互的后端应用程序代码。


LLM 连接

我们需要为 Playground 配置一个连接,以便对 LLM 举行 API 调用。截至撰写本文时,Playground 支持与 OpenAI、AWS Bedrock 和 Google Gemini 的聊天完成连接。计划提供更多连接,因此请查察文档以获取最新列表。
首次进入 Playground UI 时,单击 “Connect to an LLM

由于我在原始博客中使用了 OpenAI,因此我们将坚持使用它。Playground 的优点在于,你可以将连接切换到其他服务,并且 Playground 代码将专门针对该服务的 API 规范生成代码。你只需要选择今天要使用哪一个。

在此步骤中,你必须根据要使用的 LLM 填写字段。如上所述,由于 Playground 将抽象出 API 差别,因此你可以使用任何适合你的受支持的 LLM 服务,本指南中的其余步骤将以雷同的方式工作。
如果你没有 Azure OpenAI 帐户或 OpenAI API 帐户,你可以在此处获取一个(OpenAI 如今要求至少 5 美元来资助 API 帐户)。

完成后,点击 “Save”,你将收到连接器已添加简直认信息。之后,你只需选择我们将在应用中使用的索引。你可以选择多个,但由于我们全部的爬虫数据都将进入 elastic-labs,因此你可以选择一个。
单击 “Add data sources”,你就可以开始使用 Playground 了!

选择之前创建的 “restaurant_reviews ”索引。


在 Playground 中尝试

添加数据源后,你将进入 Playground UI。

为了尽大概简化入门过程,我们将坚持使用除提示之外的全部默认设置。但是,有关 Playground 组件及其使用方法的更多详细信息,请查察 Playground:在几分钟内使用 Elasticsearch 尝试 RAG 应用程序博客和 Playground 文档。
试验差别的设置以满足你的特定数据和应用程序需求是设置 RAG 支持的应用程序的紧张部分。
我们将使用的默认值是:


创建更详细的提示

Playground 中的默认提示只是一个占位符。随着 LLM 功能越来越强大,提示工程也不断发展。探索不断变化的提示工程世界是一个博客,但在创建系统提示时需要记取一些根本概念:

思量到这一点,我们可以创建一个更详细的系统提示:
  1. You are a helpful and knowledgeable assistant designed to assist users in querying information related to Search, Observability, and Security. Your primary goal is to provide clear, concise, and accurate responses based on semantically relevant documents retrieved using Elasticsearch.
  2. Guidelines:
  3. Audience:
  4. Assume the user could be of any experience level but lean towards a technical slant in your explanations.
  5. Avoid overly complex jargon unless it is common in the context of Elasticsearch, Search, Observability, or Security.
  6. Response Structure:
  7. Clarity: Responses should be clear and concise, avoiding unnecessary verbosity.
  8. Conciseness: Provide information in the most direct way possible, using bullet points when appropriate.
  9. Formatting: Use Markdown formatting for:
  10. Bullet points to organize information
  11. Code blocks for any code snippets, configurations, or commands
  12. Relevance: Ensure the information provided is directly relevant to the user's query, prioritizing accuracy.
  13. Content:
  14. Technical Depth: Offer sufficient technical depth while remaining accessible. Tailor the complexity based on the user's apparent knowledge level inferred from their query.
  15. Examples: Where appropriate, provide examples or scenarios to clarify concepts or illustrate use cases.
  16. Documentation Links: When applicable, suggest additional resources or documentation from Elastic.co that can further assist the user.
  17. Tone and Style:
  18. Maintain a professional yet approachable tone.
  19. Encourage curiosity by being supportive and patient with all user queries, regardless of complexity.
  20. Example Queries:
  21. "How can I optimize my Elasticsearch cluster for large-scale data?"
  22. "What are the best practices for implementing observability in a microservices architecture?"
  23. "How can I secure sensitive data in Elasticsearch?"
复制代码
你可以随意测试差别的提示和上下文设置,看看你认为最适合特定数据的结果。有关高级技术的更多示例,请查察提示部分两部分博客:高级 RAG 技术中。同样,请参阅 Playground 博客文章,相识有关你可以调解的各种设置的更多详细信息。

导出代码

在后台,Playground 会生成我们执行语义搜索、解析相关上下笔墨段以及向 LLM 发出聊天完成调用所需的全部后端聊天代码。我们无需举行任何编码工作!
在右上角单击 “View Code” 按钮以展开代码弹出窗口


你将看到生成的 Python 代码,此中包含你配置的全部设置以及对 Elasticsearch 举行语义调用、解析结果、构建完备提示、调用 LLM 息争析这些结果的函数。
单击复制图标以复制代码。

你如今可以将代码合并到你本身的聊天应用程序中!

总结

自一年多前第一次发布此博客以来,发生了许多变化,我们在本博客中涵盖了许多内容。你从云 API 密钥开始,创建了 Elasticsearch Serverless 项目,生成了云 API 密钥,配置了 Open Web Crawler,爬取了三个 Elastic Lab 站点,对长文本举行了分块,生成了嵌入,测试了 RAG 应用程序的最佳聊天设置,并导出了代码!
UI 在那里,Vestal?
请关注第二部分,我们将在此中将操场代码集成到具有 React 前端的 Python 后端中。我们还将研究部署完备的聊天应用程序。
有关上述全部内容的完备代码集,请参阅随附的 Jypyter 笔记本

准备好本身尝试一下了吗?开始免费试用。
Elasticsearch 集成了 LangChain、Cohere 等工具。加入我们的 Beyond RAG Basics 网络研讨会,构建你的下一个 GenAI 应用程序!

原文:ChatGPT and Elasticsearch integration: RAG enhancements for chatbots — Search Labs

免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。




欢迎光临 ToB企服应用市场:ToB评测及商务社交产业平台 (https://dis.qidao123.com/) Powered by Discuz! X3.4