routes.py 10.1 KB
"""
RAG HTTP 路由配置与接口暴露模块。
向外部系统或者前端提供了诸如:文件上传、解析预览、建库索引、数据检索(包括 SSE 流式输出)等能力的 API 接口。
"""
import asyncio
import json
import logging
import os

from fastapi import APIRouter, Body, HTTPException, UploadFile, File, BackgroundTasks
from fastapi.responses import StreamingResponse

from src.rag import service
from src.rag.config import RAG_INDEX_CONCURRENCY
from src.rag.schemas import RagImportReferenceRequest, RagQueryRequest, RagUploadInitRequest

logger = logging.getLogger(__name__)
router = APIRouter()


@router.get("/rag/health")
async def rag_health():
    """探针接口:用于检查 RAG 子系统及底层向量数据库的健康状态和基础统计信息。"""
    data = await service.stats()
    return {"status": "ok", **data}


@router.get("/rag/files")
async def rag_files(page: int = 1, page_size: int = 20, search: str = ""):
    """分页获取知识库中已经上传或构建索引的文档列表。"""
    return await service.list_files(page, page_size, search)


@router.post("/rag/upload/init")
async def rag_upload_init(payload: RagUploadInitRequest):
    """
    文件上传初始化步骤:
    客户端发送准备上传的文件信息,服务端在数据库生成待传记录 ID,并做重复判断校验。
    """
    return await service.init_upload([f.name for f in payload.files])


@router.post("/rag/upload/{file_id}")
async def rag_upload(file_id: str, file: UploadFile = File(...)):
    """
    执行文件流的实体上传操作:
    将上传的文件字节流保存至本地磁盘,更新对应的数据记录状态。
    """
    return await service.save_upload(file_id, file)


@router.post("/rag/preview_parse")
async def rag_preview_parse(data: dict = Body(...)):
    """
    后台调试及预览接口:
    输入本地文件路径,模拟文档解析及切块的执行过程,并直接返回切分效果给前端预览,并不存入数据库。
    """
    path = data.get("path")
    if not path:
        raise HTTPException(status_code=400, detail="path is required")
    return await service.preview_parse(path)


@router.delete("/rag/files/{file_id}")
async def rag_delete_file(file_id: str):
    """
    删除知识库指定的单个文件及关联物理存储:
    必须处于非索引中状态;物理删除文件并调用底层销毁相关向量。
    """
    from src.database.models import RagFile
    from src.database.session import AsyncSessionLocal

    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 in ["Indexed", "Indexing"]:
            raise HTTPException(status_code=400, detail="请先删除索引再删除文件")

        # 物理删除原始文档文件
        if os.path.exists(db_file.source_path):
            os.remove(db_file.source_path)
        db_file.status = "Deleted"
        await session.commit()
        
    await service.delete_index(file_id, keep_status=True, force=True)
    return {"status": "success"}


@router.post("/rag/files/batch_delete")
async def rag_batch_delete(data: dict = Body(...)):
    """批量删除知识库文件。"""
    ids = data.get("ids", [])
    errors = []
    for file_id in ids:
        try:
            await rag_delete_file(file_id)
        except Exception as exc:
            errors.append({"file_id": file_id, "error": str(exc)})
    return {"status": "success", "errors": errors}


@router.post("/rag/index/{file_id}")
async def rag_index(file_id: str):
    """
    发起单文件的索引构建任务:
    将实际费时的解析、切块、向量化写入等放入 asyncio task 异步执行。
    """
    from src.database.models import RagFile
    from src.database.session import AsyncSessionLocal
    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":
            return {"status": "already indexing", "file_id": file_id}
        
    asyncio.create_task(service.index_file(file_id))
    return {"status": "index started", "file_id": file_id}


@router.post("/rag/batch_index")
async def rag_batch_index(data: dict = Body(...)):
    """批量对未进行或已失效的文件触发索引构建任务。"""
    ids = data.get("ids", [])
    from src.database.models import RagFile
    from src.database.session import AsyncSessionLocal
    count = 0
    async with AsyncSessionLocal() as session:
        for file_id in ids:
            db_file = await session.get(RagFile, file_id)
            if db_file and db_file.status != "Indexing":
                asyncio.create_task(service.index_file(file_id))
                count += 1
    return {"status": "batch index started", "count": count}

@router.post("/rag/batch_delete_index")
async def rag_batch_delete_index(data: dict = Body(...)):
    """批量删除文件的索引数据及向量库关联(但保留文件实体不变)。"""
    ids = data.get("ids", [])
    force = data.get("force", False)
    count = 0
    errors = []
    for file_id in ids:
        try:
            await service.delete_index(file_id, force=force)
            count += 1
        except Exception as exc:
            errors.append({"file_id": file_id, "error": str(exc)})
    return {"status": "batch delete index completed", "count": count, "errors": errors}

@router.delete("/rag/index/{file_id}")
async def rag_delete_index(file_id: str, force: bool = False):
    """单独删除某文件的索引数据及向量库关联(但保留文件实体不变)。"""
    return await service.delete_index(file_id, force=force)


@router.post("/rag/rebuild_bm25")
async def rag_rebuild_bm25():
    """重建 Sparse Vector(BM25类似效果)的独立管理接口(当算法变更或库迁移时使用)。"""
    count = await service.rebuild_bm25_from_db()
    return {"status": "success", "bm25_docs": count}


@router.get("/rag/chunks/{file_id}")
async def rag_chunks(file_id: str):
    """后台工具接口:读取并展示某个文件切分产生的所有子区块。"""
    return await service.get_chunks(file_id)


@router.get("/rag/chunk/{chunk_id}")
async def rag_chunk(chunk_id: str):
    """后台工具接口:直接查看特定分块片段详情。"""
    return await service.get_chunk(chunk_id)


@router.post("/rag/query/json")
async def rag_query_json(payload: RagQueryRequest):
    """
    发起单次知识检索与生成请求(非流式接口)。
    返回一个完整的 JSON 响应(包含生成的回答、引用来源等),适用于不需要流式打印的场景。
    """
    return await service.query_json(payload)


@router.post("/rag/query")
async def rag_query(payload: RagQueryRequest):
    """
    发起知识库检索以及大模型作答请求,这是 RAG 前端主要的问答聊天接口。
    结果基于 Server-Sent Events (SSE) 方式实现流式输出(逐字吐出)。
    """
    async def events():
        yield "data: [INIT]\n\n"
        try:
            logger.info(f"[RAG] 收到 SSE 查询请求: query={payload.query}, sessionId={payload.sessionId}, history_len={len(payload.history) if payload.history else 0}")
            yield f"data: {json.dumps({'type': 'retrieval_start'}, ensure_ascii=False)}\n\n"
            async for event in service.stream_query(payload):
                yield f"data: {json.dumps(event, ensure_ascii=False)}\n\n"
            logger.info("[RAG] SSE 查询流式发送完成")
        except Exception as exc:
            logger.exception("[RAG] SSE 查询失败")
            yield f"data: {json.dumps({'type': 'error', 'content': str(exc)}, ensure_ascii=False)}\n\n"

    return StreamingResponse(
        events(),
        media_type="text/event-stream",
        headers={
            "Cache-Control": "no-cache",
            "X-Accel-Buffering": "no",
        },
    )


@router.post("/rag/clear_history")
async def rag_clear_history(data: dict = Body(default={})):
    """清除给定 Session 相关的 RAG 系统对话历史。"""
    return await service.clear_history(data.get("sessionId"))


@router.get("/rag/stats")
async def rag_stats():
    """返回 RAG 知识库大盘统计概况(文件数、索引数、片段数)。"""
    return await service.stats()


@router.post("/rag/files/batch_download")
async def rag_batch_download(data: dict = Body(...)):
    """批量下载文件。如果是单个文件直接返回,多个文件打包为zip。"""
    ids = data.get("ids", [])
    if not ids:
        raise HTTPException(status_code=400, detail="未提供文件ID")
        
    from src.database.models import RagFile
    from src.database.session import AsyncSessionLocal
    
    files = []
    async with AsyncSessionLocal() as session:
        for file_id in ids:
            db_file = await session.get(RagFile, file_id)
            if db_file and os.path.exists(db_file.source_path):
                files.append(db_file)
                
    if not files:
        raise HTTPException(status_code=404, detail="未找到可下载的文件")
        
    import urllib.parse
    if len(files) == 1:
        # 单个文件直接下载
        from fastapi.responses import FileResponse
        file = files[0]
        filename = urllib.parse.quote(file.name)
        return FileResponse(
            path=file.source_path, 
            filename=file.name,
            headers={"Content-Disposition": f"attachment; filename*=utf-8''{filename}"}
        )
    else:
        # 多个文件打包成zip
        import io
        import zipfile
        from fastapi.responses import StreamingResponse
        zip_buffer = io.BytesIO()
        with zipfile.ZipFile(zip_buffer, "w", zipfile.ZIP_DEFLATED) as zip_file:
            for file in files:
                zip_file.write(file.source_path, arcname=file.name)
        
        zip_buffer.seek(0)
        return StreamingResponse(
            zip_buffer,
            media_type="application/zip",
            headers={"Content-Disposition": "attachment; filename*=utf-8''batch_download.zip"}
        )