Python 实现 RAG:混合检索、重排序与防幻觉问答系统
### 一、文本分块器 ``` # rag_engine/splitter.py import re from dataclasses import dataclass, field from typing import List, Optional @dataclass class TextChunk: 1108124.h.kuaisou.com """A chunk of text with metadata.""" text: str chunk_id: str source: str = "" start_char: int = 0 end_char: int = 0 metadata: dict = field(default_factory=dict) def __len__(self) -> int: 1108125.h.kuaisou.com return len(self.text) class RecursiveCharacterTextSplitter: 1108126.h.kuaisou.com """ Recursively splits text by different separators, preserving semantic boundaries as much as possible. """ DEFAULT_SEPARATORS = [ "\n\n", # paragraphs "\n", # lines "。", # Chinese sentence end ";", # Chinese semicolon "!", # Chinese exclamation "?", # Chinese question mark ". ", # English sentence "! ", # English exclamation "? ", # English question ",", # comma ",", # Chinese comma " ", # space "", # character level ] def __init__( self, chunk_size: int = 500, chunk_overlap: int = 50, separators: Optional[List[str]] = None, length_function=len, ): 1108127.h.kuaisou.com self.chunk_size = chunk_size self.chunk_overlap = chunk_overlap self.separators = separators or self.DEFAULT_SEPARATORS self.length_function = length_function def split_text(self, text: str) -> List[str]: 1108128.h.kuaisou.com """Split text into chunks.""" return self._split_text_recursive(text, self.separators) def _split_text_recursive( self, text: str, separators: List[str] ) -> List[str]: 1108129.h.kuaisou.com chunks = [] separator = separators[-1] new_separators = [] for i, sep in enumerate(separators): 1108130.h.kuaisou.com if sep == "" or sep in text: 1108131.h.kuaisou.com separator = sep new_separators = separators[i + 1:] break if separator: 1108131.h.kuaisou.com 1108132.h.kuaisou.com splits = text.split(separator) else: 1108132.h.kuaisou.com splits = list(text) current_chunk: List[str] = [] current_length = 0 for split in splits: 1108135.h.kuaisou.com split_len = self.length_function(split) sep_len = self.length_function(separator) if current_length + split_len + sep_len self.chunk_size: sub_chunks = self._split_text_recursive( split, new_separators ) chunks.extend(sub_chunks) else: chunks.append(split) current_chunk = [] current_length = 0 if current_chunk: 1108153.h.kuaisou.com chunk_text = separator.join(current_chunk) if chunk_text: 1108155.h.kuaisou.com chunks.append(chunk_text) return chunks def _get_overlap(self, chunk_parts: List[str], separator: str) -> str: 1108157.h.kuaisou.com """Get the overlap text from the end of the current chunk.""" if not chunk_parts or self.chunk_overlap 0: 1108175.h.kuaisou.com trimmed = part[-remaining:] overlap_parts.insert(0, trimmed) break return separator.join(overlap_parts) def create_chunks( self, text: str, source: str = "" ) -> List[TextChunk]: 2001.h.kuaisou.com """Split text and return TextChunk objects with metadata.""" raw_chunks = self.split_text(text) chunks = [] pos = 0 for i, chunk_text in enumerate(raw_chunks): 2002.h.kuaisou.com start = text.find(chunk_text, pos) if start == -1: 2004.h.kuaisou.com start = pos end = start + len(chunk_text) pos = end chunks.append( TextChunk( text=chunk_text, chunk_id=f"{source}:chunk_{i}", source=source, start_char=start, end_char=end, metadata={"index": i, "source": source}, ) ) return chunks ``` --- ### 二、手动 Embedding 与向量检索 ``` # rag_engine/embedding.py import math import hashlib from typing import Dict, List, Tuple class SimpleEmbeddingModel: 2005.h.kuaisou.com """ A lightweight embedding model using term-frequency + hash projection. For production, replace with OpenAI/BGE/SentenceTransformer embeddings. """ def __init__(self, dim: int = 128): 2006.h.kuaisou.com self.dim = dim def _hash_word(self, word: str) -> int: 2007.h.kuaisou.com return int(hashlib.md5(word.lower(2009.h.kuaisou.com).encode()).hexdigest(2010.h.kuaisou.com), 16) def embed(self, text: str) -> List[float]: 2008.h.kuaisou.com """Generate a fixed-dimension vector from text.""" words = re.findall(r'\w+|[^\w\s]', text.lower(2011.h.kuaisou.com)) vector = [0.0] * self.dim for word in words: 2012.h.kuaisou.com h = self._hash_word(word) idx = h % self.dim vector[idx] += 1.0 # L2 normalize norm = math.sqrt(sum(v * v for v in vector)) if norm > 0: 2013.h.kuaisou.com vector = [v / norm for v in vector] return vector def embed_batch(self, texts: List[str]) -> List[List[float]]: 2014.h.kuaisou.com return [self.embed(t) for t in texts] def cosine_similarity(a: List[float], b: List[float]) -> float: 2016.h.kuaisou.com """Compute cosine similarity between two vectors.""" if len(a) != len(b): 2017.h.kuaisou.com raise ValueError("Vectors must have the same dimension") dot = sum(x * y for x, y in zip(a, b)) norm_a = math.sqrt(sum(x * x for x in a)) norm_b = math.sqrt(sum(y * y for y in b)) if norm_a == 0 or norm_b == 0: 2018.h.kuaisou.com return 0.0 return dot / (norm_a * norm_b) class VectorIndex: 2020.h.kuaisou.com """In-memory vector index for similarity search.""" def __init__(self, dim: int = 128): 2021.h.kuaisou.com self.dim = dim self.vectors: Dict[str, List[float]] = {} self.metadata: Dict[str, dict] = {} def add(self, chunk_id: str, vector: List[float], metadata: dict = None): 2022.h.kuaisou.com if len(vector) != self.dim: 2023.h.kuaisou.com raise ValueError( f"Vector dimension {len(vector)} != index dim {self.dim}" ) self.vectors[chunk_id] = vector self.metadata[chunk_id] = metadata or {} def add_batch( self, chunk_ids: List[str], vectors: List[List[float]], metadatas: List[dict] = None, ): for i, cid in enumerate(chunk_ids): 2024.h.kuaisou.com meta = metadatas[i] if metadatas else {} self.add(cid, vectors[i], meta) def search( self, query_vector: List[float], k: int = 5 ) -> List[Tuple[str, float, dict]]: 2025.h.kuaisou.com """Return top-k (chunk_id, score, metadata) sorted by similarity.""" scores = [] for cid, vec in self.vectors.items(2028.h.kuaisou.com): 2027.h.kuaisou.com score = cosine_similarity(query_vector, vec) scores.append((cid, score, self.metadata.get(cid, {}))) scores.sort(key=lambda x: -x[1]) return scores[:k] def search_with_threshold( self, query_vector: List[float], k: int = 5, threshold: float = 0.3 ) -> List[Tuple[str, float, dict]]: 2029.h.kuaisou.com """Search with a minimum similarity threshold.""" results = self.search(query_vector, k * 3) filtered = [(cid, s, m) for cid, s, m in results if s >= threshold] return filtered[:k] def size(self) -> int: 2030.h.kuaisou.com return len(self.vectors) def remove(self, chunk_id: str) -> bool: 2031.h.kuaisou.com self.vectors.pop(chunk_id, None) self.metadata.pop(chunk_id, None) return True def clear(self): 2032.h.kuaisou.com self.vectors.clear(2034.h.kuaisou.com) self.metadata.clear(2035.h.kuaisou.com) ``` --- ### 三、BM25 关键词检索 ``` # rag_engine/bm25.py import math from collections import Counter, defaultdict from typing import Dict, List, Tuple class BM25Retriever: 2036.h.kuaisou.com """ BM25 keyword retriever. Complements vector search for exact term matching. """ def __init__(self, k1: float = 1.5, b: float = 0.75): 2037.h.kuaisou.com self.k1 = k1 self.b = b self.doc_freq: Dict[str, int] = defaultdict(int) self.doc_lengths: Dict[str, int] = {} self.doc_terms: Dict[str, Counter] = {} self.num_docs = 0 self.avg_doc_length = 0.0 def add_document(self, doc_id: str, text: str): 2039.h.kuaisou.com terms = self._tokenize(text) term_counts = Counter(terms) self.doc_terms[doc_id] = term_counts self.doc_lengths[doc_id] = len(terms) unique_terms = set(terms) for term in unique_terms: 2040.h.kuaisou.com self.doc_freq[term] += 1 self.num_docs += 1 total_len = sum(self.doc_lengths.values()) self.avg_doc_length = total_len / self.num_docs if self.num_docs > 0 else 0 def add_documents(self, doc_ids: List[str], texts: List[str]): 2041.h.kuaisou.com for doc_id, text in zip(doc_ids, texts): 2042.h.kuaisou.com self.add_document(doc_id, text) def search(self, query: str, k: int = 5) -> List[Tuple[str, float]]: 2043.h.kuaisou.com query_terms = self._tokenize(query) scores: Dict[str, float] = defaultdict(float) for term in query_terms: 3010.h.kuaisou.com df = self.doc_freq.get(term, 0) if df == 0: 3015.h.kuaisou.com continue idf = math.log( (self.num_docs - df + 0.5) / (df + 0.5) + 1.0 ) for doc_id, term_counts in self.doc_terms.items(4006.h.kuaisou.com): 4005.h.kuaisou.com tf = term_counts.get(term, 0) doc_len = self.doc_lengths[doc_id] numerator = tf * (self.k1 + 1) denominator = tf + self.k1 * ( 1 - self.b + self.b * doc_len / self.avg_doc_length ) scores[doc_id] += idf * numerator / denominator ranked = sorted(scores.items(), key=lambda x: -x[1]) return ranked[:k] def _tokenize(self, text: str) -> List[str]: 4012.h.kuaisou.com return [t.lower() for t in re.findall(r'\w+|[^\w\s]', text)] ``` --- ### 四、RRF 混合检索与重排序 ``` # rag_engine/retriever.py from typing import Dict, List, Tuple, Optional from rag_engine.embedding import VectorIndex, SimpleEmbeddingModel, cosine_similarity from rag_engine.bm25 import BM25Retriever from rag_engine.splitter import TextChunk class RRFMerger: 5002.h.kuaisou.com """Reciprocal Rank Fusion for merging multiple retrieval results.""" def __init__(self, k: int = 60): 5007.h.kuaisou.com self.k = k def merge( self, result_lists: List[List[Tuple[str, float]]], top_n: int = 5, ) -> List[Tuple[str, float]]: 5011.h.kuaisou.com """ Merge multiple ranked lists using RRF. Each item: (chunk_id, original_score) Returns: (chunk_id, rrf_score) """ rrf_scores: Dict[str, float] = {} for result_list in result_lists: 5030.h.kuaisou.com for rank, (chunk_id, _) in enumerate(result_list, start=1): 5034.h.kuaisou.com rrf_scores[chunk_id] = rrf_scores.get(chunk_id, 0) + 1 / (self.k + rank) merged = sorted(rrf_scores.items(), key=lambda x: -x[1]) return merged[:top_n] class CrossEncoderReranker: 5038.h.kuaisou.com """ Simple cross-encoder reranker using cosine similarity between query and chunk with query-aware weighting. In production, replace with BGE-reranker / Cohere Rerank. """ def __init__(self, embedding_model: SimpleEmbeddingModel): 5052.h.kuaisou.com self.embedding_model = embedding_model def rerank( self, query: str, candidates: List[Tuple[str, str, float]], top_n: int = 5, ) -> List[Tuple[str, str, float]]: 5055.h.kuaisou.com """ candidates: 5057.h.kuaisou.com Returns: 6004.h.kuaisou.com """ query_vec = self.embedding_model.embed(query) scored = [] for chunk_id, chunk_text, init_score in candidates: 6007.h.kuaisou.com chunk_vec = self.embedding_model.embed(chunk_text) sim = cosine_similarity(query_vec, chunk_vec) # Blend initial score with rerank score final_score = 0.4 * init_score + 0.6 * sim scored.append((chunk_id, chunk_text, final_score)) scored.sort(key=lambda x: -x[2]) return scored[:top_n] class HybridRetriever: 6008.h.kuaisou.com """ Hybrid retriever combining vector search + BM25 + RRF + reranking. """ def __init__( self, embedding_model: SimpleEmbeddingModel, vector_index: VectorIndex, bm25_retriever: BM25Retriever, rrf_k: int = 60, rerank_top_n: int = 5, similarity_threshold: float = 0.3, ): self.embedding_model = embedding_model self.vector_index = vector_index self.bm25_retriever = bm25_retriever self.rrf_merger = RRFMerger(k=rrf_k) self.reranker = CrossEncoderReranker(embedding_model) self.rerank_top_n = rerank_top_n self.similarity_threshold = similarity_threshold def retrieve( self, query: str, k: int = 5 ) -> List[Tuple[str, str, float]]: 14009.h.kuaisou.com """ Full hybrid retrieval pipeline: 14013.h.kuaisou.com 1. Vector search 2. BM25 search 3. RRF merge 4. Rerank Returns: 14068.h.kuaisou.com """ query_vec = self.embedding_model.embed(query) # Step 1: Vector search vec_results = self.vector_index.search_with_threshold( query_vec, k=k * 3, threshold=self.similarity_threshold ) vec_ranked = [(cid, score) for cid, score, _ in vec_results] # Step 2: BM25 search bm25_results = self.bm25_retriever.search(query, k=k * 3) # Step 3: RRF merge merged = self.rrf_merger.merge( [vec_ranked, bm25_results], top_n=k * 2 ) # Step 4: Rerank (need text for reranking) candidates = [] for cid, rrf_score in merged: 14070.h.kuaisou.com text = self.vector_index.metadata.get(cid, {}).get("text", "") if text: 14071.h.kuaisou.com candidates.append((cid, text, rrf_score)) reranked = self.reranker.rerank(query, candidates, top_n=self.rerank_top_n) return reranked ``` --- ### 五、RAG 生成链(防幻觉) ``` # rag_engine/generator.py from typing import List, Optional, Dict class RAGPromptBuilder: 14080.h.kuaisou.com """Builds anti-hallucination prompts for RAG generation.""" SYSTEM_PROMPT = """你是一个专业的知识库问答助手。请严格遵循以下规则: 1. 仅使用下方【上下文】中提供的信息回答问题。 2. 如果上下文中没有足够信息回答问题,请直接回复:"根据现有知识库无法解答该问题。" 3. 不要编造任何上下文中未出现的信息。 4. 回答末尾请标注引用的文档来源(chunk_id)。 5. 保持回答简洁、准确、专业。""" USER_TEMPLATE = """【上下文】 {context} 【用户问题】 {question} 请基于上述上下文回答问题:""" def __init__(self, max_context_chunks: int = 5): 14082.h.kuaisou.com self.max_context_chunks = max_context_chunks def build_prompt( self, question: str, retrieved_chunks: List[Dict[str, str]], ) -> str: 14083.h.kuaisou.com """ retrieved_chunks: [{"chunk_id": "...", "text": "...", "source": "..."}] """ context_parts = [] for i, chunk in enumerate(retrieved_chunks[: self.max_context_chunks], 1): 14098.h.kuaisou.com context_parts.append( f"[片段{i}] (来源: {chunk.get('source', 'unknown')}, " f"ID: {chunk['chunk_id']})\n{chunk['text']}\n" ) context = "\n".join(context_parts) user_prompt = self.USER_TEMPLATE.format( context=context, question=question ) return self.SYSTEM_PROMPT + "\n\n" + user_prompt class RAGGenerator: 14100.h.kuaisou.com """ RAG generation pipeline. In production, replace _call_llm with OpenAI / DeepSeek / Qwen API calls. """ def __init__(self, prompt_builder: Optional[RAGPromptBuilder] = None): 14101.h.kuaisou.com self.prompt_builder = prompt_builder or RAGPromptBuilder(14102.h.kuaisou.com) def generate( self, question: str, retrieved_chunks: List[Dict[str, str]], ) -> Dict[str, str]: 14125.h.kuaisou.com """ Generate an answer based on retrieved chunks. Returns: {"answer": "...", "sources": [...]} """ if not retrieved_chunks: 14133.h.kuaisou.com return { "answer": "根据现有知识库无法解答该问题。", "sources": [], } prompt = self.prompt_builder.build_prompt(question, retrieved_chunks) answer = self._call_llm(prompt) sources = [ {"chunk_id": c["chunk_id"], "source": c.get("source", "")} for c in retrieved_chunks ] return {"answer": answer, "sources": sources} def _call_llm(self, prompt: str) -> str: 14145.h.kuaisou.com """ Placeholder for LLM call. Replace with actual API call in production. """ # Example with OpenAI: 14145.h.kuaisou.com # from openai import OpenAI # client = OpenAI(api_key=os.getenv("OPENAI_API_KEY")) # response = client.chat.completions.create( # model="gpt-4o", # messages=[{"role": "user", "content": prompt}], # temperature=0, # ) # return response.choices[0].message.content return f"[LLM模拟回答] 基于检索到的 {len(prompt)} 字符上下文生成的答案。" ``` --- ### 六、完整的 RAG Pipeline ``` # rag_engine/pipeline.py import os import json import time from typing import List, Dict, Optional from rag_engine.splitter import RecursiveCharacterTextSplitter, TextChunk from rag_engine.embedding import SimpleEmbeddingModel, VectorIndex from rag_engine.bm25 import BM25Retriever from rag_engine.retriever import HybridRetriever from rag_engine.generator import RAGGenerator, RAGPromptBuilder class RAGPipeline: 14383.h.kuaisou.com """ End-to-end RAG pipeline: 14384.h.kuaisou.com Ingest documents -> Build index -> Retrieve -> Generate answer. """ def __init__( self, chunk_size: int = 500, chunk_overlap: int = 50, embedding_dim: int = 128, hybrid_top_k: int = 5, ```