service.py 43.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 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962
from __future__ import annotations

import asyncio
import json
import os
import re
import shutil
import time
import logging
from datetime import datetime
from typing import Any

logger = logging.getLogger(__name__)

from fastapi import HTTPException, UploadFile
from sqlalchemy import delete, func, select, update

from config import BASE_DIR
from src.database.models import RagChunk, RagFile, RagIndexRun, RagQueryLog
from src.database.session import AsyncSessionLocal
from src.rag.errors import RagStructuredError
from src.rag.config import RAG_ANSWER_MODEL, RAG_EMBED_BATCH_SIZE, RAG_LLM_CONCURRENCY, RAG_QUERY_CONCURRENCY, RAG_INDEX_CONCURRENCY, RAG_RAW_DIR
from src.rag.ingest import RagChunkData, build_chunks, parse_document
from src.rag.loaders.common import RAG_CHUNKER_VERSION, RAG_PARSER_VERSION
from src.rag.loaders.pdf_loader import doc_vlm_stats
from src.rag.retrieval import FALLBACK_ANSWER, classify_intent, generate_answer, retrieve
from src.rag.schema_sync import ensure_rag_schema
from src.rag.stores import vector_store
from src.rag.utils import file_ext, safe_json_dumps, sha256_file
from src.utils.llm_tracker import print_thinking, token_counter_context

_file_locks: dict[str, asyncio.Lock] = {}
_query_semaphore = asyncio.Semaphore(RAG_QUERY_CONCURRENCY)
_llm_semaphore = asyncio.Semaphore(RAG_LLM_CONCURRENCY)
_index_semaphore = asyncio.Semaphore(RAG_INDEX_CONCURRENCY)


def _lock_for(file_id: str) -> asyncio.Lock:
    if file_id not in _file_locks:
        _file_locks[file_id] = asyncio.Lock()
    return _file_locks[file_id]


async def init_upload(files: list[str]) -> dict:
    """
    文件上传第一步:初始化记录。
    
    在数据库中创建处于 'Uploading' 状态的文件记录,并校验是否已有同名文件存在。
    """
    await ensure_rag_schema()
    mapping, errors = {}, {}
    async with AsyncSessionLocal() as session:
        for name in files:
            ext = file_ext(name).lstrip(".") or "txt"
            existing = await session.execute(select(RagFile).where(RagFile.name == name, RagFile.status != "Deleted"))
            if existing.scalars().first():
                errors[name] = "文件已存在,请勿重复上传。"
                continue
            raw_dir = os.path.join(RAG_RAW_DIR, ext)
            os.makedirs(raw_dir, exist_ok=True)
            db_file = RagFile(name=name, format=ext.upper(), size=0, source_path=os.path.join(raw_dir, name), status="Uploading")
            session.add(db_file)
            await session.flush()
            mapping[name] = db_file.id
        await session.commit()
    return {"mapping": mapping, "errors": errors}


async def save_upload(file_id: str, upload: UploadFile) -> dict:
    """
    文件上传第二步:保存物理文件流。
    
    将用户上传的二进制流固化到本地指定路径,更新文件大小与 Hash,状态变更为 'Pending'(等待建立索引)。
    """
    await ensure_rag_schema()
    async with AsyncSessionLocal() as session:
        db_file = await session.get(RagFile, file_id)
        if not db_file:
            raise HTTPException(status_code=404, detail="RAG file not found")
        if db_file.status != "Uploading":
            raise HTTPException(status_code=400, detail="文件不在 Uploading 状态")
        os.makedirs(os.path.dirname(db_file.source_path), exist_ok=True)
        await asyncio.to_thread(_save_upload_file, db_file.source_path, upload)
        db_file.size = os.path.getsize(db_file.source_path)
        db_file.content_hash = sha256_file(db_file.source_path)
        db_file.status = "Pending"
        await session.commit()
    return {"status": "success"}


async def preview_parse(path: str) -> dict:
    """
    后台调试方法:直接读取本地文件执行解析与切块,并不进行向量化及入库操作。
    主要用于在真实入库前评估解析器的提取质量。
    """
    source_path = _safe_project_path(path)
    if not os.path.exists(source_path):
        raise HTTPException(status_code=404, detail=f"文件不存在: {path}")
    start = time.time()
    blocks = await asyncio.to_thread(parse_document, source_path)
    parents, children = build_chunks("preview", os.path.basename(source_path), source_path, file_ext(source_path).lstrip(".").upper(), blocks)
    table_blocks = [b for b in blocks if b.block_type in {"table", "table_row"}]
    return {
        "path": source_path,
        "blocks": len(blocks),
        "table_blocks": len(table_blocks),
        "parent_chunks": len(parents),
        "child_chunks": len(children),
        "duration_ms": int((time.time() - start) * 1000),
        "sample_blocks": [
            {
                "block_type": b.block_type,
                "page_number": b.page_number,
                "title_path": b.title_path,
                "metadata": b.metadata,
                "text": b.text[:800],
            }
            for b in blocks[:12]
        ],
    }


async def list_files(page: int, page_size: int, search: str) -> dict:
    """
    分页查询文件列表及当前索引状态。
    支持按文件名模糊搜索。
    """
    await ensure_rag_schema()
    async with AsyncSessionLocal() as session:
        query = select(RagFile).where(RagFile.status != "Deleted")
        if search:
            query = query.where(RagFile.name.ilike(f"%{search}%"))
        total = (await session.execute(select(func.count()).select_from(query.subquery()))).scalar() or 0
        rows = (await session.execute(query.order_by(RagFile.created_at.desc()).offset((page - 1) * page_size).limit(page_size))).scalars().all()
        return {"files": [_file_to_dict(f) for f in rows], "total": total, "page": page, "page_size": page_size}


async def index_file(file_id: str) -> dict:
    """
    为指定的文件启动解析、切块、向量化(Embedding)以及保存倒排/向量索引到 Qdrant 的完整流程。
    
    该过程通常较慢,且会受并发控制,通过锁与状态防止重入。
    """
    await ensure_rag_schema()
    async with _lock_for(file_id):
        start = time.time()
        new_child_ids: list[str] = []
        db_committed = False
        async with AsyncSessionLocal() as session:
            db_file = await session.get(RagFile, file_id)
            if not db_file or db_file.status == "Deleted":
                raise HTTPException(status_code=404, detail="RAG file not found")
            if db_file.status == "Indexing":
                raise HTTPException(status_code=409, detail="文件正在索引中")
            if not os.path.exists(db_file.source_path):
                raise HTTPException(status_code=404, detail="源文件不存在")
            current_hash = sha256_file(db_file.source_path)
            if db_file.status == "Indexed" and db_file.content_hash == current_hash and db_file.chunk_count > 0:
                return {"status": "skipped", "reason": "索引已是最新"}
            old_chunk_ids = (await session.execute(select(RagChunk.chunk_id).where(RagChunk.file_id == file_id))).scalars().all()
            db_file.status = "Indexing"
            db_file.error_message = None
            db_file.error_code = None
            db_file.error_detail_json = None
            db_file.index_started_at = datetime.now()
            
            source_path = db_file.source_path
            name = db_file.name
            format_ext = db_file.format
            await session.commit()

        try:
            async with _index_semaphore:
                async with AsyncSessionLocal() as session:
                    check_file = await session.get(RagFile, file_id)
                    if not check_file or check_file.status == "Deleted":
                        return {"status": "skipped", "reason": "文件已被删除"}
                
                logger.info("[RAG] 正在处理 %s(file_id=%s):开始解析…", name, file_id)
                blocks = await asyncio.to_thread(parse_document, source_path)
                parents, children = build_chunks(file_id, name, source_path, format_ext, blocks)
                logger.info("[RAG] %s 切块完成:blocks=%d, parents=%d, children=%d;开始向量化…",
                            name, len(blocks), len(parents), len(children))
                _prepare_chunks(parents + children, "active")
                new_child_ids = [chunk.chunk_id for chunk in children]
                vector_count = await asyncio.to_thread(vector_store.upsert_children, children, max(16, RAG_EMBED_BATCH_SIZE * 4))
                logger.info("[RAG] %s 向量化完成:vectors=%d", name, vector_count)

                async with AsyncSessionLocal() as session:
                    await session.execute(delete(RagChunk).where(RagChunk.file_id == file_id))
                    for chunk in parents + children:
                        session.add(RagChunk(**_chunk_model_kwargs(chunk)))
                    db_file = await session.get(RagFile, file_id)
                    db_file.status = "Indexed"
                    db_file.content_hash = current_hash
                    db_file.error_code = None
                    db_file.error_detail_json = None
                    db_file.error_message = None
                    db_file.parser_version = _metadata_value(parents + children, "parser_version") or RAG_PARSER_VERSION
                    db_file.chunker_version = _metadata_value(parents + children, "chunker_version") or RAG_CHUNKER_VERSION
                    db_file.block_count = len(blocks)
                    db_file.word_count = sum(len(c.content) for c in parents)
                    db_file.chunk_count = len(parents) + len(children)
                    db_file.parent_chunk_count = len(parents)
                    db_file.child_chunk_count = len(children)
                    db_file.index_duration_ms = int((time.time() - start) * 1000)
                    vlm_stats = doc_vlm_stats(blocks)
                    db_file.vlm_page_count = int(vlm_stats.get("vlm_page_count") or 0)
                    db_file.vlm_total_tokens = int(vlm_stats.get("vlm_total_tokens") or 0)
                    db_file.vlm_duration_ms = int(vlm_stats.get("vlm_duration_ms") or 0)
                    db_file.indexed_at = datetime.now()
                    session.add(
                        RagIndexRun(
                            file_id=file_id,
                            status="Success",
                            parser_version=db_file.parser_version,
                            chunker_version=db_file.chunker_version,
                            block_count=len(blocks),
                            parent_chunk_count=len(parents),
                            child_chunk_count=len(children),
                            vector_count=vector_count,
                            duration_ms=db_file.index_duration_ms,
                            vlm_page_count=db_file.vlm_page_count,
                            vlm_total_tokens=db_file.vlm_total_tokens,
                        )
                    )
                    await session.commit()
                    db_committed = True

                if old_chunk_ids:
                    await asyncio.to_thread(vector_store.delete_chunk_ids, list(old_chunk_ids))
                duration_ms = int((time.time() - start) * 1000)
                logger.info(
                    "[RAG] 索引完成: %s → parents=%d, children=%d, vectors=%d, 用时 %dms;"
                    "VLM 落库: 页=%d, tokens=%d, VLM耗时=%dms",
                    name, len(parents), len(children), vector_count, duration_ms,
                    db_file.vlm_page_count, db_file.vlm_total_tokens, db_file.vlm_duration_ms,
                )
                return {"status": "success", "parent_chunks": len(parents), "child_chunks": len(children),
                        "vectors": vector_count, "duration_ms": duration_ms,
                        "vlm_page_count": db_file.vlm_page_count, "vlm_total_tokens": db_file.vlm_total_tokens}
        except Exception as exc:
            if new_child_ids and not db_committed:
                await asyncio.to_thread(vector_store.delete_chunk_ids, new_child_ids)
            error_code = _error_code(exc)
            error_detail_json = _error_detail_json(exc)
            if isinstance(exc, RagStructuredError):
                logger.error("[RAG] index failed with structured error: file_id=%s code=%s detail=%s", file_id, error_code, error_detail_json)
            else:
                logger.exception("[RAG] index failed: file_id=%s", file_id)
            async with AsyncSessionLocal() as session:
                db_file = await session.get(RagFile, file_id)
                if db_file:
                    db_file.status = "Failed" if isinstance(exc, RagStructuredError) else ("Indexed" if db_file.chunk_count > 0 else "Failed")
                    db_file.error_code = error_code
                    db_file.error_detail_json = error_detail_json
                    db_file.error_message = str(exc)
                    session.add(
                        RagIndexRun(
                            file_id=file_id,
                            status="Failed",
                            parser_version=getattr(db_file, "parser_version", None) or RAG_PARSER_VERSION,
                            chunker_version=getattr(db_file, "chunker_version", None) or RAG_CHUNKER_VERSION,
                            block_count=getattr(db_file, "block_count", 0) or 0,
                            parent_chunk_count=0,
                            child_chunk_count=0,
                            vector_count=0,
                            duration_ms=int((time.time() - start) * 1000),
                            error_code=error_code,
                            error_detail_json=error_detail_json,
                            error_message=str(exc),
                        )
                    )
                    await session.commit()
            raise


async def delete_index(file_id: str, keep_status: bool = False, force: bool = False) -> dict:
    """
    删除指定的已建索引(包括关系型数据库内的块记录以及 Qdrant 里的向量数据)。
    如果 keep_status=False,文件状态将回退至 'Pending'。
    """
    await ensure_rag_schema()
    async with _lock_for(file_id):
        await _delete_index_unlocked(file_id, keep_status, force)
    return {"status": "success"}


async def _delete_index_unlocked(file_id: str, keep_status: bool = False, force: bool = False) -> None:
    async with AsyncSessionLocal() as session:
        db_file = await session.get(RagFile, file_id)
        if not db_file:
            raise HTTPException(status_code=404, detail="RAG file not found")
        if db_file.status == "Indexing" and not force:
            raise HTTPException(status_code=409, detail="文件正在索引中,不能删除索引或文件")
        await asyncio.to_thread(vector_store.delete_file, file_id)
        await session.execute(delete(RagChunk).where(RagChunk.file_id == file_id))
        if not keep_status:
            db_file.status = "Pending"
            db_file.chunk_count = 0
            db_file.parent_chunk_count = 0
            db_file.child_chunk_count = 0
            db_file.error_message = None
        await session.commit()


async def repair_interrupted_indexes(cleanup_partial: bool = False) -> dict:
    """
    系统自愈工具:扫描因为服务器宕机等异常原因处于 Uploading/Indexing 假死状态的任务,
    尝试恢复或清理不完整的垃圾数据。
    """
    await ensure_rag_schema()
    repaired: list[dict] = []
    async with AsyncSessionLocal() as session:
        rows = (await session.execute(select(RagFile).where(RagFile.status.in_(["Uploading", "Indexing"])))).scalars().all()
    for row in rows:
        async with _lock_for(row.id):
            repaired.append(await _repair_one_file(row.id, cleanup_partial))
    return {"status": "success", "items": repaired}


async def _repair_one_file(file_id: str, cleanup_partial: bool) -> dict:
    async with AsyncSessionLocal() as session:
        db_file = await session.get(RagFile, file_id)
        if not db_file or db_file.status == "Deleted":
            return {"file_id": file_id, "action": "skip"}
        if db_file.status == "Uploading":
            if os.path.exists(db_file.source_path) and os.path.getsize(db_file.source_path) > 0:
                db_file.size = os.path.getsize(db_file.source_path)
                db_file.content_hash = sha256_file(db_file.source_path)
                db_file.status = "Pending"
                db_file.error_message = None
                action = "upload_recovered"
            else:
                db_file.status = "Failed"
                db_file.error_message = "服务重启导致上传中断,请重新上传"
                action = "upload_failed"
            await session.commit()
            return {"file_id": file_id, "action": action}

        parent_count = (await session.execute(select(func.count()).select_from(RagChunk).where(RagChunk.file_id == file_id, RagChunk.chunk_level == "parent"))).scalar() or 0
        child_count = (await session.execute(select(func.count()).select_from(RagChunk).where(RagChunk.file_id == file_id, RagChunk.chunk_level == "child"))).scalar() or 0

    vector_count = await asyncio.to_thread(vector_store.count_file, file_id)
    async with AsyncSessionLocal() as session:
        db_file = await session.get(RagFile, file_id)
        if not db_file or db_file.status == "Deleted":
            return {"file_id": file_id, "action": "skip"}
        complete = child_count > 0 and (vector_count is None or vector_count >= child_count)
        if complete:
            active_children = (await session.execute(select(func.count()).select_from(RagChunk).where(RagChunk.file_id == file_id, RagChunk.chunk_level == "child", RagChunk.status == "active"))).scalar() or 0
            db_file.status = "Indexed" if active_children else "Disabled"
            db_file.parent_chunk_count = parent_count
            db_file.child_chunk_count = child_count
            db_file.chunk_count = parent_count + child_count
            db_file.error_message = None
            db_file.indexed_at = db_file.indexed_at or datetime.now()
            await session.commit()
            return {"file_id": file_id, "action": "index_recovered", "parent_chunks": parent_count, "child_chunks": child_count, "vectors": vector_count}
        if cleanup_partial:
            await asyncio.to_thread(vector_store.delete_file, file_id)
            await session.execute(delete(RagChunk).where(RagChunk.file_id == file_id))
            db_file.status = "Pending"
            db_file.chunk_count = 0
            db_file.parent_chunk_count = 0
            db_file.child_chunk_count = 0
            db_file.error_message = "已清理中断索引,请重新生成索引"
            action = "partial_cleaned"
        else:
            await session.execute(update(RagChunk).where(RagChunk.file_id == file_id).values(status="disabled"))
            await asyncio.to_thread(vector_store.set_file_status, file_id, "disabled")
            db_file.status = "Failed"
            db_file.error_message = f"索引被中断且数据不完整:DB child={child_count}, Qdrant points={vector_count},请重建索引"
            action = "partial_disabled"
        await session.commit()
        return {"file_id": file_id, "action": action, "parent_chunks": parent_count, "child_chunks": child_count, "vectors": vector_count}


async def get_chunks(file_id: str) -> dict:
    """读取并返回某个文件所有切分的子段列表(含 Chunk 元数据)。"""
    await ensure_rag_schema()
    async with AsyncSessionLocal() as session:
        rows = (await session.execute(select(RagChunk).where(RagChunk.file_id == file_id).order_by(RagChunk.chunk_level.desc(), RagChunk.chunk_index))).scalars().all()
        return {"chunks": [_chunk_to_dict(c, preview=False) for c in rows]}


async def get_chunk(chunk_id: str) -> dict:
    await ensure_rag_schema()
    async with AsyncSessionLocal() as session:
        row = (await session.execute(select(RagChunk).where(RagChunk.chunk_id == chunk_id))).scalar_one_or_none()
        if not row:
            raise HTTPException(status_code=404, detail="Chunk not found")
        return {"chunk": _chunk_to_dict(row)}


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


_SAVE_QUERY_TIMEOUT_SECONDS = float(os.environ.get("RAG_SAVE_QUERY_TIMEOUT_SECONDS", "3"))


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),
            "is_neighbor": bool(getattr(c, "is_neighbor", False)),
        }
        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", []),
            "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=_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")
    await ensure_rag_schema()
    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 = 6) -> 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[:1200]})
    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'][:80]}" for item in omitted[-6:])
    return [{"role": "system", "content": f"较早会话摘要:{summary}"}] + history[-max_messages:]


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
    await ensure_rag_schema()
    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)
            logger.info(
                "[RAG] 意图识别结果: intent=%r, brand=%r, category=%r, need_clarification=%r",
                intent.intent,
                intent.brand,
                intent.business_category,
                intent.need_clarification,
            )
            yield {"type": "intent", "data": intent.__dict__}
            yield _reasoning_step("intent", "意图识别", "done", step_start, intent.__dict__)

            if intent.intent in {"chitchat", "unsupported"}:
                if intent.intent == "chitchat":
                    answer = "您好!我是您的智能助手,请问有什么可以帮您的吗?"
                else:
                    answer = intent.unsupported_reason or "当前 RAG 知识库仅支持知识问答,暂不处理课程推荐或任务检索。"
                yield {"type": "retrieval_done", "data": {}}
                step_start = time.time()
                yield _reasoning_step("answer", "生成回答", "running", step_start, {"model": RAG_ANSWER_MODEL})
                delta_count = 0
                for i in range(0, len(answer), 8):
                    delta = answer[i : i + 8]
                    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"]
            logger.info("[RAG] 检索完成: 召回 %s 个片段", len(chunks))
            safe_retrieval = {
                "filters": retrieval.get("filters"),
                "soft_boosts": retrieval.get("soft_boosts"),
                "query_plan": retrieval.get("query_plan"),
                "queries": retrieval.get("queries"),
            }
            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)})

            answer = ""
            delta_count = 0
            if chunks:
                step_start = time.time()
                yield _reasoning_step("answer", "生成回答", "running", step_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, step_start)
            else:
                step_start = time.time()
                yield _reasoning_step("answer", "生成回答", "running", step_start, {"model": RAG_ANSWER_MODEL})
                answer = FALLBACK_ANSWER
                delta_count = 1
                yield {"type": "answer_delta", "content": answer}
                _log_answer_complete(answer, delta_count, step_start)

            final_dict = await _finish_query(payload, intent, retrieval, 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}


async def stats() -> dict:
    """汇总各个阶段的文件数量及 Qdrant 集群健康概况统计。"""
    await ensure_rag_schema()
    async with AsyncSessionLocal() as session:
        total_files = (await session.execute(select(func.count()).select_from(RagFile).where(RagFile.status != "Deleted"))).scalar() or 0
        indexed = (await session.execute(select(func.count()).select_from(RagFile).where(RagFile.status == "Indexed"))).scalar() or 0
        disabled = (await session.execute(select(func.count()).select_from(RagFile).where(RagFile.status == "Disabled"))).scalar() or 0
        indexing = (await session.execute(select(func.count()).select_from(RagFile).where(RagFile.status == "Indexing"))).scalar() or 0
        failed = (await session.execute(select(func.count()).select_from(RagFile).where(RagFile.status == "Failed"))).scalar() or 0
        chunks = (await session.execute(select(func.count()).select_from(RagChunk).where(RagChunk.status == "active"))).scalar() or 0
    return {"files": total_files, "indexed": indexed, "disabled": disabled, "indexing": indexing, "failed": failed, "chunks": chunks, **vector_store.health()}


def _save_upload_file(path: str, upload: UploadFile) -> None:
    with open(path, "wb") as f:
        shutil.copyfileobj(upload.file, f)


def _safe_project_path(path: str) -> str:
    abs_path = os.path.abspath(path)
    base = os.path.abspath(BASE_DIR)
    if not abs_path.startswith(base + os.sep):
        raise HTTPException(status_code=400, detail="只允许导入项目目录内的文件")
    return abs_path


def _prepare_chunks(chunks: list[RagChunkData], status: str) -> None:
    for chunk in chunks:
        chunk.status = status


def _file_to_dict(f: RagFile) -> dict:
    return {
        "id": f.id,
        "document_id": f.id,
        "name": f.name,
        "format": f.format,
        "size": f.size,
        "word_count": f.word_count,
        "status": f.status,
        "parser_version": getattr(f, "parser_version", None),
        "chunker_version": getattr(f, "chunker_version", None),
        "block_count": getattr(f, "block_count", 0),
        "chunk_count": f.chunk_count,
        "parent_chunk_count": f.parent_chunk_count,
        "child_chunk_count": f.child_chunk_count,
        "vlm_page_count": getattr(f, "vlm_page_count", 0),
        "vlm_total_tokens": getattr(f, "vlm_total_tokens", 0),
        "vlm_duration_ms": getattr(f, "vlm_duration_ms", 0),
        "error_code": getattr(f, "error_code", None),
        "error_detail_json": _json_or_empty(getattr(f, "error_detail_json", None)),
        "error_message": f.error_message,
        "created_at": f.created_at.strftime("%Y-%m-%d %H:%M:%S") if f.created_at else "",
        "indexed_at": f.indexed_at.strftime("%Y-%m-%d %H:%M:%S") if f.indexed_at else "",
    }


def _error_code(exc: Exception) -> str | None:
    return getattr(exc, "error_code", None)


def _error_detail_json(exc: Exception) -> str | None:
    if isinstance(exc, RagStructuredError):
        return exc.to_json()
    return None


def _metadata_value(chunks: list[RagChunkData], key: str) -> str | None:
    for chunk in chunks:
        value = chunk.metadata_json.get(key) if isinstance(chunk.metadata_json, dict) else None
        if value:
            return str(value)
    return None


def _as_int(value: Any) -> int | None:
    if value is None or value == "":
        return None
    try:
        return int(value)
    except (TypeError, ValueError):
        return None


def _as_text(value: Any) -> str | None:
    if value is None:
        return None
    if isinstance(value, (list, dict)):
        return safe_json_dumps(value)
    text = str(value).strip()
    return text or None


def _chunk_model_kwargs(c: RagChunkData) -> dict:
    """构建精简 rag_chunks 的写库参数:只写真正用到的列,其余结构化字段全部收进 metadata_json。"""
    metadata = dict(c.metadata_json) if isinstance(c.metadata_json, dict) else {}
    # 把数据类上的标量字段并入 metadata_json,避免精简列后信息丢失(供 UI/调试/排障)
    for key in ("brand", "brand_series", "sub_business", "page_type", "intent_type",
                "business_category", "source_path", "file_type", "slide_number", "sheet_name",
                "parser_version", "chunker_version"):
        value = getattr(c, key, None)
        if value is None:
            value = metadata.get(key)
        if value is not None:
            metadata.setdefault(key, value)
    metadata.setdefault("parser_version", RAG_PARSER_VERSION)
    metadata.setdefault("chunker_version", RAG_CHUNKER_VERSION)
    return {
        "chunk_id": c.chunk_id,
        "file_id": c.file_id,
        "parent_chunk_id": c.parent_chunk_id,
        "chunk_level": c.chunk_level,
        "chunk_index": c.chunk_index,
        "content": c.content,
        "content_hash": c.content_hash,
        "token_estimate": c.token_estimate,
        "title_path": c.title_path,
        "source_name": c.source_name,
        "page_start": _as_int(metadata.get("page_start")) or c.page_number,
        "page_end": _as_int(metadata.get("page_end")),
        "row_start": c.row_start,
        "row_end": c.row_end,
        "prev_chunk_id": c.prev_chunk_id,
        "next_chunk_id": c.next_chunk_id,
        "status": c.status,
        "brand_series": _as_text(metadata.get("brand_series")),
        "business_category": _as_text(c.business_category),
        "content_kind": _as_text(metadata.get("content_kind")),
        "section_title": _as_text(metadata.get("section_title")),
        "parse_status": _as_text(metadata.get("parse_status") or "ok"),
        "qdrant_point_id": vector_store.point_id(c.chunk_id),
        "metadata_json": safe_json_dumps(metadata),
    }


def _chunk_to_dict(c: RagChunk, preview: bool = False, source_index: int | None = None) -> dict:
    content = c.content[:320] + "..." if preview and len(c.content) > 320 else c.content
    metadata = _json_or_empty(c.metadata_json)
    data = {
        "chunk_id": c.chunk_id,
        "file_id": c.file_id,
        "document_id": c.file_id,
        "parent_chunk_id": c.parent_chunk_id,
        "chunk_level": c.chunk_level,
        "chunk_index": c.chunk_index,
        "content": content,
        "title_path": c.title_path,
        "source_name": c.source_name,
        "page_start": getattr(c, "page_start", None),
        "page_end": getattr(c, "page_end", None),
        "slide_number": metadata.get("slide_number"),
        "sheet_name": metadata.get("sheet_name"),
        "row_start": c.row_start,
        "row_end": c.row_end,
        "content_kind": getattr(c, "content_kind", None),
        "section_title": getattr(c, "section_title", None),
        "parse_status": getattr(c, "parse_status", None),
        "parse_quality": metadata.get("parse_quality"),
        "status": c.status,
        "intent_type": metadata.get("intent_type"),
        "page_type": metadata.get("page_type"),
        "brand": metadata.get("brand"),
        "brand_series": getattr(c, "brand_series", None),
        "business_category": c.business_category,
        "sub_business": metadata.get("sub_business"),
        "metadata_json": metadata,
        "score": {
            "vector_score": round(float(getattr(c, "vector_score", 0.0) or 0.0), 4),
            "final_score": round(float(getattr(c, "final_score", 0.0) or 0.0), 4),
            "rerank_score": round(float(getattr(c, "rerank_score", 0.0) or 0.0), 4),
            "is_neighbor": bool(getattr(c, "is_neighbor", False)),
        },
    }
    if source_index is not None:
        data["source_index"] = source_index
    return data


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


def _json_or_empty(value: str | None) -> dict:
    if not value:
        return {}
    try:
        return json.loads(value)
    except Exception:
        return {}