logs.py
5.54 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
"""检索链路的日志项构造:把候选/片段压成一行摘要,避免输出完整 payload。"""
from __future__ import annotations
from typing import TYPE_CHECKING, Any
from src.rag.core.config import RAG_LOG_PREVIEW_CHARS, RAG_LOG_TOP_N
from src.rag.core.utils import safe_json_loads
from src.rag.ingestion.taxonomy import load_taxonomy
if TYPE_CHECKING: # 仅类型标注需要;运行时 import 会与 retriever 成环
from src.rag.retrieval.retriever import Candidate
RETRIEVAL_LOG_TOP_N = RAG_LOG_TOP_N
RETRIEVAL_LOG_PREVIEW_CHARS = RAG_LOG_PREVIEW_CHARS
def _taxonomy_labels(source: dict[str, Any]) -> dict[str, Any]:
"""按 taxonomy 声明动态取业务标签,不写死 brand/business_category——加维度零改动。"""
return {name: source.get(name) for name in load_taxonomy().filterable_names() if source.get(name)}
def _candidate_log_items(candidates: list['Candidate'], limit: int = RETRIEVAL_LOG_TOP_N) -> list[dict[str, Any]]:
"""把向量召回候选压成适合日志的一行摘要,避免输出完整 payload。"""
items: list[dict[str, Any]] = []
for rank, candidate in enumerate(candidates[:limit], start=1):
payload = candidate.payload or {}
items.append(
_compact_log_dict(
{
"rank": rank,
"type": candidate.retrieval_type,
"hybrid": _round_score(candidate.hybrid_score),
"fusion": _round_score(getattr(candidate, "fusion_score", None)),
"child": candidate.child_chunk_id,
"parent": candidate.parent_chunk_id,
"file_id": candidate.file_id,
"source": payload.get("source_name"),
"chunk_index": payload.get("chunk_index"),
"page": _format_page_range(payload.get("page_start"), payload.get("page_end")),
"section": payload.get("section_title"),
"kind": payload.get("content_kind"),
**_taxonomy_labels(payload),
}
)
)
return items
def _chunk_log_items(
chunks: list[Any],
limit: int = RETRIEVAL_LOG_TOP_N,
include_preview: bool = False,
rerank_threshold: float | None = None,
) -> list[dict[str, Any]]:
"""把数据库片段压成适合日志的摘要,方便排查最终上下文来源。
传入 rerank_threshold 时额外标注每条 rerank 分是否过阈值(passed),
用于在阈值过滤前记录——一眼看出「这片段为什么没进最终上下文」。
"""
items: list[dict[str, Any]] = []
for rank, chunk in enumerate(chunks[:limit], start=1):
metadata = _metadata_dict(chunk)
content = getattr(chunk, "content", "") or ""
rerank_score = getattr(chunk, "rerank_score", None)
item = {
"rank": rank,
"chunk_id": getattr(chunk, "chunk_id", None),
"child": getattr(chunk, "child_chunk_id", None),
"file_id": getattr(chunk, "file_id", None),
"source": getattr(chunk, "source_name", None),
"chunk_index": getattr(chunk, "chunk_index", None),
"page": _format_page_range(getattr(chunk, "page_start", None), getattr(chunk, "page_end", None)),
"row": _format_page_range(getattr(chunk, "row_start", None), getattr(chunk, "row_end", None)),
"title": _truncate_log_text(getattr(chunk, "title_path", None), 80),
"section": getattr(chunk, "section_title", None) or metadata.get("section_title"),
"kind": getattr(chunk, "content_kind", None) or metadata.get("content_kind"),
**_taxonomy_labels(metadata),
"type": getattr(chunk, "retrieval_type", None),
"vector_score": _round_score(getattr(chunk, "vector_score", None)),
"final_score": _round_score(getattr(chunk, "final_score", None)),
"rerank_score": _round_score(rerank_score),
"chars": len(content),
}
if rerank_threshold is not None:
item["passed"] = bool((rerank_score or 0.0) >= rerank_threshold)
if include_preview:
item["preview"] = _truncate_log_text(content, RETRIEVAL_LOG_PREVIEW_CHARS)
items.append(_compact_log_dict(item))
return items
def _compact_log_dict(item: dict[str, Any]) -> dict[str, Any]:
return {key: value for key, value in item.items() if value is not None and value != ""}
def _round_score(value: Any) -> float | None:
if value is None:
return None
try:
return round(float(value), 4)
except (TypeError, ValueError):
return None
def _format_page_range(start: Any, end: Any) -> str | None:
if start is None or start == "":
return None
if end is None or end == "" or str(end) == str(start):
return str(start)
return f"{start}-{end}"
def _truncate_log_text(value: Any, limit: int) -> str | None:
if value is None:
return None
text = " ".join(str(value).split())
if not text:
return None
return text if len(text) <= limit else f"{text[:limit]}..."
# ---------------------------------------------------------------------------
# 小工具
# ---------------------------------------------------------------------------
def _metadata_dict(chunk: Any) -> dict[str, Any]:
metadata = getattr(chunk, "metadata_json", None)
if isinstance(metadata, dict):
return metadata
if isinstance(metadata, str):
parsed = safe_json_loads(metadata, {})
return parsed if isinstance(parsed, dict) else {}
return {}