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
+90
View File
@@ -0,0 +1,90 @@
"""RRF 融合 + 去重 + 分页 —— 从生产检索库抽出的可测版本。
生产对照:`kb_index_lib.py:1185-1200`(rrf_fuse)与 `:1329-1354`(去重+分页)。
RRF(Reciprocal Rank Fusion)的全部价值在于**只吃排名不吃分数**。
向量相似度和 BM25 分数不在同一量纲,直接加权求和必须先归一化,而归一化
参数很难调;RRF 绕开这个问题:每个文档在每路里的贡献是 `1/(k+rank)`,
rank 从 0 开始。两路都认可 → 分数相加;只有一路认可 → 拿不到加成的那些
自然沉底。没有可调参数,没有量纲问题。
这是"混合检索"里唯一一个**不需要调参就能工作**的环节,也是我选它的原因。
"""
from __future__ import annotations
NO_HEADING = "(无标题)"
def item_key(item: dict) -> str | tuple:
"""融合去重键:优先 id,其次 (file, heading)。"""
return item.get("id") or (item.get("file", "?"), item.get("heading", NO_HEADING))
def rrf_fuse(lists: list[list[dict]], k: int = 60) -> list[dict]:
"""Reciprocal Rank Fusion:多个排序列表按 1/(k+rank) 求和取 top。
同一条结果在多路中出现时只保留一份(`first` 记录首次出现的那份),
分数累加。返回按 fusion 分数降序的新列表,**每项附加 `fusion` 字段**。
"""
scores: dict[str | tuple, float] = {}
first: dict[str | tuple, dict] = {}
for lst in lists:
for rank, item in enumerate(lst):
key = item_key(item)
scores[key] = scores.get(key, 0.0) + 1.0 / (k + rank + 1)
first.setdefault(key, item)
ranked = sorted(scores.items(), key=lambda x: x[1], reverse=True)
out = []
for key, sc in ranked:
item = dict(first[key])
item["fusion"] = round(sc, 4)
out.append(item)
return out
def dedupe_pool(
items: list[dict],
pool_size: int,
dedupe: bool = True,
) -> list[dict]:
"""按 (file, heading) 压掉同一节的重复块,截到候选池大小。
生产库这里有一条**不写测试就一定会被后人改错**的分支
(`kb_index_lib.py:1339-1342`):
无标题笔记整篇只有一个 heading,按 (file, heading) 去重会把整篇
压成一条结果。这种笔记退到按 (file, id) 去重,允许同文件多条。
早期版本漏了这个分支,表现为"检索某篇没写标题的笔记只出1 条结果,
且看起来像 bug"。已抽成 `dedupe_key()` 并在测试中锁定。
"""
if pool_size <= 0:
return []
seen: set = set()
pool: list[dict] = []
for item in items:
if dedupe:
key = dedupe_key(item)
if key in seen:
continue
seen.add(key)
pool.append(item)
if len(pool) >= pool_size:
break
return pool
def dedupe_key(item: dict) -> tuple:
"""去重键。无标题条目按 id 退化为块级去重(见 dedupe_pool 的docstring)。"""
heading = item.get("heading", NO_HEADING)
if heading == NO_HEADING:
return (item.get("file", "?"), item.get("id", ""))
return (item.get("file", "?"), heading)
def paginate(items: list[dict], k: int, offset: int = 0) -> list[dict]:
"""分页。offset 越界返回空列表而不是报错。"""
if offset < 0 or k < 0:
return []
return items[offset : offset + k]