pipeline.py 20.8 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
"""查询流程编排:历史 -> 意图 -> 检索 -> 生成 -> 落库,SSE 与 JSON 两种出口。"""
from __future__ import annotations

import asyncio
import json
import logging
import re
import time
from typing import Any

from fastapi import HTTPException
from sqlalchemy import delete, select

from src.database.models import RagChunk, RagQueryLog
from src.database.session import AsyncSessionLocal
from src.rag.core.config import (
    RAG_ANSWER_MODEL,
    RAG_FAKE_STREAM_CHUNK_CHARS,
    RAG_HISTORY_CONTENT_CHARS,
    RAG_HISTORY_MAX_MESSAGES,
    RAG_HISTORY_SESSION_LIMIT,
    RAG_HISTORY_SUMMARY_CHARS,
    RAG_LLM_CONCURRENCY,
    RAG_QUERY_CONCURRENCY,
    RAG_SAVE_QUERY_TIMEOUT_SECONDS,
)
from src.rag.core.utils import safe_json_dumps
from src.rag.infra.serializers import _chunk_to_dict, _json_or_empty
from src.rag.retrieval.answer import (
    FALLBACK_ANSWER,
    generate_answer,
    generate_answer_stream,
    generate_chitchat_stream,
)
from src.rag.retrieval.intent import classify_intent
from src.rag.retrieval.retriever import retrieve
from src.utils.llm_tracker import print_thinking, token_counter_context

logger = logging.getLogger(__name__)

_query_semaphore = asyncio.Semaphore(RAG_QUERY_CONCURRENCY)
_llm_semaphore = asyncio.Semaphore(RAG_LLM_CONCURRENCY)


async def query_json(payload) -> dict:
    """
    包装流式查询接口,一直等待直到获取最终的完整结果字典再返回。
    """
    final_data = None
    async for event in stream_query(payload):
        if event.get("type") == "done":
            final_data = event.get("data")
    
    if final_data:
        return {
            "answer": final_data.get("answer", ""),
            "tokens": final_data.get("tokens", 0),
            "duration_ms": final_data.get("duration_ms", 0),
            "status": "Success"
        }
    return {}


async def query_debug(payload) -> dict:
    """评测/排障专用:跑完整检索问答流程,把 done 事件的**全部数据**整体返回。

    含 intent 全字段、queries、sub_queries、filters、soft_boosts、ranked(融合候选带 payload 与
    各分数)、context_sources、citations、answer、tokens、duration_ms。非流式、一个 JSON,
    便于 curl/jq 逐条排查或批量跑测试集做整体效果评测。
    """
    final_data = None
    async for event in stream_query(payload):
        if event.get("type") == "done":
            final_data = event.get("data")
    return final_data or {}





def _build_query_result(
    payload,
    intent,
    retrieval: dict,
    answer: str,
    tokens: int,
    start: float,
    query_log_id: int | None = None,
) -> tuple[dict, list[dict], list[dict]]:
    duration = int((time.time() - start) * 1000)
    context_sources = [_chunk_to_dict(c, preview=True, source_index=i + 1) for i, c in enumerate(retrieval.get("chunks", []))]
    score_by_parent = {
        (getattr(c, "parent_chunk_id", None) or getattr(c, "child_chunk_id", None) or getattr(c, "chunk_id", None)): {
            "child_chunk_id": getattr(c, "child_chunk_id", None),
            "retrieval_type": getattr(c, "retrieval_type", None),
            "vector_score": round(float(getattr(c, "hybrid_score", 0.0) or 0.0), 4),
            "final_score": round(float(getattr(c, "hybrid_score", 0.0) or 0.0), 4),
            "rerank_score": round(float(getattr(c, "rerank_score", 0.0) or 0.0), 4),
        }
        for c in retrieval.get("ranked", [])
    }
    for item in context_sources:
        item_score = item.get("score") or {}
        ranked_score = score_by_parent.get(item.get("chunk_id"), {})
        item["score"] = {**ranked_score, **item_score}
    citations = _build_citations(answer, context_sources)
    sources = _sources_from_citations(citations, context_sources)
    source_summary = [
        {
            "chunk_id": item.get("chunk_id"),
            "file_id": item.get("file_id"),
            "document_id": item.get("document_id") or item.get("file_id"),
            "source_name": item.get("source_name"),
            "title_path": item.get("title_path"),
            "section_title": item.get("section_title"),
            "content_kind": item.get("content_kind"),
            "page_start": item.get("page_start"),
            "page_end": item.get("page_end"),
            "row_start": item.get("row_start"),
            "row_end": item.get("row_end"),
            "score": item.get("score"),
        }
        for item in context_sources
    ]
    result = {
        "answer": answer,
        "intent": intent.__dict__,
        "sources": sources,
        "citations": citations,
        "adoptedChunkIds": [item["chunk_id"] for item in citations if item.get("chunk_id")],
        "queryLogId": query_log_id,
        "duration_ms": duration,
        "tokens": tokens,
        "sessionId": payload.sessionId,
        "query_plan": retrieval.get("query_plan", {}),
        "retrieval": {
            "queries": retrieval.get("queries", []),
            "recall": retrieval.get("recall", {}),
            "filters": retrieval.get("filters", {}),
            "soft_boosts": retrieval.get("soft_boosts", {}),
            "ranked": [c.__dict__ for c in retrieval.get("ranked", [])],
            "context_sources": context_sources,
            "duration_ms": duration,
        },
    }
    return result, source_summary, citations


async def _save_query(payload, intent, retrieval: dict, answer: str, tokens: int, start: float, status: str) -> dict:
    result, source_summary, citations = _build_query_result(payload, intent, retrieval, answer, tokens, start)
    async with AsyncSessionLocal() as session:
        qlog = RagQueryLog(
            session_id=payload.sessionId,
            query_text=payload.query,
            intent_result_json=safe_json_dumps(intent.__dict__),
            retrieval_plan_json=safe_json_dumps(
                {
                    "query_plan": retrieval.get("query_plan", {}),
                    "queries": retrieval.get("queries", []),
                    "filters": retrieval.get("filters", {}),
                    "soft_boosts": retrieval.get("soft_boosts", {}),
                    "sources": source_summary,
                    "ranked": [c.__dict__ for c in retrieval.get("ranked", [])],
                }
            ),
            query_plan_json=safe_json_dumps(retrieval.get("query_plan", {})),
            filters_json=safe_json_dumps(retrieval.get("filters", {})),
            ranked_json=safe_json_dumps([c.__dict__ for c in retrieval.get("ranked", [])]),
            sources_json=safe_json_dumps(source_summary),
            adopted_chunk_ids_json=safe_json_dumps([item["chunk_id"] for item in citations if item.get("chunk_id")]),
            citation_map_json=safe_json_dumps(citations),
            answer_text=answer,
            model_name=RAG_ANSWER_MODEL,
            total_tokens=tokens,
            duration_ms=result["duration_ms"],
            status=status,
        )
        session.add(qlog)
        await session.flush()
        query_log_id = qlog.id
        await session.commit()
    result["queryLogId"] = query_log_id
    return result


async def _finish_query(payload, intent, retrieval: dict, answer: str, tokens: int, start: float, status: str = "Success") -> dict:
    try:
        return await asyncio.wait_for(
            _save_query(payload, intent, retrieval, answer, tokens, start, status),
            timeout=RAG_SAVE_QUERY_TIMEOUT_SECONDS,
        )
    except Exception:
        logger.exception("[RAG] failed to save query log, returning SSE result without queryLogId")
        result, _, _ = _build_query_result(payload, intent, retrieval, answer, tokens, start)
        result["queryLogId"] = None
        return result


def _log_answer_complete(answer: str, delta_count: int, start: float) -> None:
    logger.info(
        "[RAG] answer complete: chars=%s, deltas=%s, elapsed_ms=%s\n%s",
        len(answer),
        delta_count,
        int((time.time() - start) * 1000),
        answer,
    )


async def clear_history(session_id: str | None) -> dict:
    if not session_id:
        raise HTTPException(status_code=400, detail="sessionId is required")
    async with AsyncSessionLocal() as session:
        result = await session.execute(delete(RagQueryLog).where(RagQueryLog.session_id == session_id))
        await session.commit()
    return {"status": "success", "deleted": int(result.rowcount or 0), "sessionId": session_id}


async def _build_effective_history(payload) -> list[dict[str, str]]:
    frontend_history = _normalize_history(getattr(payload, "history", None))
    session_id = getattr(payload, "sessionId", None)
    stored_history: list[dict[str, str]] = []
    if session_id:
        logs = await _load_session_history(session_id)
        for item in logs:
            if item.query_text:
                stored_history.append({"role": "user", "content": str(item.query_text)})
            if item.answer_text:
                stored_history.append({"role": "assistant", "content": str(item.answer_text)})
    return _compact_history(_dedupe_history([*stored_history, *frontend_history]))


async def _load_session_history(session_id: str, limit: int = RAG_HISTORY_SESSION_LIMIT) -> list[RagQueryLog]:
    if AsyncSessionLocal is None:
        return []
    async with AsyncSessionLocal() as session:
        rows = (
            await session.execute(
                select(RagQueryLog)
                .where(RagQueryLog.session_id == session_id, RagQueryLog.status == "Success")
                .order_by(RagQueryLog.created_at.desc())
                .limit(limit)
            )
        ).scalars().all()
    return list(reversed(rows))


def _normalize_history(history: list[dict[str, Any]] | None) -> list[dict[str, str]]:
    normalized = []
    for item in history or []:
        role = str(item.get("role") or "").strip()
        if role == "ai":
            role = "assistant"
        if role not in {"user", "assistant", "system"}:
            continue
        content = str(item.get("content") or "").strip()
        if not content:
            continue
        normalized.append({"role": role, "content": content[:RAG_HISTORY_CONTENT_CHARS]})
    return normalized


def _dedupe_history(history: list[dict[str, str]]) -> list[dict[str, str]]:
    deduped = []
    seen = set()
    for item in history:
        key = (item["role"], item["content"])
        if key in seen:
            continue
        seen.add(key)
        deduped.append(item)
    return deduped


def _compact_history(history: list[dict[str, str]], max_messages: int = 16) -> list[dict[str, str]]:
    if len(history) <= max_messages:
        return history
    omitted = history[:-max_messages]
    summary = ";".join(f"{item['role']}:{item['content'][:RAG_HISTORY_SUMMARY_CHARS]}" for item in omitted[-RAG_HISTORY_SESSION_LIMIT:])
    return [{"role": "system", "content": f"较早会话摘要:{summary}"}] + history[-max_messages:]


def _source_digest(source: dict[str, Any]) -> dict[str, Any]:
    """把召回片段压成前端「思考过程」用的一行摘要:定位 + 分数 + 短预览。"""
    score = source.get("score") or {}
    content = source.get("content") or ""
    return {
        "source_index": source.get("source_index"),
        "chunk_id": source.get("chunk_id"),
        "source_name": source.get("source_name"),
        "title_path": source.get("title_path"),
        "section_title": source.get("section_title"),
        "page_start": source.get("page_start"),
        "page_end": source.get("page_end"),
        "content_kind": source.get("content_kind"),
        "retrieval_type": score.get("retrieval_type"),
        "rerank_score": score.get("rerank_score"),
        "vector_score": score.get("vector_score"),
        "preview": content[:120],
    }


def _reasoning_step(phase: str, title: str, status: str, start: float, data: dict[str, Any] | None = None) -> dict:
    return {
        "type": "reasoning_step",
        "data": {
            "id": phase,
            "phase": phase,
            "title": title,
            "status": status,
            "elapsed_ms": int((time.time() - start) * 1000),
            "data": data or {},
        },
    }

async def stream_query(payload):
    """
    RAG 对话核心业务逻辑(基于 SSE 流)。
    
    内部包含:
    1. 获取上下文历史
    2. 判断并抽取搜索意图
    3. 调用多路检索管道
    4. 对召回资料做拼接、构建最终 Prompt
    5. 请求大模型流式吐字并 Yield 回响应
    """
    from src.rag.retrieval import generate_answer_stream
    async with _query_semaphore:
        start = time.time()
        logger.info("[RAG] 开始处理查询: query=%r, userContext=%r", payload.query, payload.userContext)
        async with token_counter_context() as get_tokens:
            step_start = time.time()
            effective_history = await _build_effective_history(payload)
            yield _reasoning_step("history", "加载会话记忆", "done", step_start, {"messages": len(effective_history)})

            step_start = time.time()
            intent = await classify_intent(payload.query, effective_history)
            t_intent = int((time.time() - step_start) * 1000)
            logger.info(
                "[RAG] 意图识别结果: intent=%r intents=%r standalone=%r sub_queries=%r labels=%s degraded=%r t=%dms",
                intent.intent,
                intent.intents,
                intent.standalone_query,
                intent.sub_queries,
                intent.query_labels or "-",
                intent.degraded,
                t_intent,
            )
            yield {"type": "intent", "data": intent.__dict__}
            yield _reasoning_step("intent", "意图识别", "done", step_start, intent.__dict__)

            if intent.intent in {"chitchat", "unsupported"}:
                yield {"type": "retrieval_done", "data": {}}
                step_start = time.time()
                yield _reasoning_step("answer", "生成回答", "running", step_start, {"model": RAG_ANSWER_MODEL})
                answer = ""
                delta_count = 0
                if intent.intent == "chitchat":
                    # 闲聊也让模型真正读用户这句话作答(不检索知识库),而不是回固定问候语。
                    async with _llm_semaphore:
                        token = print_thinking.set(False)
                        try:
                            async for event in generate_chitchat_stream(payload.query, effective_history):
                                if event["type"] == "thinking_delta":
                                    continue
                                if event["type"] == "answer_delta":
                                    answer += event["content"]
                                    delta_count += 1
                                yield event
                        finally:
                            print_thinking.reset(token)
                else:
                    # unsupported:给出明确的不支持原因(无需模型),假流式吐出。
                    answer = intent.unsupported_reason or "当前 RAG 知识库仅支持知识问答,暂不处理课程推荐或任务检索。"
                    for i in range(0, len(answer), RAG_FAKE_STREAM_CHUNK_CHARS):
                        delta = answer[i : i + RAG_FAKE_STREAM_CHUNK_CHARS]
                        delta_count += 1
                        yield {"type": "answer_delta", "content": delta}
                        await asyncio.sleep(0)
                _log_answer_complete(answer, delta_count, step_start)
                final_dict = await _finish_query(payload, intent, {}, answer, get_tokens(), start, "Success")
                yield _reasoning_step("answer", "生成回答", "done", step_start, {"tokens": get_tokens(), "answer_length": len(answer)})
                yield {"type": "done", "data": final_dict}
                return

            step_start = time.time()
            yield _reasoning_step("retrieval", "检索资料", "running", step_start, {"query": payload.query})
            retrieval = await retrieve(payload.query, intent, effective_history, payload.userContext)
            chunks = retrieval["chunks"]
            t_retrieve = int((time.time() - step_start) * 1000)
            # 详细的「检索完成」汇总由 retriever.retrieve 内部打(含各变体召回数/耗时),此处不重复。
            safe_retrieval = {
                "filters": retrieval.get("filters"),
                "soft_boosts": retrieval.get("soft_boosts"),
                "query_plan": retrieval.get("query_plan"),
                "queries": retrieval.get("queries"),
                "recall": retrieval.get("recall"),
            }
            yield {"type": "retrieval_done", "data": safe_retrieval}
            yield _reasoning_step("retrieval", "检索资料", "done", step_start, {**safe_retrieval, "chunk_count": len(chunks)})

            step_start = time.time()
            # 召回片段带上定位与分数送前端「思考过程」,展开即可见(此前只送了计数)。
            sources = [_chunk_to_dict(c, preview=True, source_index=i + 1) for i, c in enumerate(chunks)]
            yield _reasoning_step("sources", "召回片段", "done", step_start,
                                  {"source_count": len(sources), "sources": [_source_digest(s) for s in sources]})

            answer = ""
            delta_count = 0
            answer_start = time.time()
            if chunks:
                yield _reasoning_step("answer", "生成回答", "running", answer_start, {"model": RAG_ANSWER_MODEL})
                async with _llm_semaphore:
                    token = print_thinking.set(False)
                    try:
                        async for event in generate_answer_stream(payload.query, intent, chunks, effective_history):
                            if event["type"] == "thinking_delta":
                                continue
                            if event["type"] == "answer_delta":
                                answer += event["content"]
                                delta_count += 1
                            yield event
                    finally:
                        print_thinking.reset(token)
                _log_answer_complete(answer, delta_count, answer_start)
            else:
                yield _reasoning_step("answer", "生成回答", "running", answer_start, {"model": RAG_ANSWER_MODEL})
                answer = FALLBACK_ANSWER
                delta_count = 1
                yield {"type": "answer_delta", "content": answer}
                _log_answer_complete(answer, delta_count, answer_start)
            t_answer = int((time.time() - answer_start) * 1000)

            tokens = get_tokens()
            final_dict = await _finish_query(payload, intent, retrieval, answer, tokens, start, "Success")
            # 一行可 grep 的查询总账:意图/召回总数/最终上下文/token/各阶段耗时,排障主入口。
            recalled_total = sum((retrieval.get("recall") or {}).values())
            logger.info(
                "[RAG] 查询完成: intent=%s recalled=%s final=%s tokens=%s "
                "t_intent=%dms t_retrieve=%dms t_answer=%dms t_total=%dms",
                intent.intent, recalled_total, len(chunks), tokens,
                t_intent, t_retrieve, t_answer, int((time.time() - start) * 1000),
            )
            yield _reasoning_step("answer", "生成回答", "done", answer_start, {"tokens": tokens, "answer_length": len(answer)})
            yield {"type": "done", "data": final_dict}

def _build_citations(answer: str, sources: list[dict[str, Any]]) -> list[dict[str, Any]]:
    used = sorted({int(item) for item in re.findall(r"\[(\d+)\]", answer or "")})
    source_by_index = {
        int(source.get("source_index") or pos): source
        for pos, source in enumerate(sources, start=1)
    }
    citations: list[dict[str, Any]] = []
    for idx in used:
        source = source_by_index.get(idx)
        if source:
            citations.append(
                {
                    "index": idx,
                    "chunk_id": source.get("chunk_id"),
                    "file_id": source.get("file_id"),
                    "source_name": source.get("source_name"),
                    "title_path": source.get("title_path"),
                    "page_start": source.get("page_start"),
                    "row_start": source.get("row_start"),
                    "row_end": source.get("row_end"),
                }
            )
    return citations


def _sources_from_citations(citations: list[dict[str, Any]], sources: list[dict[str, Any]]) -> list[dict[str, Any]]:
    if not citations:
        return []
    source_by_chunk_id = {source.get("chunk_id"): source for source in sources}
    selected = []
    seen = set()
    for citation in citations:
        chunk_id = citation.get("chunk_id")
        if not chunk_id or chunk_id in seen:
            continue
        source = source_by_chunk_id.get(chunk_id)
        if source:
            selected.append(source)
            seen.add(chunk_id)
    return selected