Elasticsearch:使用 Open AI 和 Langchain 的 RAG - Retrieval Augmented Generation (三)

这是继之前文章:

的续篇。在今天的文章中,我将详述如何使用 ElasticsearchStore。这也是被推荐的使用方法。如果你还没有设置好自己的环境,请详细阅读第一篇文章。

创建应用并展示

安装包

复制代码
#!pip3 install langchain

导入包

复制代码
from dotenv import load_dotenv
from langchain.embeddings import OpenAIEmbeddings
from langchain.vectorstores import ElasticsearchStore
from langchain.text_splitter import CharacterTextSplitter
from urllib.request import urlopen
import os, json

load_dotenv()
 
openai_api_key=os.getenv('OPENAI_API_KEY')
elastic_user=os.getenv('ES_USER')
elastic_password=os.getenv('ES_PASSWORD')
elastic_endpoint=os.getenv("ES_ENDPOINT")
elastic_index_name='elasticsearch-store'

添加文档并将文档分成段落

复制代码
with open('workplace-docs.json') as f:
   workplace_docs = json.load(f)
 
print(f"Successfully loaded {len(workplace_docs)} documents")
复制代码
metadata = []
content = []

for doc in workplace_docs:
  content.append(doc["content"])
  metadata.append({
      "name": doc["name"],
      "summary": doc["summary"],
      "rolePermissions":doc["rolePermissions"]
  })

text_splitter = CharacterTextSplitter(chunk_size=50, chunk_overlap=0)
docs = text_splitter.create_documents(content, metadatas=metadata)

把数据写入到 Elasticsearch

复制代码
from elasticsearch import Elasticsearch

embeddings = OpenAIEmbeddings(openai_api_key=openai_api_key)
 
url = f"https://{elastic_user}:{elastic_password}@{elastic_endpoint}:9200"
connection = Elasticsearch(url, ca_certs = "./http_ca.crt", verify_certs = True)

 
es = ElasticsearchStore.from_documents( 
                            docs,
                            embedding = embeddings, 
                            es_url = url, 
                            es_connection = connection,
                            index_name = elastic_index_name, 
                            es_user = elastic_user,
                            es_password = elastic_password)

展示结果

复制代码
def showResults(output):
  print("Total results: ", len(output))
  for index in range(len(output)):
    print(output[index])
复制代码
query = "work from home policy"
result = es.similarity_search(query=query)

showResults(result)

我们在 Kibana 的 Dev Tools 里打入如下的命令:

复制代码
embeddings = OpenAIEmbeddings(openai_api_key=openai_api_key)


es = ElasticsearchStore(
    es_url = url,
    es_connection = connection,
    es_user=elastic_user,
    es_password=elastic_password,
    embedding=embeddings,
    index_name=elastic_index_name,
    strategy=ElasticsearchStore.ApproxRetrievalStrategy(
        hybrid=True
    )
)

es.similarity_search("work from home policy")

造成这个错误的原因是因为当前的 License 模式不支持 RRF。我们去 Kibana 启动当前的授权:

我们再次运行代码:

复制代码
embeddings = OpenAIEmbeddings(openai_api_key=openai_api_key)


es = ElasticsearchStore(
    es_url = url,
    es_connection = connection,
    es_user=elastic_user,
    es_password=elastic_password,
    embedding=embeddings,
    index_name=elastic_index_name,
    strategy=ElasticsearchStore.ExactRetrievalStrategy()
)

es.similarity_search("work from home policy")

在这个步骤中,我们需要启动 ELSER。有关 ELSER 的启动,请参阅文章 "Elasticsearch:部署 ELSER - Elastic Learned Sparse EncoderR"。

复制代码
embeddings = OpenAIEmbeddings(openai_api_key=openai_api_key)

es = ElasticsearchStore.from_documents(
    docs,
    es_url = url,
    es_connection = connection,
    es_user=elastic_user,
    es_password=elastic_password,
    index_name=elastic_index_name+"-"+"elser",
    strategy=ElasticsearchStore.SparseVectorRetrievalStrategy()
)

es.similarity_search("work from home policy")

在运行完上面的代码后,我们可以在 Kibana 中进行查看所生成的字段:

上面代码的整个 jupyter notebook 可以在地址 https://github.com/liu-xiao-guo/semantic_search_es/blob/main/ElasticsearchStore.ipynb 下载。

相关推荐
极小狐7 分钟前
极狐GitLab 如何 cherry-pick 变更?
人工智能·git·机器学习·gitlab
沛沛老爹11 分钟前
从线性到非线性:简单聊聊神经网络的常见三大激活函数
人工智能·深度学习·神经网络·激活函数·relu·sigmoid·tanh
0x21120 分钟前
[论文阅读]ReAct: Synergizing Reasoning and Acting in Language Models
人工智能·语言模型·自然语言处理
mucheni31 分钟前
迅为iTOP-RK3576开发板/核心板6TOPS超强算力NPU适用于ARM PC、边缘计算、个人移动互联网设备及其他多媒体产品
arm开发·人工智能·边缘计算
Jamence32 分钟前
多模态大语言模型arxiv论文略读(三十六)
人工智能·语言模型·自然语言处理
猿饵块44 分钟前
opencv--图像变换
人工智能·opencv·计算机视觉
LucianaiB1 小时前
【金仓数据库征文】_AI 赋能数据库运维:金仓KES的智能化未来
运维·数据库·人工智能·金仓数据库 2025 征文·数据库平替用金仓
24k小善1 小时前
Flink TaskManager详解
java·大数据·flink·云计算
jndingxin1 小时前
OpenCV 图形API(63)图像结构分析和形状描述符------计算图像中非零像素的边界框函数boundingRect()
人工智能·opencv·计算机视觉
时序数据说1 小时前
时序数据库IoTDB在航空航天领域的解决方案
大数据·数据库·时序数据库·iotdb