intent.py 10.8 KB
"""查询理解:单次 LLM 调用完成意图识别 + 历史指代消解。

设计原则:检索前只发一次调用,尽量快。解析失败时降级到会走完整检索的意图,
绝不能变成 chitchat——那会把用户的真实问题静默吞成罐头问候语。
"""
from __future__ import annotations

import json
import logging
from dataclasses import dataclass, field
from typing import Any

from src.rag.core.config import (
    RAG_HISTORY_CONTENT_CHARS,
    RAG_INTENT_FALLBACK_INTENT,
    RAG_INTENT_MODEL,
    RAG_MAX_SUB_QUERIES,
)
from src.rag.ingestion.taxonomy import load_taxonomy
from src.rag.core.utils import safe_json_loads
from src.rag.infra.llm import chat_once

logger = logging.getLogger(__name__)

# 查询理解提示词模板。用 str.format 注入 {query}/{history}/{label_spec};
# 字面大括号写成 {{ }}(如输出格式示例)。改提示词直接改这段。
_INTENT_PROMPT_TEMPLATE = """你是汽车后市场知识库的查询理解器。只输出 JSON,不要解释,禁止 Markdown 代码块和 <think>。

## 意图判定

可选 intent(用复数形式):products、scripts、policies、procedures、troubleshooting、comparisons、concepts、entities、sources、synthesis、unsupported、chitchat。

**重要偏好**:进入这里的问题大多数是在查「话术/说法/客户沟通口径」,因此要显著优先判为 scripts。
只要问题可以合理理解为想知道「怎么跟客户说、怎么回复、怎么解释、怎么引导、怎么成交、怎么处理异议、怎么邀约/回访、客户问某事该怎么答、销售/客服可直接照着说的话」,即使没有出现"话术"二字,也优先输出 scripts。

当问题同时涉及产品、价格、免责、政策、流程、概念,但用户更像是在要对外表达口径时,主意图必须是 scripts,其余放进 intents 后续项。例如:
- "客户问价格为什么这么贵怎么说" -> intent="scripts", intents=["scripts","products"]
- "免责怎么跟客户解释" -> intent="scripts", intents=["scripts","policies"]
- "客户不信任/嫌贵/担心理赔怎么办" -> intent="scripts", intents=["scripts"]

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

多意图并存时按此优先级排 intents:troubleshooting > policies > scripts > products > procedures > comparisons > concepts。

## standalone_query

结合历史把指代("它/这个/上述/刚才"等)补全成不依赖上下文、可直接检索的完整问题。
问题本身已完整则原样返回。不要新增事实,不要追问。

## sub_queries

**仅当问题包含多个可独立检索的子问题时才拆分**,否则必须返回 []。
- "价格和免责怎么跟客户说" -> ["太阳膜价格政策", "太阳膜免责条款"]
- "A 和 B 的区别" -> ["A 的保障范围", "B 的保障范围"]

每条必须自包含、可单独检索、不含指代。最多 3 条。
**不要为了凑数而拆分,也不要把同一个问题改写成同义句** —— 单一问题返回 [] 是正确答案。

## labels

从问题中抽取业务维度,用于检索结果的软性加权(不做硬过滤,抽错不会漏召回):

{label_spec}

## 输出格式

{{"intent": "...", "intents": [...], "confidence": 0.9, "standalone_query": "...", "sub_queries": [...], "labels": {{...}}, "unsupported_reason": ""}}

问题: {query}
历史: {history}"""

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",
}


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

@dataclass
class IntentResult:
    """一次查询理解的结果:意图 + 指代消解 + 子问题拆分 + 业务维度信号。"""

    intent: str
    confidence: float = 0.8
    intents: list[str] = field(default_factory=list)
    standalone_query: str = ""                  # 指代消解后的独立问题
    sub_queries: list[str] = field(default_factory=list)   # 复杂问题的子问题;简单问题为 []
    # 业务维度信号,键集合由 taxonomy.boostable() 决定——加一个 boost 维度,
    # prompt 自动多问一个字段、这里自动多一个键、融合自动多一项加权,代码零改动。
    query_labels: dict[str, str] = field(default_factory=dict)
    unsupported_reason: str = ""
    degraded: bool = False  # True = 查询理解失败已降级,本次意图不可信(用于统计降级率)


def _label_spec() -> str:
    """按 taxonomy 生成 prompt 里的业务维度约束段。手写这段就等于把维度写死两遍。"""
    lines = []
    for dim in load_taxonomy().boostable():
        values = "、".join(list(dim.values)[:40])
        label = dim.display or dim.name
        lines.append(f'- {dim.name}({label}):只能填 {values} 之一,判断不了就留空字符串')
    return "\n".join(lines) if lines else "(本知识库未启用业务维度,相关字段一律留空)"


def _label_keys() -> tuple[str, ...]:
    return tuple(d.name for d in load_taxonomy().boostable())


async def classify_intent(query: str, history: list[dict[str, Any]] | None = None) -> IntentResult:
    """一次 LLM 调用完成全部查询理解:意图 + 指代消解 + 子问题拆分 + 业务维度抽取。

    刻意合并成一次调用:检索必须等它返回才能开始,多一次往返就是纯延迟。
    子问题拆分因此是"白送"的——不增加任何 LLM 往返。
    """
    history_text = json.dumps(history or [], ensure_ascii=False)[:RAG_HISTORY_CONTENT_CHARS]
    prompt = _INTENT_PROMPT_TEMPLATE.format(
        query=query, history=history_text, label_spec=_label_spec()
    )
    try:
        content = await chat_once(RAG_INTENT_MODEL, prompt, purpose="RAG_INTENT")
    except Exception as exc:  # 网络抖动 / 限流 / 模型不可用
        return _fallback_intent(query, "", f"chat_once 异常: {exc}")

    # 兼容 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:
        return _fallback_intent(query, content, "模型返回格式错误或缺少 intent")

    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),
        intents=intents,
        standalone_query=standalone,
        sub_queries=_clean_sub_queries(data.get("sub_queries"), query, standalone),
        query_labels=_clean_labels(data.get("labels")),
        unsupported_reason=data.get("unsupported_reason") or "",
    )


def _clean_sub_queries(raw: Any, query: str, standalone: str) -> list[str]:
    """子问题必须自包含、去重、且不能是原问题的复述。最多 3 条。"""
    if not isinstance(raw, (list, tuple)):
        return []
    seen = {query.strip(), standalone.strip()}
    cleaned: list[str] = []
    for item in raw:
        text = str(item or "").strip()
        if not text or text in seen:
            continue
        seen.add(text)
        cleaned.append(text)
        if len(cleaned) >= RAG_MAX_SUB_QUERIES:
            break
    return cleaned


def _clean_labels(raw: Any) -> dict[str, str]:
    """只收 taxonomy 声明为可加权的维度,且取值必须在受控词表内。"""
    if not isinstance(raw, dict):
        return {}
    labels: dict[str, str] = {}
    for dim in load_taxonomy().boostable():
        value = str(raw.get(dim.name) or "").strip()
        if value and value in dim.values:
            labels[dim.name] = value
    return labels


def _fallback_intent(query: str, raw: str, reason: str) -> IntentResult:
    """
    查询理解失败时的降级结果。

    关键:绝不能降级成 chitchat——那会让 stream_query 短路返回罐头问候语且零检索,
    把用户的真实问题静默吞掉。这里回落到一个会走完整检索的意图,
    检索照常进行,只是回答格式的先验退化。degraded=True 供上游统计降级率。
    """
    logger.error(
        "[RAG] 查询理解降级: reason=%s query=%r raw=%r",
        reason,
        query,
        raw[:300],
    )
    return IntentResult(
        intent=RAG_INTENT_FALLBACK_INTENT,
        confidence=0.0,
        intents=[RAG_INTENT_FALLBACK_INTENT],
        standalone_query=query,
        degraded=True,
    )


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