Elasticsearch:带有自查询检索器的聊天机器人示例

本工作簿演示了 Elasticsearch 的自查询检索器 (self-query retriever) 将问题转换为结构化查询并将结构化查询应用于 Elasticsearch 索引的示例。

在开始之前,我们首先使用 langchain 将文档分割成块,然后使用 ElasticsearchStore.from_documents 创建一个向量存储并将数据索引到 elasticsearch。

然后,我们将看到一些示例查询,展示了由 elasticsearch 驱动的自查询检索器的全部功能。

安装

如果你还没有安装好自己的 Elasticsearch 及 Kibana,请参考文章:

安装 Elasticsearch 及 Kibana

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

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

Python 安装包

我们需要安装 Python 版本 3.6 及以上版本。我们还需要安装如下的 Python 安装包:

复制代码
python3 -m pip install -qU lark elasticsearch langchain openai

$ pwd
/Users/liuxg/python/elser
$ python3 -m pip install -qU lark elasticsearch langchain openai
$ pip3 list | grep elasticsearch
elasticsearch             8.11.1
rag-elasticsearch         0.0.1        /Users/liuxg/python/rag-elasticsearch/my-app/packages/rag-elasticsearch

在本练习中,我们将使用最新的 Elastic Stack 8.11 来进行展示。

环境变量

在启动 Jupyter 之前,我们设置如下的环境变量:

复制代码
export ES_USER="elastic"
export ES_PASSWORD="yarOjyX5CLqTsKVE3v*d"
export ES_ENDPOINT="localhost"
export OPENAI_API_KEY="YOUR_OPEN_AI_KEY"

请在上面修改相应的变量的值。特别是你需要输入自己的 OPENAI_API_KEY。

拷贝 Elasticsearch 证书

我们把 Elasticsearch 的证书拷贝到当前的目录下:

复制代码
$ pwd
/Users/liuxg/python/elser
$ cp ~/elastic/elasticsearch-8.11.0/config/certs/http_ca.crt .
overwrite ./http_ca.crt? (y/n [n]) y
$ ls http_ca.crt 
http_ca.crt

创建应用

导入 python 包

我们在当前的目录下创建 jupyter notebook:Chatbot Example with Self Query Retriever.ipynb

复制代码
from langchain.schema import Document
from langchain.embeddings.openai import OpenAIEmbeddings
from langchain.vectorstores import ElasticsearchStore
from langchain.llms import OpenAI
from langchain.retrievers.self_query.base import SelfQueryRetriever
from langchain.chains.query_constructor.base import AttributeInfo

创建文档

接下来,我们将使用 langchain 模式文档创建包含电影摘要的文档列表,其中包含每个文档的 page_content 和元数据。

复制代码
docs = [
    Document(
        page_content="A bunch of scientists bring back dinosaurs and mayhem breaks loose",
        metadata={"year": 1993, "rating": 7.7, "genre": "science fiction", "director": "Steven Spielberg", "title": "Jurassic Park"},
    ),
    Document(
        page_content="Leo DiCaprio gets lost in a dream within a dream within a dream within a ...",
        metadata={"year": 2010, "director": "Christopher Nolan", "rating": 8.2, "title": "Inception"},
    ),
    Document(
        page_content="A psychologist / detective gets lost in a series of dreams within dreams within dreams and Inception reused the idea",
        metadata={"year": 2006, "director": "Satoshi Kon", "rating": 8.6, "title": "Paprika"},
    ),
    Document(
        page_content="A bunch of normal-sized women are supremely wholesome and some men pine after them",
        metadata={"year": 2019, "director": "Greta Gerwig", "rating": 8.3, "title": "Little Women"},
    ),
    Document(
        page_content="Toys come alive and have a blast doing so",
        metadata={"year": 1995, "genre": "animated", "director": "John Lasseter", "rating": 8.3, "title": "Toy Story"},
    ),
    Document(
        page_content="Three men walk into the Zone, three men walk out of the Zone",
        metadata={
            "year": 1979,
            "rating": 9.9,
            "director": "Andrei Tarkovsky",
            "genre": "science fiction",
            "rating": 9.9,
            "title": "Stalker",
        },
    ),
]

连接到 Elasticsearch

我们将使用我们本地构建的 Elasticsearch 集群进行连接。我们可以参考之前的文章 "Elasticsearch:使用 Open AI 和 Langchain 的 RAG - Retrieval Augmented Generation (三)"。

复制代码
from dotenv import load_dotenv
from langchain.embeddings import OpenAIEmbeddings
from langchain.vectorstores import ElasticKnnSearch
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='elastic-knn-search'

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

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)

设置查询检索器

接下来,我们将通过提供有关文档属性的一些信息和有关文档的简短描述来实例化自查询检索器。

然后我们将使用 SelfQueryRetriever.from_llm 实例化检索器 (retriever)

复制代码
metadata_field_info = [
    AttributeInfo(
        name="genre",
        description="The genre of the movie. Can be either 'science fiction' or 'animated'.",
        type="string or list[string]",
    ),
    AttributeInfo(
        name="year",
        description="The year the movie was released",
        type="integer",
    ),
    AttributeInfo(
        name="director",
        description="The name of the movie director",
        type="string",
    ),
    AttributeInfo(
        name="rating", description="A 1-10 rating for the movie", type="float"
    ),
]

document_content_description = "Brief summary of a movie"

# Set up openAI llm with sampling temperature 0
llm = OpenAI(temperature=0, openai_api_key=openai_api_key)

# instantiate retriever
retriever = SelfQueryRetriever.from_llm(
    llm, es, document_content_description, metadata_field_info, verbose=True
)

使用自查询检索器回答问题

现在我们将演示如何使用 RAG 的自查询检索器。

复制代码
from langchain.chat_models import ChatOpenAI
from langchain.schema.runnable import RunnableParallel, RunnablePassthrough
from langchain.prompts import ChatPromptTemplate, PromptTemplate
from langchain.schema import format_document

LLM_CONTEXT_PROMPT = ChatPromptTemplate.from_template("""
Use the following context movies that matched the user question. Use the movies below only to answer the user's question.

If you don't know the answer, just say that you don't know, don't try to make up an answer.

----
{context}
----
Question: {question}
Answer:
""")

DOCUMENT_PROMPT = PromptTemplate.from_template("""
---
title: {title}                                                                                   
year: {year}  
director: {director}    
---
""")

def _combine_documents(
    docs, document_prompt=DOCUMENT_PROMPT, document_separator="\n\n"
):
    doc_strings = [format_document(doc, document_prompt) for doc in docs]
    return document_separator.join(doc_strings)


_context = RunnableParallel(
    context=retriever | _combine_documents,
    question=RunnablePassthrough(),
)

chain = (_context | LLM_CONTEXT_PROMPT | llm)

chain.invoke("What movies are about dreams and it was released after the year 2009 but before the year 2011?")

上面的代码可以在地址:https://github.com/liu-xiao-guo/semantic_search_es/blob/main/Chatbot%20Example%20with%20Self%20Query%20Retriever.ipynb下载。

相关推荐
MARS_AI_3 小时前
云蝠智能 Voice Agent 落地展会邀约场景:重构会展行业的智能交互范式
人工智能·自然语言处理·重构·交互·语音识别·信息与通信
weixin_422456443 小时前
第N7周:调用Gensim库训练Word2Vec模型
人工智能·机器学习·word2vec
HuggingFace7 小时前
Hugging Face 开源机器人 Reachy Mini 开启预定
人工智能
智海观潮7 小时前
Flink CDC支持Oracle RAC架构CDB+PDB模式的实时数据同步吗,可以上生产环境吗
大数据·oracle·flink·flink cdc·数据同步
企企通采购云平台7 小时前
「天元宠物」×企企通,加速数智化升级,“链”接萌宠消费新蓝海
大数据·人工智能·宠物
超级小忍7 小时前
Spring AI ETL Pipeline使用指南
人工智能·spring
Apache Flink7 小时前
Flink Forward Asia 2025 主旨演讲精彩回顾
大数据·flink
张较瘦_8 小时前
[论文阅读] 人工智能 | 读懂Meta-Fair:让LLM摆脱偏见的自动化测试新方法
论文阅读·人工智能
巴伦是只猫8 小时前
【机器学习笔记 Ⅲ】4 特征选择
人工智能·笔记·机器学习
好心的小明9 小时前
【王树森推荐系统】召回11:地理位置召回、作者召回、缓存召回
人工智能·缓存·推荐系统·推荐算法