reranker.py
3.66 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
"""
重排(Rerank)模块。
在初筛出的若干粗排 Chunk 后,通过调用阿里 DashScope 的 Reranker API,
对(Query + Chunk 文本)进行深层次的语义匹配与再打分,以提升靠前结果的精度。
"""
from __future__ import annotations
import logging
import os
from dotenv import load_dotenv
from src.database.models import RagChunk
from src.rag.config import RAG_RERANKER_MODEL, RAG_RERANKER_TOP_K
logger = logging.getLogger(__name__)
def rerank_chunks(query: str, chunks: list[RagChunk]) -> list[RagChunk]:
"""
利用重排大模型重新评估给定片段与查询的相关性。
1. 只对传入候选序列中的前 RAG_RERANKER_TOP_K 个(默认如 20 个)进行重新打分;
2. 后续未送入 Reranker 的分片保持原有的排名相对位置,或直接得分置底。
:param query: 用户的查询问题
:param chunks: 粗排挑选出的备选 RagChunk 对象列表
:return: 按 Reranker 重打分结果降序排列的新 Chunk 列表
"""
# 如果候选结果少于等于 1 个,无需耗费资源重排,直接返回
if len(chunks) <= 1:
return chunks
try:
load_dotenv()
import dashscope
# 初始化阿里云 API Key
dashscope.api_key = os.getenv("DASHSCOPE_API_KEY")
# 截取头部列表以减小 Reranker API 消耗,其它排在后面的直接视为低相关度
head = chunks[:RAG_RERANKER_TOP_K]
# 拼接片段的层级标题和文本内容,供模型评估
documents = [f"{chunk.title_path or ''}\n{chunk.content}" for chunk in head]
# 同步调用 DashScope 的 Reranker 模型
resp = dashscope.TextReRank.call(
model=RAG_RERANKER_MODEL,
query=query,
documents=documents,
return_documents=False,
)
# 校验请求结果
if getattr(resp, "status_code", None) != 200:
logger.warning(
"[RAG] reranker returned error: model=%s status=%s message=%s",
RAG_RERANKER_MODEL,
getattr(resp, "status_code", None),
getattr(resp, "message", ""),
)
return chunks
# 解析模型返回的结果列表
results = getattr(getattr(resp, "output", None), "results", []) or []
scored: list[tuple[RagChunk, float]] = []
scored_indices: set[int] = set()
for res in results:
if res.index < 0 or res.index >= len(head):
continue
chunk = head[res.index]
# 从模型返回中取出相关度分数,通常介于 0 到 1 或更大的连续空间
chunk.rerank_score = float(res.relevance_score)
scored.append((chunk, chunk.rerank_score))
scored_indices.add(res.index)
# 补充模型由于某些原因没有返回打分的那些 head 内 Chunk(给最低分 -1.0)
for idx, chunk in enumerate(head):
if idx not in scored_indices:
chunk.rerank_score = -1.0
scored.append((chunk, -1.0))
# 补充没有被送入 Reranker 的后续 Chunk(给最低分 -1.0)
for chunk in chunks[RAG_RERANKER_TOP_K:]:
chunk.rerank_score = -1.0
scored.append((chunk, -1.0))
# 按 Rerank 后的得分重新降序排列并返回
return [chunk for chunk, _ in sorted(scored, key=lambda item: item[1], reverse=True)]
except Exception as exc:
logger.warning(
"[RAG] reranker unavailable, keeping original retrieval order: model=%s error=%s",
RAG_RERANKER_MODEL,
exc,
exc_info=True,
)
return chunks