feat: RAG 混合检索可测核心(BM25 / RRF / 去重 / 降级,75 项离线单测)

This commit is contained in:
2026-10-03 08:34:28 +08:00
commit 1b4e6a5ad6
13 changed files with 1282 additions and 0 deletions
+88
View File
@@ -0,0 +1,88 @@
"""BM25 关键词检索 —— 从生产检索库抽出、去掉重依赖的可测版本。
生产对照:本文件是 `~/toolsite/kb_index_lib.py` 中 `tokenize` / `BM25Index`
的等价实现(L1098-1152),逐行保持一致。生产版同文件还承担 ChromaDB、
torch、增量同步、索引锁等职责,因此**无法脱离那些重依赖单独测试**。
这里只保留 BM25 本身:分词 + idf + 词频饱和 + 文档长度归一化。
零第三方依赖,构造一个 BM25Index 只需要一个list[str],不需要向量库。
分词策略(与生产一致):ASCII 词整体保留,中文取 bigram(单字则取单字)。
bigram 的取舍:中文不做词典分词,靠二元组近似"词",避免引入分词库依赖,
代价是索引变大、单个字的语义弱 —— 这是刻意的工程取舍,不是偷懒。
"""
from __future__ import annotations
import math
import re
from collections import Counter
_ASCII_RE = re.compile(r"[a-zA-Z0-9_]+")
_CJK_RE = re.compile(r"[一-鿿]+")
def tokenize(text: str) -> list[str]:
"""中英文轻量分词:ASCII 词 + 中文 bigram/单字。"""
text = text.lower()
toks: list[str] = []
for m in _ASCII_RE.finditer(text):
toks.append(m.group())
for run in _CJK_RE.findall(text):
if len(run) == 1:
toks.append(run)
else:
toks.extend(run[i : i + 2] for i in range(len(run) - 1))
return toks
class BM25Index:
"""Okapi BM25(k1=1.5, b=0.75)。构建一次后只读,进程内复用。
与生产库同款参数。k1 控制词频饱和速度,b 控制文档长度归一化强度。
"""
def __init__(self, docs: list[str], k1: float = 1.5, b: float = 0.75):
self.k1, self.b = k1, b
self._tokenized = [tokenize(d) for d in docs]
self.N = len(self._tokenized)
self.avgdl = sum(len(d) for d in self._tokenized) / max(1, self.N)
self._doc_freqs: list[Counter] = []
df = Counter()
for doc in self._tokenized:
freq = Counter(doc)
self._doc_freqs.append(freq)
for t in freq:
df[t] += 1
self._df = df
self.idf = {
t: math.log(1 + (self.N - n + 0.5) / (n + 0.5)) for t, n in df.items()
}
def score_all(self, query: str) -> list[float]:
"""返回每个文档的 BM25 分数(无命中的为 0.0)。"""
q_toks = [t for t in tokenize(query) if t in self.idf]
if not q_toks:
return [0.0] * self.N
scores = [0.0] * self.N
for t in q_toks:
idf = self.idf[t]
for i in range(self.N):
tf = self._doc_freqs[i].get(t, 0)
if tf == 0:
continue
dl = len(self._tokenized[i])
denom = tf + self.k1 * (1 - self.b + self.b * dl / self.avgdl)
scores[i] += idf * tf * (self.k1 + 1) / denom
return scores
def top_n(self, query: str, n: int = 20, min_score: float = 0.0) -> list[tuple[int, float]]:
"""返回 [(下标, 分数), ...] 按分数降序,最多 n 条,分数 > min_score。
生产库在 `search_hybrid` 里内联做这件事(`kb_index_lib.py:1300-1304`);
抽成方法是为了让它可被单测覆盖——那段内联代码里的 `scores[i] <= 0: continue`
是防"BM25 侧塞入全零项污染融合池"的关键分支,不能只靠肉眼保证。
"""
scores = self.score_all(query)
order = sorted(range(len(scores)), key=lambda i: scores[i], reverse=True)
return [(i, scores[i]) for i in order[:n] if scores[i] > min_score]