mirror of
https://github.com/ThearchyHelios/AgentLab.git
synced 2026-11-26 02:12:11 +00:00
检索质量有数了:评测集 + 重排,alpha 不再写死
先做评测再做重排——否则重排的收益只能靠"搜两下感觉准了"。
**评测集**(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,四条路径都有测试。重排是增强,不该因为模型抽风就让整个检索挂掉。
This commit is contained in:
@@ -143,6 +143,25 @@ def embedder_dim() -> int:
|
||||
return int(getattr(get_embedder(), "dim", _DIM))
|
||||
|
||||
|
||||
def has_semantics() -> bool:
|
||||
"""当前 embedder 有没有语义泛化能力。
|
||||
|
||||
LocalEmbedder 是词频哈希:它和 BM25 吃同一批词,给它权重等于把关键词
|
||||
信号打个折再加回自己身上,同义改写一条都召不回。
|
||||
"""
|
||||
return getattr(get_embedder(), "name", "") != "local-hashing"
|
||||
|
||||
|
||||
def default_alpha() -> float:
|
||||
"""向量那一路默认占多少权重。
|
||||
|
||||
实测(backend/tests/test_retrieval_quality.py,24 篇语料 / 16 问):
|
||||
本地哈希向量下 alpha=0 的 hit@1 是 88%,alpha 一旦大于 0 就掉到 81%
|
||||
——那一路不是"弱一点",是纯噪音。所以没有语义能力时默认给 0。
|
||||
"""
|
||||
return 0.5 if has_semantics() else 0.0
|
||||
|
||||
|
||||
def usable(embed_model: str | None, embed_dim: int | None) -> bool:
|
||||
"""这条存量向量还能不能和当前查询比对。
|
||||
|
||||
|
||||
@@ -8,7 +8,8 @@ from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.db.models import Chunk, Document
|
||||
from app.memory.embeddings import (
|
||||
embed_text, embed_texts, embedder_dim, embedder_id, from_blob, hybrid_rank, to_blob, usable,
|
||||
default_alpha, embed_text, embed_texts, embedder_dim, embedder_id, from_blob,
|
||||
hybrid_rank, to_blob, usable,
|
||||
)
|
||||
|
||||
_TARGET = 800
|
||||
@@ -116,7 +117,7 @@ async def search(
|
||||
collection: str | None,
|
||||
query: str,
|
||||
limit: int = 5,
|
||||
alpha: float = 0.5,
|
||||
alpha: float | None = None,
|
||||
on_degrade: Any = None,
|
||||
) -> list[dict[str, Any]]:
|
||||
"""混合检索。
|
||||
@@ -128,6 +129,11 @@ async def search(
|
||||
在此之前这里连维度都不查,换个 embedder 直接 ValueError
|
||||
(shapes (1536,) and (512,) not aligned),整个检索 500。
|
||||
"""
|
||||
# 没显式指定就跟着 embedder 走——写死 0.5 是在给一个没有语义能力的信号
|
||||
# 一半权重,实测会把 hit@1 从 88% 拉到 81%
|
||||
if alpha is None:
|
||||
alpha = default_alpha()
|
||||
|
||||
stmt = select(Chunk)
|
||||
if collection:
|
||||
stmt = stmt.where(Chunk.collection == collection)
|
||||
|
||||
@@ -0,0 +1,101 @@
|
||||
"""重排:让模型把初筛结果重新排一遍。
|
||||
|
||||
混合检索给的是"大致相关"——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
|
||||
Reference in New Issue
Block a user