RAG高級優(yōu)化:檢索策略探討Fusion, HyDE安排上
- Fusion retrieval:基于向量和基于bm25的檢索
- HyDE(假設文檔嵌入):通過根據(jù)查詢生成和嵌入假設文檔來增強檢索。
- RAG-Fusion:通過結(jié)合多次搜索迭代的結(jié)果來提高檢索質(zhì)量。
高級 RAG 技術介紹
Fusion Retrieval
融合檢索是一種強大的文檔搜索方法,它結(jié)合了語義理解和關鍵字匹配的優(yōu)勢。通過利用基于向量和BM25的檢索方法,它為信息檢索任務提供了更全面、更靈活的解決方案。這種方法在概念相似性和關鍵字相關性都很重要的各個領域都有潛在的應用,例如學術研究、法律文檔搜索或通用搜索引擎。
實現(xiàn)方法:
- 接受一個查詢,并執(zhí)行基于向量和基于bm25的檢索。
- 兩種方法的得分歸一化到一個共同的尺度。
- 計算這些分數(shù)的加權(quán)組合(由alpha參數(shù)控制)。
- 根據(jù)綜合得分對文檔進行排名,并返回前k個結(jié)果。
優(yōu)點:
提高檢索質(zhì)量:通過結(jié)合語義搜索和基于關鍵字的搜索,系統(tǒng)可以捕獲概念相似度和精確的關鍵字匹配。
靈活性:alpha參數(shù)允許根據(jù)特定用例或查詢類型調(diào)整矢量和關鍵字搜索之間的平衡。
健壯性:組合方法可以有效地處理更大范圍的查詢,減輕單個方法的弱點。
可定制性:該系統(tǒng)可以很容易地適應使用不同的矢量存儲或基于關鍵字的檢索方法。
實現(xiàn)圖
下面的圖表說明了流程(最后一部分給出了實現(xiàn)代碼):
HyDE
HyDE 是什么?
HyDE 是一種創(chuàng)新方法,可增強密集檢索,尤其是在零樣本場景中。其工作原理如下:
- 查詢擴展:HyDE 使用語言模型根據(jù)用戶的查詢生成假設答案或文檔。
- 增強嵌入:這些假設文檔被嵌入,從而創(chuàng)建了更豐富的語義搜索空間。
- 相似性搜索:嵌入用于查找數(shù)據(jù)庫中最相關的實際文檔。
- 知情生成:檢索到的文檔和原始查詢用于生成最終響應。
實現(xiàn)圖
下面的圖表說明了 HyDE 流程:
圖片
RAG-Fusion
什么是 RAG-Fusion?
RAG-Fusion 是一種先進的技術,它將檢索增強生成 (RAG) 與互易秩融合 (RRF) 相結(jié)合,以提高檢索信息的質(zhì)量和相關性。其工作原理如下:
- 查詢擴展:利用原始查詢生成多個相關查詢,為用戶的問題提供不同的視角。
- 多次檢索:每個生成的查詢都用于從數(shù)據(jù)庫中檢索相關文檔。
- 倒數(shù)秩融合:使用 RRF 算法對檢索到的文檔進行重新排序,該算法結(jié)合了多次檢索嘗試的排名。
- 增強 RAG:重新排序的文檔以及原始和生成的查詢用于生成最終響應。
與傳統(tǒng) RAG 相比,這種方法有助于捕捉更廣泛的背景和潛在的更多相關信息。
實現(xiàn)圖
下面是說明 RAG-Fusion 工作流程的圖表:
圖片
Fusion retrieval實戰(zhàn)
加載依賴
import os
import sys
from dotenv import load_dotenv
from langchain.docstore.document import Document
from typing import List
from rank_bm25 import BM25Okapi
import numpy as np
bm25召回
def create_bm25_index(documents: List[Document]) -> BM25Okapi:
"""
Create a BM25 index from the given documents.
BM25 (Best Matching 25) is a ranking function used in information retrieval.
It's based on the probabilistic retrieval framework and is an improvement over TF-IDF.
Args:
documents (List[Document]): List of documents to index.
Returns:
BM25Okapi: An index that can be used for BM25 scoring.
"""
# Tokenize each document by splitting on whitespace
# This is a simple approach and could be improved with more sophisticated tokenization
tokenized_docs = [doc.page_content.split() for doc in documents]
return BM25Okapi(tokenized_docs)
混合召回
def fusion_retrieval(vectorstore, bm25, query: str, k: int = 5, alpha: float = 0.5) -> List[Document]:
"""
Perform fusion retrieval combining keyword-based (BM25) and vector-based search.
Args:
vectorstore (VectorStore): The vectorstore containing the documents.
bm25 (BM25Okapi): Pre-computed BM25 index.
query (str): The query string.
k (int): The number of documents to retrieve.
alpha (float): The weight for vector search scores (1-alpha will be the weight for BM25 scores).
Returns:
List[Document]: The top k documents based on the combined scores.
"""
# Step 1: Get all documents from the vectorstore
all_docs = vectorstore.similarity_search("", k=vectorstore.index.ntotal)
# Step 2: Perform BM25 search
bm25_scores = bm25.get_scores(query.split())
# Step 3: Perform vector search
vector_results = vectorstore.similarity_search_with_score(query, k=len(all_docs))
# Step 4: Normalize scores
vector_scores = np.array([score for _, score in vector_results])
vector_scores = 1 - (vector_scores - np.min(vector_scores)) / (np.max(vector_scores) - np.min(vector_scores))
bm25_scores = (bm25_scores - np.min(bm25_scores)) / (np.max(bm25_scores) - np.min(bm25_scores))
# Step 5: Combine scores
combined_scores = alpha * vector_scores + (1 - alpha) * bm25_scores
# Step 6: Rank documents
sorted_indices = np.argsort(combined_scores)[::-1]
# Step 7: Return top k documents
return [all_docs[i] for i in sorted_indices[:k]]