retrieval.py 30.7 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 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738
"""
RAG 检索与回答生成核心逻辑模块(两段式:Qdrant 混合召回 → DashScope 精排)。

设计原则:召回与排序交给真正擅长的组件——Qdrant 的 dense+sparse RRF 负责召回,
DashScope reranker 负责精排——不再用硬编码关键词表 / 元数据启发式去干预排序。
检索前只做一次「查询理解」调用(意图识别 + 历史指代消解),尽量快。
"""
from __future__ import annotations

import asyncio
import json
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.config import (
    RAG_ANSWER_MODEL,
    RAG_INTENT_MODEL,
    RAG_MAX_CONTEXT_CHARS,
    RAG_MIN_RERANK_SCORE,
    RAG_NEIGHBOR_WINDOW,
    RAG_PARENT_FINAL_TOP_K,
    RAG_RERANKER_TOP_K,
    RAG_VECTOR_TOP_K,
)
from src.rag.llm import chat_once, chat_stream
from src.rag.reranker import rerank_chunks
from src.rag.stores import vector_store
from src.rag.utils import safe_json_dumps, safe_json_loads

logger = logging.getLogger(__name__)
RETRIEVAL_LOG_TOP_N = 8
RETRIEVAL_LOG_PREVIEW_CHARS = 140
CANONICAL_INTENT_ALIASES = {
    "entity": "entities",
    "entities": "entities",
    "product": "products",
    "products": "products",
    "script": "scripts",
    "scripts": "scripts",
    "policy": "policies",
    "policies": "policies",
    "compliance": "policies",
    "procedure": "procedures",
    "procedures": "procedures",
    "comparison": "comparisons",
    "comparisons": "comparisons",
    "concept": "concepts",
    "concepts": "concepts",
    "general_knowledge": "concepts",
    "source": "sources",
    "sources": "sources",
    "synthesis": "synthesis",
    "troubleshooting": "troubleshooting",
    "unsupported": "unsupported",
    "chitchat": "chitchat",
}

# 召回为空或精排后无可用片段时的温和兜底回复
FALLBACK_ANSWER = (
    "抱歉,现有知识库里我暂时没找到能准确回答这个问题的资料~"
    "您可以补充一下品牌或更具体的问题,或者请管理员补充相关文档,我再帮您查。"
)


# ---------------------------------------------------------------------------
# 查询理解(单次 LLM 调用:意图识别 + 历史指代消解)
# ---------------------------------------------------------------------------

@dataclass
class IntentResult:
    """一次查询理解的结果:意图标签 + 业务上下文 + 指代消解后的独立问题。"""
    intent: str
    confidence: float = 0.8
    brand: str | None = None
    business_category: str | None = None
    sub_business: str | None = None
    intents: list[str] = field(default_factory=list)
    standalone_query: str = ""
    need_clarification: bool = False
    clarification_question: str = ""
    unsupported_reason: str = ""


async def classify_intent(query: str, history: list[dict[str, Any]] | None = None) -> IntentResult:
    """
    单次调用大模型完成「查询理解」:判断意图,并把依赖上下文的问题改写成独立完整的问题
    (standalone_query),供后续检索使用。不再单独发起查询改写调用。
    """
    prompt = f"""你是汽车后市场知识库的查询理解器。只输出 JSON,不要解释。
可选 intent: product, script, policy, compliance, procedure, troubleshooting, comparison, unsupported, general_knowledge, chitchat。

重要偏好:进入这里的问题大多数是在查「话术/说法/客户沟通口径」,因此要显著优先判为 script。
只要问题可以合理理解为想知道「怎么跟客户说、怎么回复、怎么解释、怎么引导、怎么成交、怎么处理异议、怎么邀约/回访、客户问某事该怎么答、销售/客服可直接照着说的话」,即使没有出现“话术”二字,也优先输出 intent="script"。
当问题同时涉及产品、价格、免责、政策、流程、概念等内容,但用户更像是在要对外表达口径或可直接使用的回答时,主意图必须是 script,其他意图放入 intents 的后续项。例如:
- "客户问价格为什么这么贵怎么说" -> intent="script", intents=["script", "product"]
- "免责怎么跟客户解释" -> intent="script", intents=["script", "policy"]
- "这个服务怎么介绍给客户" -> intent="script", intents=["script", "product"]
- "客户不信任/嫌贵/担心理赔怎么办" -> intent="script", intents=["script"]

只有在问题明确不是要沟通口径时,才选择其他主意图:查具体参数/保障范围用 product;查硬性规则/合规红线用 policy 或 compliance;查内部操作步骤用 procedure;查系统报错/故障处理用 troubleshooting;纯闲聊用 chitchat;知识库不支持的问题用 unsupported。
如果在 script 与其他意图之间犹豫,默认选择 script,并把置信度保持在 0.75 以上。

允许复合意图,intents 是数组,主意图放第一位。例如"价格和免责"如果是在查资料应为 ["product", "policy"];如果是在问怎么对客户说明,应为 ["script", "product", "policy"]。
standalone_query: 结合历史把指代("它/这个/上述/刚才"等)补全为不依赖上下文、可直接检索的完整问题;
若问题本身已完整,则原样返回。不要新增事实,不要追问。
need_clarification 必须为 false(信息不足由后续问答链路处理)。

问题: {query}
历史: {json.dumps(history or [], ensure_ascii=False)[:1200]}
输出字段: intent, intents, confidence, brand, business_category, sub_business, standalone_query, unsupported_reason
"""
    content = await chat_once(RAG_INTENT_MODEL, prompt, purpose="RAG_INTENT")

    # 兼容 markdown 代码块包裹的 JSON
    if content.startswith("```json"):
        content = content[7:]
    if content.startswith("```"):
        content = content[3:]
    data = safe_json_loads(content.strip().strip("`"), {})

    if not data or "intent" not in data:
        logger.warning("[RAG] 查询理解失败,模型返回格式错误或缺少 intent: %s。默认 chitchat。", content)
        data = {"intent": "chitchat", "confidence": 0.5, "intents": ["chitchat"]}

    primary_intent, intents = _normalize_intent_fields(data.get("intent"), data.get("intents"))
    standalone = str(data.get("standalone_query") or "").strip() or query
    return IntentResult(
        intent=primary_intent,
        confidence=float(data.get("confidence") or 0.8),
        brand=data.get("brand"),
        business_category=data.get("business_category"),
        sub_business=data.get("sub_business"),
        intents=intents,
        standalone_query=standalone,
        need_clarification=False,
        clarification_question="",
        unsupported_reason=data.get("unsupported_reason") or "",
    )


def _normalize_intent_fields(intent: Any, intents: Any) -> tuple[str, list[str]]:
    """Normalize model intent output so the primary intent is always a string."""
    primary_candidates = _intent_list(intent)
    intent_list = _intent_list(intents) or primary_candidates
    primary = primary_candidates[0] if primary_candidates else (intent_list[0] if intent_list else "chitchat")
    if not intent_list:
        intent_list = [primary]
    return primary, _dedupe_strings(intent_list)


def _intent_list(value: Any) -> list[str]:
    if value is None:
        return []
    if isinstance(value, str):
        stripped = _canonical_intent(value)
        return [stripped] if stripped else []
    if isinstance(value, (list, tuple, set)):
        return [_canonical_intent(item) for item in value if _canonical_intent(item)]
    stripped = _canonical_intent(value)
    return [stripped] if stripped else []


def _canonical_intent(value: Any) -> str:
    normalized = str(value or "").strip()
    if not normalized:
        return ""
    return CANONICAL_INTENT_ALIASES.get(normalized.lower(), normalized)


def _dedupe_strings(values: list[str]) -> list[str]:
    seen: set[str] = set()
    deduped: list[str] = []
    for value in values:
        if value in seen:
            continue
        seen.add(value)
        deduped.append(value)
    return deduped


# ---------------------------------------------------------------------------
# 召回(Qdrant 混合检索)
# ---------------------------------------------------------------------------

@dataclass
class Candidate:
    """从向量库召回并按父块聚合后的候选片段。排序只看 hybrid_score(RRF 融合分)。"""
    child_chunk_id: str
    parent_chunk_id: str | None
    file_id: str
    retrieval_type: str
    payload: dict[str, Any] = field(default_factory=dict)
    hybrid_score: float = 0.0


def _variants(query: str, intent: IntentResult) -> list[tuple[str, str]]:
    """构造检索查询变体:原始问题 +(不同的话)指代消解后的独立问题。"""
    items = [("direct", query)]
    standalone = (intent.standalone_query or "").strip()
    if standalone and standalone != query.strip():
        items.append(("standalone", standalone))
    seen: set[str] = set()
    dedup: list[tuple[str, str]] = []
    for retrieval_type, text in items:
        text = text.strip()
        if text and text not in seen:
            seen.add(text)
            dedup.append((retrieval_type, text))
    return dedup


def _merge_candidates(candidates: list[Candidate]) -> list[Candidate]:
    """按父块(无父块则按自身)聚合去重,保留各路召回中最高的 hybrid_score。"""
    grouped: dict[str, Candidate] = {}
    for candidate in candidates:
        key = candidate.parent_chunk_id or candidate.child_chunk_id
        existing = grouped.get(key)
        if existing is None:
            grouped[key] = candidate
            continue
        existing.hybrid_score = max(existing.hybrid_score, candidate.hybrid_score)
        if len(candidate.payload) > len(existing.payload):
            existing.payload = candidate.payload
        if candidate.retrieval_type not in existing.retrieval_type:
            existing.retrieval_type = f"{existing.retrieval_type},{candidate.retrieval_type}"
    return sorted(grouped.values(), key=lambda c: c.hybrid_score, reverse=True)


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]:
    """
    两段式检索管道:
    1. 多变体并发混合召回(Qdrant dense+sparse RRF)
    2. 按父块聚合去重,按 hybrid_score 取前 RAG_RERANKER_TOP_K
    3. 加载父级片段(含简化邻居补全)
    4. DashScope reranker 精排,按 rerank_score 截断到 RAG_PARENT_FINAL_TOP_K
    5. 按字符预算裁剪送入 LLM 的上下文
    """
    filters = {"status": "active"}
    variants = _variants(query, intent)
    logger.info("[RAG] 检索变体: %s", [text for _, text in variants])
    logger.info(
        "[RAG] 检索参数: filters=%s vector_top_k=%s reranker_top_k=%s final_top_k=%s "
        "min_rerank_score=%s neighbor_window=%s max_context_chars=%s",
        filters,
        RAG_VECTOR_TOP_K,
        RAG_RERANKER_TOP_K,
        RAG_PARENT_FINAL_TOP_K,
        RAG_MIN_RERANK_SCORE,
        RAG_NEIGHBOR_WINDOW,
        RAG_MAX_CONTEXT_CHARS,
    )

    async def fetch_hits(retrieval_type: str, variant_query: str) -> list[Candidate]:
        started = time.time()
        hits = await asyncio.to_thread(vector_store.search, variant_query, filters, RAG_VECTOR_TOP_K)
        variant_candidates = _candidates_from_hits(hits, retrieval_type)
        logger.info(
            "[RAG] 变体召回完成: type=%s query=%r hits=%s duration_ms=%s top=%s",
            retrieval_type,
            variant_query,
            len(variant_candidates),
            int((time.time() - started) * 1000),
            safe_json_dumps(_candidate_log_items(variant_candidates, RETRIEVAL_LOG_TOP_N)),
        )
        return variant_candidates

    results = await asyncio.gather(*(fetch_hits(t, q) for t, q in variants))
    candidates: list[Candidate] = [c for res in results for c in res]
    logger.info("[RAG] 召回候选 %s 个(含重复),开始按父块聚合", len(candidates))
    logger.info(
        "[RAG] 召回候选明细(top %s): %s",
        RETRIEVAL_LOG_TOP_N,
        safe_json_dumps(_candidate_log_items(candidates, RETRIEVAL_LOG_TOP_N)),
    )

    ranked = _merge_candidates(candidates)[:RAG_RERANKER_TOP_K]
    logger.info("[RAG] 聚合去重后送精排 %s 个父块候选", len(ranked))
    logger.info(
        "[RAG] 父块候选明细(top %s): %s",
        RETRIEVAL_LOG_TOP_N,
        safe_json_dumps(_candidate_log_items(ranked, RETRIEVAL_LOG_TOP_N)),
    )

    chunks = await _load_parent_chunks(ranked)
    logger.info(
        "[RAG] 父块加载完成: requested=%s loaded_with_neighbors=%s top=%s",
        len(ranked),
        len(chunks),
        safe_json_dumps(_chunk_log_items(chunks, RETRIEVAL_LOG_TOP_N, include_preview=True)),
    )
    chunks = rerank_chunks(query, chunks)
    logger.info(
        "[RAG] 精排明细(top %s): %s",
        RETRIEVAL_LOG_TOP_N,
        safe_json_dumps(_chunk_log_items(chunks, RETRIEVAL_LOG_TOP_N, include_preview=True)),
    )
    chunks = [c for c in chunks if getattr(c, "rerank_score", 0.0) >= RAG_MIN_RERANK_SCORE][:RAG_PARENT_FINAL_TOP_K]
    logger.info(
        "[RAG] 精排后保留 %s 个片段, top_scores=%s",
        len(chunks),
        [round(getattr(c, "rerank_score", 0.0), 4) for c in chunks[:5]],
    )

    chunks = _apply_context_budget(chunks)
    logger.info(
        "[RAG] 上下文裁剪后最终 %s 个片段送入 LLM, total_chars=%s, chunks=%s",
        len(chunks),
        sum(len(c.content or "") for c in chunks),
        safe_json_dumps(_chunk_log_items(chunks, RETRIEVAL_LOG_TOP_N, include_preview=True)),
    )

    return {
        "filters": filters,
        "soft_boosts": {},
        "query_plan": {"standalone_query": intent.standalone_query, "queries": [q for _, q in variants]},
        "queries": [{"type": t, "query": q} for t, q in variants],
        "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.is_neighbor = False
                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
        chunks = await _expand_neighbors(session, chunks)
        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))


async def _expand_neighbors(session, chunks: list[RagChunk]) -> list[RagChunk]:
    """简化邻居补全:取命中父块的前/后兄弟父块(用已串好的 prev/next_chunk_id 列)补充上下文。"""
    if RAG_NEIGHBOR_WINDOW <= 0 or not chunks:
        return chunks
    collected = {chunk.chunk_id: chunk for chunk in chunks}
    neighbor_ids: set[str] = set()
    for chunk in chunks:
        for nid in (chunk.prev_chunk_id, chunk.next_chunk_id):
            if nid and nid not in collected:
                neighbor_ids.add(nid)
    if not neighbor_ids:
        return chunks
    result = await session.execute(
        select(RagChunk).where(RagChunk.chunk_id.in_(neighbor_ids), RagChunk.status == "active")
    )
    for chunk in result.scalars().all():
        if chunk.chunk_id not in collected:
            chunk.is_neighbor = True
            chunk.final_score = 0.0
            chunk.rerank_score = -1.0
            collected[chunk.chunk_id] = chunk
    return list(collected.values())


def _apply_context_budget(chunks: list[RagChunk]) -> list[RagChunk]:
    """按 rerank_score 优先、邻居块靠后的顺序,在字符预算内选片段,最后按阅读顺序排版。"""
    ranked_for_budget = sorted(
        chunks,
        key=lambda chunk: (
            bool(getattr(chunk, "is_neighbor", False)),
            -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))


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,
                    "score": _round_score(candidate.hybrid_score),
                    "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"),
                    "brand": payload.get("brand") or payload.get("brand_series"),
                    "category": payload.get("business_category"),
                }
            )
        )
    return items


def _chunk_log_items(
    chunks: list[Any],
    limit: int = RETRIEVAL_LOG_TOP_N,
    include_preview: bool = False,
) -> list[dict[str, Any]]:
    """把数据库片段压成适合日志的摘要,方便排查最终上下文来源。"""
    items: list[dict[str, Any]] = []
    for rank, chunk in enumerate(chunks[:limit], start=1):
        metadata = _metadata_dict(chunk)
        content = getattr(chunk, "content", "") or ""
        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"),
            "brand": getattr(chunk, "brand_series", None) or metadata.get("brand") or metadata.get("brand_series"),
            "category": getattr(chunk, "business_category", None) or metadata.get("business_category"),
            "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(getattr(chunk, "rerank_score", None)),
            "neighbor": bool(getattr(chunk, "is_neighbor", False)),
            "chars": len(content),
        }
        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 _answer_system_prompt() -> str:
    return """你是一名汽车后市场服务领域的知识顾问,专业、可靠,同时温和有温度——像一位耐心的资深同事在帮客户解决问题,而不是冷冰冰地复述资料。

【回答依据】
- 只能依据【召回资料】作答,不得编造或脑补资料里没有的内容。
- 价格、保额、折扣、年限、里程、免责条款等数字与表述必须与资料逐字一致,禁止四舍五入或改写。
- 每一处具体结论后用 [1][2] 标注来源序号;结尾用"📚 来源:"列出实际用到的序号与文件名。
- 根据【意图】和召回资料中的 content_kind、section_title、title_path 等信息判断最贴近的回答类型;如果同时命中多个类型,优先级为:troubleshooting > policies(合规红线)> scripts > products > policies(其他)> procedures > comparisons / synthesis > concepts。
- 不同品牌/车型的信息不要混淆;召回资料里出现多个品牌或口径冲突时,必须说明差异并标注各自来源。

【语气与共情】
- 先简短回应用户的处境或情绪(如"这个问题确实容易混淆""理解您想确认清楚再下单"),再给答案。
- 用自然口语,避免生硬的条款腔;可以用"我来帮您捋一下""简单说"等过渡。
- 答案末尾主动给一句贴心的下一步建议或邀请追问。

【差异化回答格式】
请根据命中的问题类型选择对应格式,禁止不分类型地平铺陈述。栏目可以在资料不足时省略,但不要改造成无来源的泛泛建议。

1. scripts(话术类)
**适用场景**:[异议场景或客户问题]
**话术示例**:
> "[直接呈现资料中的话术原文]"

**逻辑拆解**([资料中出现的方法或技巧标签,如算账法/锚点法]):
- 第一步:...
- 第二步:...

**注意事项**:
- [合规边界或不能说的话]

📚 来源:[1] 文件名 | 方法论参见:[2] 文件名

2. troubleshooting(系统排障类)
📋 **问题症状**:[用户描述的现象]

**可能原因**:
1. ...
2. ...

**操作步骤**:
1. [第一步,包含具体菜单、页面、按钮或路径]
2. [第二步]

**如仍未解决**:[资料中给出的上报路径 / 联系方式]

📚 来源:[1] 文件名

3. policies(政策/合规红线类)
⚠️ **合规红线(禁止行为)**:
- ❌ [禁止话术或禁止行为](如资料中有 violation_type,需一并写出)

✅ **合规表述方式**:
- "[正确话术或正确处理方式]"

**政策背景**:[条款说明或适用范围]

📚 来源:[1] 文件名

4. products(产品类)
## [产品名称]

**一句话定义**:[核心卖点或产品定位]

| 关键参数 | 说明 |
|---------|------|
| ... | ... |

**保障边界提示**:[免责、保障范围、适用条件或不适用场景]

📚 来源:[1] 文件名 | 相关条款:[2] 文件名

5. procedures(流程/SOP 类)
**触发条件**:[trigger 或适用场景]
**预期产出**:[output 或完成标准]

**操作步骤**:
1. [Step 1]
2. [Step 2]

**注意事项**:[合规、权限、材料或时效说明]

📚 来源:[1] 文件名

6. comparisons / synthesis(对比分析/综合类)
**对比维度**:[对比的核心问题]

| 维度 | [对象A] | [对象B] |
|------|---------|---------|
| ... | ... | ... |

**综合建议**:[基于资料的结论;如资料不足,说明只能比较已命中的维度]

📚 来源:[1] 文件名 | [2] 文件名

7. concepts(概念类)
**定义**:[一句话定义]

**适用场景**:[什么情况下用]

**典型示例**:
- [示例 1]

📚 来源:[1] 文件名

【信息不足或问题模糊时——一定要温和追问,不要生硬拒答】
- 资料不足以支撑准确回答时,使用以下兜底话术结构,并根据【意图】填入具体的 {意图类型} 与 {推荐的页面 type},不要使用通用措辞:
  🔍 当前知识库中暂无关于「{关键词}」的 {意图类型} 信息。

  建议您联系管理员补充以下文档:
  - 类型:{推荐的页面 type,如 scripts / products / policies}
  - 路径建议:raw/sources/{品牌}/{文档名}.md

  您也可以换个角度提问,我会尝试从现有知识中找到相关内容。
- 缺少关键上下文(尤其品牌不明确,不同品牌价格政策不同)时先礼貌追问再作答,例如:
  "为了给您准确的信息~请问您指的是哪个品牌呢?(如鸿蒙智行、岚图、零跑等)不同品牌的价格和政策会有差别。"

只输出最终回答,不要输出思考过程或工具细节。"""


def _build_answer_prompt(query: str, intent: IntentResult, chunks: list[RagChunk], history: list[dict[str, Any]] | None) -> str:
    context = "\n\n".join(_format_chunk(i + 1, chunk) for i, chunk in enumerate(chunks))
    return f"""{_answer_system_prompt()}

【用户问题】{query}

【意图】{intent.intent} / {intent.intents}

【历史对话】{history or []}

【召回资料】
{context}

请用中文回答。"""


async def generate_answer(query: str, intent: IntentResult, chunks: list[RagChunk], history: list[dict[str, Any]] | None = None) -> str:
    """结合召回资料,一次性(非流式)生成完整回答。"""
    if not chunks:
        return FALLBACK_ANSWER
    answer = (await chat_once(
        RAG_ANSWER_MODEL,
        _build_answer_prompt(query, intent, chunks, history),
        purpose="RAG_ANSWER",
    )).strip()
    return answer or FALLBACK_ANSWER


async def generate_answer_stream(query: str, intent: IntentResult, chunks: list[RagChunk], history: list[dict[str, Any]] | None = None):
    """同 generate_answer,但流式逐步 yield(供 SSE 推送前端)。"""
    if not chunks:
        yield {"type": "answer_delta", "content": FALLBACK_ANSWER}
        return
    async for item in chat_stream(
        RAG_ANSWER_MODEL,
        _build_answer_prompt(query, intent, chunks, history),
        purpose="RAG_ANSWER",
    ):
        yield item


def _format_chunk(idx: int, chunk: RagChunk) -> str:
    """把片段渲染成带来源定位(页码/章节/表头)的上下文条目,供回答标注来源。"""
    loc: list[str] = []
    page_start = getattr(chunk, "page_start", None)
    page_end = getattr(chunk, "page_end", None) or page_start
    if page_start:
        loc.append(f"第{page_start}-{page_end}页" if page_end and page_end != page_start else f"第{page_start}页")
    metadata = _metadata_dict(chunk)
    if metadata.get("slide_number"):
        loc.append(f"第{metadata.get('slide_number')}页幻灯片")
    if metadata.get("sheet_name"):
        loc.append(f"Sheet:{metadata.get('sheet_name')}")
    if chunk.row_start:
        loc.append(f"行{chunk.row_start}-{chunk.row_end or chunk.row_start}")
    location = ",".join(loc) if loc else "无位置"

    section_title = getattr(chunk, "section_title", None) or metadata.get("section_title")
    content_kind = getattr(chunk, "content_kind", None) or metadata.get("content_kind")
    table_header = _as_list(getattr(chunk, "table_header_json", None) or metadata.get("table_header"))

    meta_parts = [f"文件: {chunk.source_name}", location, f"标题: {chunk.title_path or ''}"]
    if section_title:
        meta_parts.append(f"章节: {section_title}")
    if content_kind:
        meta_parts.append(f"内容类型: {content_kind}")
    if table_header:
        meta_parts.append(f"表头: {' | '.join(table_header[:8])}")
    return f"[{idx}] chunk_id={chunk.chunk_id} | {' | '.join(meta_parts)}\n{chunk.content}"


# ---------------------------------------------------------------------------
# 小工具
# ---------------------------------------------------------------------------

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 {}


def _as_list(value: Any) -> list[str]:
    if value is None or value == "":
        return []
    if isinstance(value, str):
        stripped = value.strip()
        parsed = safe_json_loads(stripped, None) if stripped.startswith(("[", "{")) else None
        if isinstance(parsed, list):
            return [str(item).strip() for item in parsed if str(item).strip()]
        if isinstance(parsed, dict):
            return [str(item).strip() for item in parsed.values() if str(item).strip()]
        return [stripped] if stripped else []
    if isinstance(value, dict):
        return [str(item).strip() for item in value.values() if str(item).strip()]
    if isinstance(value, (list, tuple, set)):
        return [str(item).strip() for item in value if str(item).strip()]
    return [str(value).strip()]