retrieval.py 18.5 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
"""
RAG 检索与回答生成核心逻辑模块(两段式:Qdrant 混合召回 → DashScope 精排)。

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

import asyncio
import json
import logging
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_loads

logger = logging.getLogger(__name__)

# 召回为空或精排后无可用片段时的温和兜底回复
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。
允许复合意图,intents 是数组。例如"价格和免责"应为 ["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)

    # 兼容 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"]}

    standalone = str(data.get("standalone_query") or "").strip() or query
    return IntentResult(
        intent=data.get("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=[str(item) for item in data.get("intents", [])] or [data.get("intent")],
        standalone_query=standalone,
        need_clarification=False,
        clarification_question="",
        unsupported_reason=data.get("unsupported_reason") or "",
    )


# ---------------------------------------------------------------------------
# 召回(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])

    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)

    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))

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

    chunks = await _load_parent_chunks(ranked)
    chunks = rerank_chunks(query, chunks)
    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", len(chunks))

    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 _answer_system_prompt() -> str:
    return """你是一名汽车后市场服务领域的知识顾问,专业、可靠,同时温和有温度——像一位耐心的资深同事在帮客户解决问题,而不是冷冰冰地复述资料。

【回答依据】
- 只能依据【召回资料】作答,不得编造或脑补资料里没有的内容。
- 价格、保额、折扣、年限、里程、免责条款等数字与表述必须与资料逐字一致,禁止四舍五入或改写。
- 每一处具体结论后用 [1][2] 标注来源序号;结尾用"📚 来源:"列出实际用到的序号与文件名。

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

【按问题类型灵活组织(不必死板套模板)】
- 产品/价格:一句话定位产品 → 关键参数(可用简表)→ 保障边界/免责提示。
- 话术:适用场景 → 话术原文(引号呈现)→ 简要逻辑拆解 → 合规注意。
- 政策/合规:先点明红线(禁止做什么)→ 合规的正确表述 → 简述条款背景。
- 流程/排障:触发条件 → 分步骤操作 → 仍未解决时的上报路径。
- 对比:列出对比维度(可用表)→ 给出综合建议。

【信息不足或问题模糊时——一定要温和追问,不要生硬拒答】
- 资料不足以支撑准确回答时:温和说明知识库暂无相关内容,并建议补充哪类文档,同时邀请用户换个角度提问。
- 缺少关键上下文(尤其品牌不明确,不同品牌价格政策不同)时先礼貌追问再作答,例如:
  "为了给您准确的信息~请问您指的是哪个品牌呢?(如鸿蒙智行、岚图、零跑等)不同品牌的价格和政策会有差别。"
- 不同品牌/车型的信息不要混淆。

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


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))).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)):
        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()]