mirror of
https://github.com/ThearchyHelios/AgentLab.git
synced 2026-11-17 03:11:58 +00:00
e8ef6ff9a8
先做评测再做重排——否则重排的收益只能靠"搜两下感觉准了"。
**评测集**(test_retrieval_quality.py):24 篇语料 + 16 个问题,问题分成字面
重叠和纯语义两类。第一版是 8 篇、主指标 hit@3,结果各档 alpha 全是 100%,
等于什么都没量——8 选 3 瞎猜都有 37%。扩语料、加干扰、主指标换成 hit@1
之后才开始能分辨。
量出来的第一个结论就推翻了我原来的猜测:
alpha hit@1 hit@5 MRR 字面 语义
0.0 88% 100% 0.911 100% 75%
0.2 81% 100% 0.880 88% 75%
0.5 81% 100% 0.880 88% 75%
1.0 81% 100% 0.880 88% 75%
本地哈希向量那一路不是"弱一点",是**纯噪音**:给它任何权重,hit@1 都从 88%
掉到 81%。而 alpha 的默认值一直写死 0.5,等于主动把检索做差。改成跟着
embedder 能力走(default_alpha:有语义泛化才给 0.5,否则 0),节点上的
alpha 也不再写死默认值。
**重排**(memory/rerank.py):初筛多捞一些(20 条),让模型按"对回答这个问题
有多大帮助"重排,再取 top_n。只捞 5 条的话重排最多把这 5 条换个顺序,第 6
条是对的也救不回来。
用已配置的对话模型做,不引入本地 cross-encoder——后者要下模型权重,和"零配置
能跑起来"的基线冲突。代价是每次检索多一次调用,所以默认关闭。
失败一律退回初筛顺序并说一声:解析不出分数、个数对不上、模型抛异常、没配
provider,四条路径都有测试。重排是增强,不该因为模型抽风就让整个检索挂掉。
102 lines
3.8 KiB
Python
102 lines
3.8 KiB
Python
"""重排:让模型把初筛结果重新排一遍。
|
|
|
|
混合检索给的是"大致相关"——BM25 看词频,向量看空间距离,两者都不读句子。
|
|
重排让模型把 query 和每个候选放在一起判断,这是检索链路上单点收益最大的一步。
|
|
|
|
用已配置的对话模型做,不引入本地 cross-encoder:后者要下模型权重,和这个
|
|
项目"零配置能跑起来"的基线冲突(同理不照抄 RAGFlow 那套 Elasticsearch +
|
|
Infinity,官方建议 32GB 内存起)。代价是每次检索多一次模型调用,所以默认关闭。
|
|
|
|
失败一律退回原顺序:重排是增强,不该因为模型抽风或没配 key 就让整个检索挂掉。
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import json
|
|
import re
|
|
from typing import Any
|
|
|
|
_PROMPT = """给下面每个片段打分:它对回答这个问题有多大帮助。
|
|
|
|
问题:{query}
|
|
|
|
片段:
|
|
{candidates}
|
|
|
|
只输出一行 JSON,形如 {{"scores": [{example}]}}——{n} 个 0 到 10 的整数,
|
|
按片段顺序一一对应。不要输出任何别的东西。
|
|
0 表示完全无关,10 表示直接回答了问题。"""
|
|
|
|
|
|
def _parse_scores(text: str, n: int) -> list[float] | None:
|
|
"""从模型回复里抠出分数数组。
|
|
|
|
模型偶尔会加围栏或者说两句废话,所以不直接 json.loads 整段;
|
|
但也不做过度容错——解析不出来就退回原顺序,比按半截数据重排安全。
|
|
"""
|
|
match = re.search(r"\{[^{}]*\"scores\"\s*:\s*\[[^\]]*\][^{}]*\}", text, re.S)
|
|
if not match:
|
|
return None
|
|
try:
|
|
scores = json.loads(match.group(0)).get("scores")
|
|
except json.JSONDecodeError:
|
|
return None
|
|
if not isinstance(scores, list) or len(scores) != n:
|
|
# 个数对不上就没法一一对应,硬凑只会把顺序搅乱
|
|
return None
|
|
out: list[float] = []
|
|
for s in scores:
|
|
if not isinstance(s, (int, float)):
|
|
return None
|
|
out.append(float(s))
|
|
return out
|
|
|
|
|
|
async def rerank(
|
|
model: Any, query: str, hits: list[dict[str, Any]], *, top_n: int,
|
|
on_note: Any = None,
|
|
) -> list[dict[str, Any]]:
|
|
"""把 hits 重排后取前 top_n。失败原样返回前 top_n。
|
|
|
|
model 是任意带 ainvoke 的 LangChain 模型;传 None 表示不重排。
|
|
"""
|
|
if not hits or model is None or len(hits) <= 1:
|
|
return hits[:top_n]
|
|
|
|
listing = "\n\n".join(
|
|
# 截断是必要的:初筛 20 条 × 每条 800 字会把 prompt 撑到两万字,
|
|
# 而判断相关性用不着整段
|
|
f"[{i + 1}] {h.get('content', '')[:400]}"
|
|
for i, h in enumerate(hits)
|
|
)
|
|
prompt = _PROMPT.format(
|
|
query=query, candidates=listing, n=len(hits),
|
|
example=", ".join(["8"] * min(len(hits), 3)) + (", …" if len(hits) > 3 else ""),
|
|
)
|
|
|
|
try:
|
|
reply = await model.ainvoke(prompt)
|
|
text = reply if isinstance(reply, str) else getattr(reply, "content", "")
|
|
if isinstance(text, list): # Anthropic 的块状 content
|
|
text = "".join(b.get("text", "") for b in text if isinstance(b, dict))
|
|
scores = _parse_scores(str(text), len(hits))
|
|
except Exception as e: # noqa: BLE001
|
|
if on_note:
|
|
on_note(f"重排失败,按初筛顺序返回:{type(e).__name__}: {e}")
|
|
return hits[:top_n]
|
|
|
|
if scores is None:
|
|
if on_note:
|
|
on_note("重排结果解析不出来,按初筛顺序返回")
|
|
return hits[:top_n]
|
|
|
|
ranked = sorted(zip(hits, scores), key=lambda t: t[1], reverse=True)
|
|
out: list[dict[str, Any]] = []
|
|
for hit, score in ranked[:top_n]:
|
|
item = dict(hit)
|
|
item["rerank_score"] = score
|
|
# 初筛分保留:重排把它挪到第几位、原来是第几位,事后要能对照
|
|
item.setdefault("signals", {})
|
|
out.append(item)
|
|
return out
|