retriever.py
9.05 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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
"""召回与排序:多变体并发混合检索 -> 按父块聚合 -> 精排 -> 上下文预算裁剪。"""
from __future__ import annotations
import asyncio
import logging
import time
from dataclasses import dataclass, field
from typing import Any
from sqlalchemy import select
from src.database.models import RagChunk
from src.database.session import AsyncSessionLocal
from src.rag.core.config import (
RAG_LOG_RETRIEVAL_DETAIL,
RAG_MAX_CONTEXT_CHARS,
RAG_MIN_RERANK_SCORE,
RAG_PARENT_FINAL_TOP_K,
RAG_RERANKER_TOP_K,
RAG_VECTOR_TOP_K,
)
from src.rag.core.utils import safe_json_dumps
from src.rag.infra.reranker import rerank_chunks_async
from src.rag.infra.vector_store import vector_store
from src.rag.retrieval.fusion import fuse_candidates
from src.rag.retrieval.intent import IntentResult
from src.rag.retrieval.logs import (
RETRIEVAL_LOG_TOP_N,
_candidate_log_items,
_chunk_log_items,
)
logger = logging.getLogger(__name__)
# ---------------------------------------------------------------------------
# 召回(Qdrant 混合检索)
# ---------------------------------------------------------------------------
@dataclass
class Candidate:
"""从向量库召回、按父块聚合后的候选片段。"""
child_chunk_id: str
parent_chunk_id: str | None
file_id: str
retrieval_type: str # 命中它的变体;多路命中时形如 "direct,sub_1"
payload: dict[str, Any] = field(default_factory=dict)
hybrid_score: float = 0.0 # 各路原始分的最大值(前端展示用)
fusion_score: float = 0.0 # 跨变体 RRF 融合分 + 软提升 —— 真正的排序依据
def _variants(query: str, intent: IntentResult) -> list[tuple[str, str]]:
"""构造检索变体:原问题 + 指代消解后的问题 + 子问题,去重后最多 5 路并发。
子问题来自意图那一次调用,不额外发 LLM 请求——拆分是白送的。
"""
items = [("direct", query), ("standalone", intent.standalone_query or "")]
items += [(f"sub_{i}", q) for i, q in enumerate(intent.sub_queries, start=1)]
seen: set[str] = set()
dedup: list[tuple[str, str]] = []
for retrieval_type, text in items:
text = (text or "").strip()
if text and text not in seen:
seen.add(text)
dedup.append((retrieval_type, text))
return dedup
def _candidates_from_hits(hits: list[dict[str, Any]], retrieval_type: str) -> list[Candidate]:
candidates: list[Candidate] = []
for hit in hits:
payload = hit.get("payload", {})
candidates.append(
Candidate(
child_chunk_id=hit["chunk_id"],
parent_chunk_id=payload.get("parent_chunk_id"),
file_id=payload.get("document_id") or payload.get("file_id", ""),
retrieval_type=retrieval_type,
payload=payload,
hybrid_score=hit.get("hybrid_score", hit.get("vector_score", 0.0)),
)
)
return candidates
async def retrieve(
query: str,
intent: IntentResult,
history: list[dict[str, Any]] | None = None,
user_context: dict[str, Any] | None = None,
) -> dict[str, Any]:
"""检索管道:多变体并发召回 -> RRF 融合 + 软提升 -> 精排 -> 上下文预算裁剪。
业务维度不进 Qdrant filter(只过滤 status),只在融合后做分数加权——
LLM 抽错品牌时正确文档仍在召回集里,不会被静默排除。
"""
started = time.time()
filters = {"status": "active"}
variants = _variants(query, intent)
# 精排与生成都用补全指代后的问题:像"它多少钱"这种跟进问题,用原文精排会因为
# 没有信息量被打到阈值以下,表现成"检索到了但答不出来"。
effective_query = (intent.standalone_query or "").strip() or query
async def fetch_hits(retrieval_type: str, variant_query: str) -> list[Candidate]:
hits = await asyncio.to_thread(vector_store.search, variant_query, filters, RAG_VECTOR_TOP_K)
return _candidates_from_hits(hits, retrieval_type)
per_variant = await asyncio.gather(*(fetch_hits(t, q) for t, q in variants))
t_recall = time.time()
# 各变体召回数,形如 {"direct": 50, "standalone": 50, "sub_1": 50}
recall_by_variant = {t: len(v) for (t, _), v in zip(variants, per_variant)}
fused, soft_boosts = fuse_candidates(list(per_variant), intent.query_labels)
ranked = fused[:RAG_RERANKER_TOP_K]
reranked = await _load_parent_chunks(ranked)
reranked = await rerank_chunks_async(effective_query, reranked)
t_rerank = time.time()
reranked_count = len(reranked)
# 阈值过滤前先按 rerank 分排好——日志要看到被丢弃的片段,才知道「为什么没进上下文」。
reranked_sorted = sorted(reranked, key=lambda c: -float(getattr(c, "rerank_score", 0.0) or 0.0))
chunks = [c for c in reranked if getattr(c, "rerank_score", 0.0) >= RAG_MIN_RERANK_SCORE][:RAG_PARENT_FINAL_TOP_K]
chunks = _apply_context_budget(chunks)
# 每查询一条汇总(detail != off 时打)。此前明细压在 DEBUG 级默认看不见。
if RAG_LOG_RETRIEVAL_DETAIL != "off":
logger.info(
"[RAG] 检索完成: variants=%s recall=%s fused=%s reranked=%s final=%s chars=%s "
"intent=%s degraded=%s boosts=%s t_recall=%dms t_rerank=%dms t_total=%dms",
len(variants),
recall_by_variant,
len(fused),
reranked_count,
len(chunks),
sum(len(c.content or "") for c in chunks),
intent.intent,
intent.degraded,
soft_boosts or "-",
int((t_recall - started) * 1000),
int((t_rerank - t_recall) * 1000),
int((time.time() - started) * 1000),
)
# detail=full 时把明细按 INFO 打出来(与全局 DEBUG 解耦):召回变体、融合候选 top-N、
# 重排明细(带过阈值标记)——排障时无需把整个 app 切 DEBUG。
if RAG_LOG_RETRIEVAL_DETAIL == "full":
logger.info("[RAG] 检索变体: %s", [{"type": t, "query": q} for t, q in variants])
logger.info("[RAG] 融合候选 top-%d: %s", RETRIEVAL_LOG_TOP_N,
safe_json_dumps(_candidate_log_items(ranked, RETRIEVAL_LOG_TOP_N)))
logger.info(
"[RAG] 重排明细 top-%d(阈值%.2f): %s",
RETRIEVAL_LOG_TOP_N, RAG_MIN_RERANK_SCORE,
safe_json_dumps(_chunk_log_items(reranked_sorted, RETRIEVAL_LOG_TOP_N,
include_preview=True, rerank_threshold=RAG_MIN_RERANK_SCORE)),
)
logger.info("[RAG] 最终上下文: %s",
safe_json_dumps(_chunk_log_items(chunks, RETRIEVAL_LOG_TOP_N, include_preview=True)))
return {
"filters": filters,
"soft_boosts": soft_boosts,
"query_plan": {
"standalone_query": intent.standalone_query,
"sub_queries": intent.sub_queries,
"queries": [q for _, q in variants],
},
"queries": [{"type": t, "query": q} for t, q in variants],
"recall": recall_by_variant,
"ranked": ranked,
"chunks": chunks,
}
async def _load_parent_chunks(ranked: list[Candidate]) -> list[RagChunk]:
"""按候选的父块 id 加载完整父级片段,并把召回信息回填到 ORM 对象上。"""
parent_ids = [candidate.parent_chunk_id or candidate.child_chunk_id for candidate in ranked]
if not parent_ids:
return []
candidate_by_id = {pid: cand for pid, cand in zip(parent_ids, ranked)}
async with AsyncSessionLocal() as session:
result = await session.execute(
select(RagChunk).where(RagChunk.chunk_id.in_(parent_ids), RagChunk.status == "active")
)
chunks = list(result.scalars().all())
for chunk in chunks:
candidate = candidate_by_id.get(chunk.chunk_id)
if candidate:
chunk.child_chunk_id = candidate.child_chunk_id
chunk.retrieval_type = candidate.retrieval_type
chunk.vector_score = candidate.hybrid_score
chunk.final_score = candidate.hybrid_score
rank_order = {cid: idx for idx, cid in enumerate(parent_ids)}
return sorted(chunks, key=lambda c: (rank_order.get(c.chunk_id, 999), c.file_id, c.chunk_index))
def _apply_context_budget(chunks: list[RagChunk]) -> list[RagChunk]:
"""按 rerank_score 排序,在字符预算内选片段,最后按阅读顺序排版。"""
ranked_for_budget = sorted(
chunks,
key=lambda chunk: (
-float(getattr(chunk, "rerank_score", 0.0) or 0.0),
-float(getattr(chunk, "final_score", 0.0) or 0.0),
chunk.file_id,
chunk.chunk_index,
),
)
selected: list[RagChunk] = []
total = 0
for chunk in ranked_for_budget:
chunk_len = len(chunk.content)
if total + chunk_len > RAG_MAX_CONTEXT_CHARS:
continue
selected.append(chunk)
total += chunk_len
return sorted(selected, key=lambda chunk: (chunk.file_id, chunk.chunk_index))