基于 Python 的自然语言处理系列(61):RAG Fusion介绍

RAG Fusion 是一种检索方法,旨在弥合传统搜索范式与人类查询的多维特性之间的差距。本项目受 Retrieval Augmented Generation (RAG) 的启发,进一步采用 多查询生成互惠排序融合 (Reciprocal Rank Fusion, RRF) 来重新排名搜索结果,以提升检索效果。

本实现基于 该 GitHub 仓库 进行重构,所有贡献归原作者所有。

环境设置

本示例使用 Pinecone 作为向量数据库,并构造一组示例数据。

复制代码
import pinecone
from langchain.embeddings import OpenAIEmbeddings
from langchain.vectorstores import Pinecone

pinecone.init(api_key="...", environment="...")

all_documents = {
    "doc1": "Climate change and economic impact.",
    "doc2": "Public health concerns due to climate change.",
    "doc3": "Climate change: A social perspective.",
    "doc4": "Technological solutions to climate change.",
    "doc5": "Policy changes needed to combat climate change.",
    "doc6": "Climate change and its impact on biodiversity.",
    "doc7": "Climate change: The science and models.",
    "doc8": "Global warming: A subset of climate change.",
    "doc9": "How climate change affects daily weather.",
    "doc10": "The history of climate change activism."
}

vectorstore = Pinecone.from_texts(
    list(all_documents.values()), OpenAIEmbeddings(), index_name="rag-fusion"")

查询生成器

我们将定义一个 LangChain 查询生成链,该链可以基于单个查询生成多个相关查询。

复制代码
from langchain.chat_models import ChatOpenAI
from langchain.schema.output_parser import StrOutputParser
from langchain import hub

prompt = hub.pull("langchain-ai/rag-fusion-query-generation")

generate_queries = (
    prompt | ChatOpenAI(temperature=0) | StrOutputParser() | (lambda x: x.split("\n"))
)

定义完整检索链

该检索链的执行流程如下:

  1. 生成多个查询。

  2. 使用检索器查询每个子查询。

  3. 使用 互惠排序融合 (RRF) 对结果重新排名。

注意:此过程不会执行最终的生成步骤,仅进行检索和融合。

复制代码
original_query = "impact of climate change"
vectorstore = Pinecone.from_existing_index("rag-fusion", OpenAIEmbeddings())
retriever = vectorstore.as_retriever()

from langchain.load import dumps, loads

def reciprocal_rank_fusion(results: list[list], k=60):
    fused_scores = {}
    for docs in results:
        # 假设检索结果已按相关性排序
        for rank, doc in enumerate(docs):
            doc_str = dumps(doc)
            if doc_str not in fused_scores:
                fused_scores[doc_str] = 0
            fused_scores[doc_str] += 1 / (rank + k)

    reranked_results = [
        (loads(doc), score)
        for doc, score in sorted(fused_scores.items(), key=lambda x: x[1], reverse=True)
    ]
    return reranked_results

chain = generate_queries | retriever.map() | reciprocal_rank_fusion

# 执行查询
results = chain.invoke({"original_query": original_query})

结论

RAG Fusion 通过 多查询生成 + 互惠排序融合 ,提升了传统 RAG 框架的检索效果,适用于需要高精度检索的应用,如 科研论文、法律文档、技术资料 等。如果你有任何问题或改进建议,欢迎交流!

如果你觉得这篇博文对你有帮助,请点赞、收藏、关注我,并且可以打赏支持我!

欢迎关注我的后续博文,我将分享更多关于人工智能、自然语言处理和计算机视觉的精彩内容。

谢谢大家的支持!

相关推荐
p186848058101 小时前
ICFEEIE 2025 WS4:计算机视觉和自然语言处理中的深度学习模型和算法
深度学习·计算机视觉·自然语言处理
rqtz2 小时前
【C++指针】搭建起程序与内存深度交互的桥梁(下)
开发语言·c++·指针
AI让世界更懂你2 小时前
Python 包管理器 UV 全面介绍
开发语言·python·uv
milo.qu2 小时前
AI人工智能-Jupyter Notbook&Pycharm:Py开发
人工智能·python·jupyter·pycharm
IT猿手2 小时前
基于烟花算法(Fireworks Algorithm,FWA)及三次样条的机器人路径规划,50个场景任意选择,完整MATLAB代码
开发语言·算法·机器学习·matlab·机器人·无人机
厌世小晨宇yu.3 小时前
对Gpt关于泛型、Stream的提问
java·开发语言·gpt·ai
了一li3 小时前
2025年春招-Linux面经
开发语言·php
lllsure3 小时前
SpringMVC 拦截器(Interceptor)
java·开发语言·mysql
Learn-Share_HY3 小时前
[Python]如何利用Flask搭建一個Web服務器,並透過Ngrok訪問來實現LINE Bot功能?
linux·人工智能·python·ubuntu·flask·ollama·ngrok
花果山-马大帅3 小时前
我的机器学习学习之路
人工智能·python·算法·机器学习·scikit-learn