主题
本指南展示如何在 LlamaIndex 中使用 Weaviate 执行自动检索。
Weaviate 向量数据库除支持用于语义搜索的查询字符串外,还支持一组元数据过滤器。给定自然语言查询后,我们首先使用大语言模型(LLM)推断一组元数据过滤器以及要传给向量数据库的正确查询字符串(两者也可以为空)。随后,将整个查询包针对向量数据库执行。
这允许超越 top-k 语义搜索,实现更动态、更具表现力的检索形式。给定查询的相关上下文可能只需要对元数据标签进行过滤,或者需要在过滤集内进行过滤 + 语义搜索的联合组合,或者只需要原始语义搜索。
设置
我们首先定义导入,并定义一个空的 Weaviate 集合。
如果你在 Colab 中打开此 Notebook,可能需要安装 LlamaIndex 🦙。
%pip install llama-index-vector-stores-weaviate!pip install llama-index weaviate-clientimport logging
import sys
logging.basicConfig(stream=sys.stdout, level=logging.INFO)
logging.getLogger().addHandler(logging.StreamHandler(stream=sys.stdout))我们将使用 GPT-4 的推理能力来推断元数据过滤器。根据你的用例,"gpt-3.5-turbo" 也可以胜任。
# set up OpenAI
import os
import getpass
import openai
os.environ["OPENAI_API_KEY"] = getpass.getpass("OpenAI API Key:")
openai.api_key = os.environ["OPENAI_API_KEY"]from llama_index.embeddings.openai import OpenAIEmbedding
from llama_index.llms.openai import OpenAI
from llama_index.core.settings import Settings
Settings.llm = OpenAI(model="gpt-4")
Settings.embed_model = OpenAIEmbedding()本 Notebook 以嵌入式模式使用 Weaviate,该模式支持 Linux 和 macOS。
如果你更想尝试 Weaviate 的全托管服务 Weaviate Cloud Services (WCS),可以启用注释中的代码。
import weaviate
from weaviate.embedded import EmbeddedOptions
# Connect to Weaviate client in embedded mode
client = weaviate.connect_to_embedded()
# Enable this code if you want to use Weaviate Cloud Services instead of Embedded mode.
"""
import weaviate
# cloud
cluster_url = ""
api_key = ""
client = weaviate.connect_to_wcs(cluster_url=cluster_url,
auth_credentials=weaviate.auth.AuthApiKey(api_key),
)
# local
# client = weaviate.connect_to_local()
"""定义一些示例数据
我们向向量数据库中插入一些包含文本分块的示例节点。请注意,每个 TextNode 不仅包含文本,还包含元数据,例如 category 和 country。这些元数据字段将按原样转换/存储在底层向量数据库中。
from llama_index.core.schema import TextNode
nodes = [
TextNode(
text=(
"Michael Jordan is a retired professional basketball player,"
" widely regarded as one of the greatest basketball players of all"
" time."
),
metadata={
"category": "Sports",
"country": "United States",
},
),
TextNode(
text=(
"Angelina Jolie is an American actress, filmmaker, and"
" humanitarian. She has received numerous awards for her acting"
" and is known for her philanthropic work."
),
metadata={
"category": "Entertainment",
"country": "United States",
},
),
TextNode(
text=(
"Elon Musk is a business magnate, industrial designer, and"
" engineer. He is the founder, CEO, and lead designer of SpaceX,"
" Tesla, Inc., Neuralink, and The Boring Company."
),
metadata={
"category": "Business",
"country": "United States",
},
),
TextNode(
text=(
"Rihanna is a Barbadian singer, actress, and businesswoman. She"
" has achieved significant success in the music industry and is"
" known for her versatile musical style."
),
metadata={
"category": "Music",
"country": "Barbados",
},
),
TextNode(
text=(
"Cristiano Ronaldo is a Portuguese professional footballer who is"
" considered one of the greatest football players of all time. He"
" has won numerous awards and set multiple records during his"
" career."
),
metadata={
"category": "Sports",
"country": "Portugal",
},
),
]使用 Weaviate 向量存储构建向量索引
这里我们将数据加载到向量存储中。如上所述,每个节点的文本和元数据都会转换为 Weaviate 中对应的表示形式。现在,我们可以基于 Weaviate 中的这些数据运行语义查询和元数据过滤。
from llama_index.core import VectorStoreIndex, StorageContext
from llama_index.vector_stores.weaviate import WeaviateVectorStore
vector_store = WeaviateVectorStore(
weaviate_client=client, index_name="LlamaIndex_filter"
)
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.types import MetadataInfo, VectorStoreInfo
vector_store_info = VectorStoreInfo(
content_info="brief biography of celebrities",
metadata_info=[
MetadataInfo(
name="category",
type="str",
description=(
"Category of the celebrity, one of [Sports, Entertainment,"
" Business, Music]"
),
),
MetadataInfo(
name="country",
type="str",
description=(
"Country of the celebrity, one of [United States, Barbados,"
" Portugal]"
),
),
],
)
retriever = VectorIndexAutoRetriever(
index, vector_store_info=vector_store_info
)在一些示例数据上运行
我们尝试在一些示例数据上运行。注意元数据过滤器是如何被推断出来的——这有助于实现更精确的检索!
response = retriever.retrieve("Tell me about celebrities from United States")print(response[0])response = retriever.retrieve(
"Tell me about Sports celebrities from United States"
)print(response[0])