from __future__ import annotations from fastapi import APIRouter, HTTPException, status from pydantic import BaseModel from app.deps import AuthDep from app.schemas.tasks import TaskStatusResponse from app.services.lightrag_service import lightrag_service from app.services.supabase_rest import supabase_rest from app.services.task_tracker import task_tracker from app.workers.tasks import lightrag_index_pipeline router = APIRouter(prefix="/lightrag") class IndexRequest(BaseModel): document_id: str @router.post("/index", response_model=TaskStatusResponse) async def enqueue_lightrag_index(payload: IndexRequest, auth: AuthDep) -> TaskStatusResponse: document = supabase_rest.select_one( "documents", {"id": payload.document_id, "user_id": auth.user_id} ) if not document: raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Document not found") raw_text = str(document.get("raw_text") or "").strip() if not raw_text: raise HTTPException( status_code=status.HTTP_400_BAD_REQUEST, detail="文档尚未生成 raw_text,无法索引", ) supabase_rest.update( "documents", {"id": payload.document_id}, {"index_status": "pending"} ) task = task_tracker.create_task( user_id=auth.user_id, document_id=payload.document_id, task_type="index" ) lightrag_index_pipeline.delay(task.task_id, payload.document_id, auth.user_id) return task @router.get("/health") async def lightrag_health(): result = await lightrag_service.run_healthcheck() if not result.get("ok"): raise HTTPException( status_code=status.HTTP_503_SERVICE_UNAVAILABLE, detail=result.get("error", "LightRAG 未就绪"), ) return result