Files

122 lines
4.9 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""混合检索编排 —— 复刻生产 `search_hybrid` 的控制流,向量侧可注入。
生产对照:`kb_index_lib.py:1261-1354`(search_hybrid)。生产版里向量检索
那一路直接调 `search_structured()`(连 ChromaDB),BM25 那一路通过
`_bm25_cached()` 连向量库取语料——**两路都离不开索引**,所以整条链路在
单测里没法跑。
本文件把两路都做成参数:
- `vector_pool`:调用方给一份已排好序的向量检索结果(生产里是 ChromaDB 命中)
- `bm25_docs`:调用方给一份语料(生产里是从向量库读出的 documents)
于是整条链路可以**不建索引、不加载模型、纯内存**跑完,并且
`tests/test_pipeline.py` 能锁定那些真正容易出错的控制流:
1. 一路失败只丢一路,另一路仍出结果(降级不扩散)
2. 两路都失败 → 返回空列表,不抛异常
3.候选池大小与分页的相互作用(`pool_size` 必须覆盖 `k + offset`)
4. 无标题笔记的去重分支
5. 精排在分页之前发生(精排看的是更大的池子)
这五条都是生产里真实踩过或推演过的分支。
"""
from __future__ import annotations
from typing import Callable, Iterable
from .bm25 import BM25Index
from .fusion import dedupe_pool, item_key, paginate, rrf_fuse
from .rerank import rerank_candidates
RERANK_TOP_N = 20 # 精排候选池大小,与生产库一致
RRF_K = 60 # RRF 平滑常数,生产惯例取 60
def hybrid_fuse(
query: str,
vector_pool: Iterable[dict] | None = None,
bm25_docs: list[str] | None = None,
bm25_ids: list[str] | None = None,
k: int = 5,
offset: int = 0,
bm25_top: int = 20,
dedupe: bool = True,
rerank: bool = False,
rerank_scorer: Callable[[str, str], float] | None = None,
rerank_top_n: int = RERANK_TOP_N,
) -> list[dict]:
"""向量 top-N + BM25 top-N → RRF 融合 → 去重 → 可选精排 → 分页。
参数
----
vector_pool : 已按相似度降序的向量检索结果;None → 该路跳过
bm25_docs: BM25 语料;None → 该路跳过
bm25_ids: 与 bm25_docs 等长的块身份(如 parent_id)。**不传则两路无法对齐**
k, offset : 分页
rerank : 是否精排(默认关;生产库默认开,这里由 scorer 是否存在决定)
rerank_scorer : 打分器;None 时 rerank 无意义,等同不精排
返回
----
融合结果,每项含 `fusion`(RRF 分数)、`source_of`(vector/bm25/both)、
可选 `rerank_score`。**不修改入参**。
⚠️ `bm25_ids` 不是可选便利参数,是融合能否生效的前提。
RRF 靠身份键对齐两路:生产库里向量侧 `id` 是 chunk id,BM25 侧显式取
`meta["parent_id"]`(kb_index_lib.py:1310)才能对上同一节父块。两路
键不同 → 同一段内容被算成两条独立结果 → `source_of` 永远是 vector 或
bm25,不会出现 both,而"两路都认可"这个最可信的信号就此丢失,
**且不报错**。这正是本项目最初版本的一个真实缺陷,由
`tests/test_pipeline.py::test_agreement_marked_both` 拦下。
"""
pools: list[list[dict]] = []
if vector_pool is not None:
pools.append([dict(r, source_of=r.get("source_of", "vector")) for r in vector_pool])
if bm25_docs is not None:
if bm25_ids is not None and len(bm25_ids) != len(bm25_docs):
raise ValueError("bm25_ids 与 bm25_docs 必须等长")
idx = BM25Index(bm25_docs)
bm_pool: list[dict] = []
for i, score in idx.top_n(query, n=bm25_top):
if score <= 0:
continue
bm_pool.append(
{
"id": bm25_ids[i] if bm25_ids else f"bm25::{i}",
"file": f"doc-{i}",
"heading": f"doc-{i}",
"text": bm25_docs[i],
"similarity": 0.0,
"bm25_score": round(score, 4),
}
)
if bm_pool:
pools.append([dict(r, source_of="bm25") for r in bm_pool])
if not pools:
return []
# 先统计每条结果出现在几路里,供融合后标 source_of=both
seen_in: dict[str | tuple, int] = {}
for pool in pools:
for item in pool:
key = item_key(item)
seen_in[key] = seen_in.get(key, 0) + 1
fused = rrf_fuse(pools, k=RRF_K)
for item in fused:
item["source_of"] = (
"both" if seen_in.get(item_key(item), 1) > 1 else item.get("source_of", "vector")
)
pool_size = max(k + offset, rerank_top_n if rerank else k + offset)
pool = dedupe_pool(fused, pool_size=pool_size, dedupe=dedupe)
# 精排发生在分页之前:精排要看到整个候选池,分页只是取其中一段
if rerank and pool:
pool = rerank_candidates(query, pool, scorer=rerank_scorer)
return paginate(pool, k=k, offset=offset)