logs.py 5.54 KB
"""检索链路的日志项构造:把候选/片段压成一行摘要,避免输出完整 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 {}