从向量数据库进行自动检索¶
本指南展示了如何在 LlamaIndex 中执行**自动检索**。
许多流行的向量数据库除了支持用于语义搜索的查询字符串外,还支持一组元数据过滤器。给定一个自然语言查询,我们首先使用 LLM 推断出一组元数据过滤器以及传递给向量数据库的正确查询字符串(两者都可以为空)。然后,这个完整的查询包会在向量数据库上执行。
这使得检索形式更加动态、富有表现力,超越了传统的 Top-K 语义搜索。给定查询的相关上下文可能只需要根据元数据标签进行过滤,或者需要在过滤后的集合中结合过滤和语义搜索,或者仅仅进行原始语义搜索。
我们将使用 Elasticsearch 演示一个示例,但自动检索也已通过许多其他向量数据库(例如 Pinecone、Weaviate 等)实现。
设置¶
我们首先定义导入。
如果您在 Colab 上打开此 Notebook,您可能需要安装 LlamaIndex 🦙。
%pip install llama-index-vector-stores-elasticsearch
!pip install llama-index
import logging
import sys
logging.basicConfig(stream=sys.stdout, level=logging.INFO)
logging.getLogger().addHandler(logging.StreamHandler(stream=sys.stdout))
# set up OpenAI
import os
import getpass
os.environ["OPENAI_API_KEY"] = getpass.getpass("OpenAI API Key:")
import openai
openai.api_key = os.environ["OPENAI_API_KEY"]
定义一些样本数据¶
我们将包含文本块的一些样本节点插入到向量数据库中。请注意,每个 TextNode
不仅包含文本,还包含元数据,例如 category
和 country
。这些元数据字段将在底层向量数据库中按原样进行转换/存储。
from llama_index.core import VectorStoreIndex, StorageContext
from llama_index.vector_stores.elasticsearch import ElasticsearchStore
from llama_index.core.schema import TextNode
nodes = [
TextNode(
text=(
"A bunch of scientists bring back dinosaurs and mayhem breaks"
" loose"
),
metadata={"year": 1993, "rating": 7.7, "genre": "science fiction"},
),
TextNode(
text=(
"Leo DiCaprio gets lost in a dream within a dream within a dream"
" within a ..."
),
metadata={
"year": 2010,
"director": "Christopher Nolan",
"rating": 8.2,
},
),
TextNode(
text=(
"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},
),
TextNode(
text=(
"A bunch of normal-sized women are supremely wholesome and some"
" men pine after them"
),
metadata={"year": 2019, "director": "Greta Gerwig", "rating": 8.3},
),
TextNode(
text="Toys come alive and have a blast doing so",
metadata={"year": 1995, "genre": "animated"},
),
]
使用 Elasticsearch 向量存储构建向量索引¶
在这里,我们将数据加载到向量存储中。如上所述,每个节点的文本和元数据都将被转换为 Elasticsearch 中相应的表示形式。我们现在可以对 Elasticsearch 中的这些数据运行语义查询以及元数据过滤。
vector_store = ElasticsearchStore(
index_name="auto_retriever_movies", es_url="http://localhost:9200"
)
storage_context = StorageContext.from_defaults(vector_store=vector_store)
index = VectorStoreIndex(nodes, storage_context=storage_context)
定义 VectorIndexAutoRetriever
¶
我们定义核心 VectorIndexAutoRetriever
模块。该模块接受 VectorStoreInfo
,其中包含向量存储集合及其支持的元数据过滤器的结构化描述。然后,此信息将用于自动检索提示中,LLM 在其中推断元数据过滤器。
from llama_index.core.retrievers import VectorIndexAutoRetriever
from llama_index.core.vector_stores import MetadataInfo, VectorStoreInfo
vector_store_info = VectorStoreInfo(
content_info="Brief summary of a movie",
metadata_info=[
MetadataInfo(
name="genre",
description="The genre of the movie",
type="string or list[string]",
),
MetadataInfo(
name="year",
description="The year the movie was released",
type="integer",
),
MetadataInfo(
name="director",
description="The name of the movie director",
type="string",
),
MetadataInfo(
name="rating",
description="A 1-10 rating for the movie",
type="float",
),
],
)
retriever = VectorIndexAutoRetriever(
index, vector_store_info=vector_store_info
)
运行一些样本数据¶
我们尝试运行一些样本数据。注意元数据过滤器是如何推断的——这有助于更精确的检索!
retriever.retrieve(
"What are 2 movies by Christopher Nolan were made before 2020?"
)
retriever.retrieve("Has Andrei Tarkovsky directed any science fiction movies")
INFO:llama_index.indices.vector_store.retrievers.auto_retriever.auto_retriever:Using query str: science fiction Using query str: science fiction INFO:llama_index.indices.vector_store.retrievers.auto_retriever.auto_retriever:Using filters: {'director': 'Andrei Tarkovsky'} Using filters: {'director': 'Andrei Tarkovsky'} INFO:llama_index.indices.vector_store.retrievers.auto_retriever.auto_retriever:Using top_k: 2 Using top_k: 2 INFO:elastic_transport.transport:POST http://localhost:9200/auto_retriever_movies/_search [status:200 duration:0.042s] POST http://localhost:9200/auto_retriever_movies/_search [status:200 duration:0.042s]
[]