圣诞老人遇见 GenAI:利用大语言模型、LangChain 和 Elasticsearch 破译手写的圣诞信件

在北极的中心地带,圣诞老人的精灵团队面临着巨大的后勤挑战:如何处理来自世界各地儿童的数百万封信件。 圣诞老人表情坚定,他决定是时候将人工智能纳入圣诞节行动了。

圣诞老人坐在配备了最新人工智能技术的电脑前,开始在 Jupyter Notebook 中编写 Python 脚本。 我们的目标既简单又雄心勃勃:利用生成式人工智能和 LLM 的力量来解释手写字母并提取必要的数据,并将其组织在 Elasticsearch 中。

安装

安装 Elasticsearch 及 Kibana

如果你还没有安装好自己的 Elasticsearch 及 Kibana,那么请参考一下的文章来进行安装:

在安装的时候,请选择 Elastic Stack 8.x 进行安装。在安装的时候,我们可以看到如下的安装信息:

在下面的展示中,我将使用 Elastic Stack 8.11 来进行展示。

Python

你可以安装自己喜欢的 Python 版本。版本在 3.8 及以上。我们还需要安装如下的 Python 包:

pip3 install python-dotenv elasticsearch langchain openai

数据

为了展示方便,我们需要在当前的目录下创建如下的 .env 文件:

.env

ini 复制代码
1.  $ pwd
2.  /Users/liuxg/python/elser
3.  $ cat .env
4.  ES_USER="elastic"
5.  ES_PASSWORD="yarOjyX5CLqTsKVE3v*d"
6.  ES_ENDPOINT="localhost"
7.  OPENAI_API_KEY="YourOwnOpenAiKey"

你可以根据自己的 Elasticsearch 配置进行修改上面的值。你需要申请一个 OpenAI 的 key 来进行使用。

为了能够访问 Elasticsearch,我们还需要把 Elasticsearch 的证书拷贝到当前的工作目录中:

bash 复制代码
1.  $ pwd
2.  /Users/liuxg/python/elser
3.  $ cp ~/elastic/elasticsearch-8.11.0/config/certs/http_ca.crt .
4.  $ ls http_ca.crt 
5.  http_ca.crt

我们想要解密的手写信件可以在地址进行下载:

应用设计

我们在项目当前的目录下运行:

markdown 复制代码
1.  $ pwd
2.  /Users/liuxg/python/elser
3.  $ jupyter notebook

这样我们就开创建我们的 notebook。第一步是设置环境变量,该变量将用作访问 OpenAI 和 Elasticsearch API 的凭据。

ini 复制代码
1.  import os

3.  from dotenv import load_dotenv

5.  load_dotenv()

7.  # OpenAI API Key
8.  OPENAI_API_KEY = os.getenv('OPENAI_API_KEY')
9.  OPENAI_API_URL = "https://api.openai.com/v1/chat/completions"

11.  elastic_user=os.getenv('ES_USER')
12.  elastic_password=os.getenv('ES_PASSWORD')
13.  elastic_endpoint=os.getenv("ES_ENDPOINT")
14.  openai_api_key=os.getenv('OPENAI_API_KEY')

接下来,圣诞老人使用圣诞信件的数字化图像编写了一个脚本,使用 "gpt-4-vision-preview" 提取文本。 这一关键步骤将手写文字转变为数字文本。 "GPT-4-vision-preview" 是 OpenAI 的 GPT-4 语言模型的实验版本,扩展后包含图像处理和分析功能。

python 复制代码
1.  from PIL import Image
2.  import requests
3.  import numpy as np

5.  from langchain.chat_models import ChatOpenAI
6.  from langchain.schema.messages import HumanMessage, SystemMessage

8.  image_path = 'https://i.imgur.com/IxC9lgd.png'

10.  chat = ChatOpenAI(model="gpt-4-vision-preview", max_tokens=512, openai_api_key=openai_api_key)
11.  result = chat.invoke(
12.      [
13.          HumanMessage(
14.              content=[
15.                  {"type": "text", "text": "What is in the picture? Please provide a detailed introduction."},
16.                  {
17.                      "type": "image_url",
18.                      "image_url": {
19.                          "url": image_path,
20.                          "detail": "auto",
21.                      },
22.                  },
23.              ]
24.          )
25.      ]
26.  )

29.  print(result.content)

然后,LangChain 开始行动,分析文本并识别关键元素,例如孩子的名字和愿望清单。

python 复制代码
1.  from langchain.prompts import PromptTemplate
2.  from langchain.chat_models import ChatOpenAI
3.  from langchain.schema import StrOutputParser

5.  chain = ChatOpenAI(model="gpt-3.5-turbo", max_tokens=1024)

7.  prompt = PromptTemplate.from_template(
8.  """
9.  Extract the list and child's name from the text below and return the data in JSON format using the following name:
10.  - "child_name", "wishlist".

12.  {santalist}

14.  """
15.  )

17.  runnable = prompt | chain | StrOutputParser()

19.  letter = result.content
20.  wishlist = runnable.invoke({"santalist": letter})
21.  print(wishlist)

圣诞老人决定丰富一下数据库,并要求人工智能估算这些礼物的重量。 这样,他就可以在 Kibana 中生成一份清单,将孩子们的礼物分为每个袋子并放入雪橇的空间中 - 什么组织!

python 复制代码
1.  chain = ChatOpenAI(model="gpt-3.5-turbo", max_tokens=1024)

3.  prompt = PromptTemplate.from_template(
4.  """

6.  {santalist_json}

8.  From the JSON above, include a new attribute in the JSON called 'weight',
9.  which will calculate the total estimated weight of each item in the list in kilograms.

11.  You will first need to estimate the weight of each item individually.
12.  After that, sum these values to obtain the total weight.
13.  Extract only the numerical value.

15.  """
16.  )

18.  runnable = prompt | chain | StrOutputParser()

20.  new_wishlist = runnable.invoke({"santalist_json": wishlist})
21.  print(new_wishlist)

现在,数据已结构化,是时候将它们写入到 Elasticsearch 了。

ini 复制代码
1.  from elasticsearch import Elasticsearch
2.  import json

4.  url = f"https://{elastic_user}:{elastic_password}@{elastic_endpoint}:9200"
5.  es = Elasticsearch(url, ca_certs = "./http_ca.crt", verify_certs = True)

7.  es.info() # should return cluster info

9.  # Parse the JSON string
10.  json_string = new_wishlist
11.  data = json.loads(json_string)

13.  # Index name
14.  index_name = "santa_claus_list"

16.  # Index the document
17.  response = es.index(index=index_name, document=data)

19.  # Print the response from Elasticsearch
20.  print(response)

使用 Dev Tools(集成到 Kibana 中的工具),圣诞老人和精灵可以轻松搜索和分析数据。 这样可以清楚地了解今年的礼物趋势、信件最常出现的位置,甚至可以识别那些表达特殊或紧急愿望的信件,当然还有礼物的重量。 正如使用 ES|QL 的查询一样 (你需要安装 Elastic Stack 8.11 及以上版本才可以使用 ES|QL)。

python 复制代码
1.  POST /_query?format=txt
2.  {
3.    "query": """
4.    FROM santa_claus_list
5.    | STATS  sum_toy = SUM(weight) BY child_name
6.    | LIMIT 100
7.    """
8.  }

到目前为止,我们只处理了一封信。我们可以按照同样的套路对多封信进行处理。最终我们可以得到像如下的数据统计:

markdown 复制代码
1.  # result
2.      sum_toy    |  child_name   
3.  ---------------+---------------
4.  30.5           |Maria
5.  1.5            |Mike
6.  3.0            |Theo
7.  2.5            |Isabella
8.  40.0           |William
9.  30.0           |Olivia 

借助这一创新解决方案,圣诞老人不仅能够更高效地满足请求,而且还获得了对世界各地儿童的欢乐和希望的宝贵洞察,这一切都得益于人工智能、LangChain和 Elasticsearch 的力量。 今年的圣诞节注定会是最神奇、最井然有序的一个!

上面的代码可以在地址下载:github.com/liu-xiao-gu...

相关推荐
Lill_bin8 小时前
深入理解ElasticSearch集群:架构、高可用性与数据一致性
大数据·分布式·elasticsearch·搜索引擎·zookeeper·架构·全文检索
RwTo11 小时前
Elasticsearch 聚合搜索
大数据·elasticsearch·搜索引擎·全文检索
求学小火龙12 小时前
ElasticSearch介绍+使用
java·大数据·elasticsearch
檀越剑指大厂12 小时前
【Elasticsearch系列六】系统命令API
大数据·elasticsearch·搜索引擎
bug菌¹18 小时前
滚雪球学SpringCloud[5.1讲]: Spring Cloud Config详解
spring·elasticsearch·spring cloud
Li小李同学Li18 小时前
git学习【持续更新中。。。】
git·学习·elasticsearch
nangonghen19 小时前
通过logstash同步elasticsearch数据
大数据·elasticsearch
檀越剑指大厂19 小时前
【Elasticsearch系列四】ELK Stack
大数据·elk·elasticsearch
2401_8401922720 小时前
ELFK日志分析平台,架构和通信
elk·elasticsearch·架构
cyt涛1 天前
搜索功能技术方案
mysql·elasticsearch·全文检索·canal·索引·数据同步·搜索