RAG高級(jí)優(yōu)化:檢索策略探討Fusion, HyDE安排上
- Fusion retrieval:基于向量和基于bm25的檢索
- HyDE(假設(shè)文檔嵌入):通過(guò)根據(jù)查詢(xún)生成和嵌入假設(shè)文檔來(lái)增強(qiáng)檢索。
- RAG-Fusion:通過(guò)結(jié)合多次搜索迭代的結(jié)果來(lái)提高檢索質(zhì)量。
高級(jí) RAG 技術(shù)介紹
Fusion Retrieval
融合檢索是一種強(qiáng)大的文檔搜索方法,它結(jié)合了語(yǔ)義理解和關(guān)鍵字匹配的優(yōu)勢(shì)。通過(guò)利用基于向量和BM25的檢索方法,它為信息檢索任務(wù)提供了更全面、更靈活的解決方案。這種方法在概念相似性和關(guān)鍵字相關(guān)性都很重要的各個(gè)領(lǐng)域都有潛在的應(yīng)用,例如學(xué)術(shù)研究、法律文檔搜索或通用搜索引擎。
實(shí)現(xiàn)方法:
- 接受一個(gè)查詢(xún),并執(zhí)行基于向量和基于bm25的檢索。
- 兩種方法的得分歸一化到一個(gè)共同的尺度。
- 計(jì)算這些分?jǐn)?shù)的加權(quán)組合(由alpha參數(shù)控制)。
- 根據(jù)綜合得分對(duì)文檔進(jìn)行排名,并返回前k個(gè)結(jié)果。
優(yōu)點(diǎn):
提高檢索質(zhì)量:通過(guò)結(jié)合語(yǔ)義搜索和基于關(guān)鍵字的搜索,系統(tǒng)可以捕獲概念相似度和精確的關(guān)鍵字匹配。
靈活性:alpha參數(shù)允許根據(jù)特定用例或查詢(xún)類(lèi)型調(diào)整矢量和關(guān)鍵字搜索之間的平衡。
健壯性:組合方法可以有效地處理更大范圍的查詢(xún),減輕單個(gè)方法的弱點(diǎn)。
可定制性:該系統(tǒng)可以很容易地適應(yīng)使用不同的矢量存儲(chǔ)或基于關(guān)鍵字的檢索方法。
實(shí)現(xiàn)圖
下面的圖表說(shuō)明了流程(最后一部分給出了實(shí)現(xiàn)代碼):
HyDE
HyDE 是什么?
HyDE 是一種創(chuàng)新方法,可增強(qiáng)密集檢索,尤其是在零樣本場(chǎng)景中。其工作原理如下:
- 查詢(xún)擴(kuò)展:HyDE 使用語(yǔ)言模型根據(jù)用戶(hù)的查詢(xún)生成假設(shè)答案或文檔。
- 增強(qiáng)嵌入:這些假設(shè)文檔被嵌入,從而創(chuàng)建了更豐富的語(yǔ)義搜索空間。
- 相似性搜索:嵌入用于查找數(shù)據(jù)庫(kù)中最相關(guān)的實(shí)際文檔。
- 知情生成:檢索到的文檔和原始查詢(xún)用于生成最終響應(yīng)。
實(shí)現(xiàn)圖
下面的圖表說(shuō)明了 HyDE 流程:
圖片
RAG-Fusion
什么是 RAG-Fusion?
RAG-Fusion 是一種先進(jìn)的技術(shù),它將檢索增強(qiáng)生成 (RAG) 與互易秩融合 (RRF) 相結(jié)合,以提高檢索信息的質(zhì)量和相關(guān)性。其工作原理如下:
- 查詢(xún)擴(kuò)展:利用原始查詢(xún)生成多個(gè)相關(guān)查詢(xún),為用戶(hù)的問(wèn)題提供不同的視角。
- 多次檢索:每個(gè)生成的查詢(xún)都用于從數(shù)據(jù)庫(kù)中檢索相關(guān)文檔。
- 倒數(shù)秩融合:使用 RRF 算法對(duì)檢索到的文檔進(jìn)行重新排序,該算法結(jié)合了多次檢索嘗試的排名。
- 增強(qiáng) RAG:重新排序的文檔以及原始和生成的查詢(xún)用于生成最終響應(yīng)。
與傳統(tǒng) RAG 相比,這種方法有助于捕捉更廣泛的背景和潛在的更多相關(guān)信息。
實(shí)現(xiàn)圖
下面是說(shuō)明 RAG-Fusion 工作流程的圖表:
圖片
Fusion retrieval實(shí)戰(zhàn)
加載依賴(lài)
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]]