1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60
| import math, re from collections import Counter, defaultdict from dataclasses import dataclass import numpy as np
@dataclass(slots=True) class Chunk: id: str source: str text: str
def chunk_markdown(source: str, content: str) -> list[Chunk]: """按二级标题切分,保留标题上下文,避免硬切撕裂语义。""" parts = re.split(r"(?m)^(?=##\s+)", content.strip()) return [Chunk(id=f"{source}#{i}", source=source, text=p.strip()) for i, p in enumerate(parts) if p.strip()]
def tokenize(text: str) -> list[str]: return re.findall(r"[a-zA-Z0-9_]+|[\u4e00-\u9fff]", text.lower())
class MiniHybridRAG: def __init__(self, chunks: list[Chunk], embed_fn) -> None: self.chunks = chunks self.embed_fn = embed_fn vecs = np.asarray(embed_fn([c.text for c in chunks]), dtype=np.float32) self.mat = vecs / np.maximum(np.linalg.norm(vecs, axis=1, keepdims=True), 1e-12) self.docs_tok = [tokenize(c.text) for c in chunks] self.avg_dl = sum(len(t) for t in self.docs_tok) / max(len(self.docs_tok), 1) df = Counter(tok for doc in self.docs_tok for tok in set(doc)) n = len(self.docs_tok) self.idf = {t: math.log((n - c + 0.5) / (c + 0.5) + 1.0) for t, c in df.items()}
def _bm25_rank(self, query: str, k1: float = 1.5, b: float = 0.75) -> list[int]: q_toks = tokenize(query) scores = [] for idx, doc in enumerate(self.docs_tok): tf = Counter(doc) dl = len(doc) s = sum( self.idf.get(t, 0.0) * (tf[t] * (k1 + 1)) / (tf[t] + k1 * (1 - b + b * dl / self.avg_dl)) for t in q_toks if t in tf ) scores.append((s, idx)) return [idx for _, idx in sorted(scores, reverse=True)]
def search(self, query: str, top_k: int = 4, rrf_k: int = 60) -> list[Chunk]: q_vec = np.asarray(self.embed_fn([query])[0], dtype=np.float32) q_vec /= max(float(np.linalg.norm(q_vec)), 1e-12) dense_order = np.argsort(-(self.mat @ q_vec)).tolist() bm25_order = self._bm25_rank(query)
rrf: dict[int, float] = defaultdict(float) for rank, idx in enumerate(dense_order[:20], start=1): rrf[idx] += 1.0 / (rrf_k + rank) for rank, idx in enumerate(bm25_order[:20], start=1): rrf[idx] += 1.0 / (rrf_k + rank)
best_ids = [idx for idx, _ in sorted(rrf.items(), key=lambda x: x[1], reverse=True)[:top_k]] return [self.chunks[i] for i in best_ids]
|