178 lines
5.5 KiB
Python
178 lines
5.5 KiB
Python
import uuid
|
|
from contextlib import asynccontextmanager
|
|
from datetime import datetime
|
|
|
|
from fastapi import BackgroundTasks, Depends, FastAPI, HTTPException
|
|
from pydantic import BaseModel, Field
|
|
|
|
from global_context import GlobalContext
|
|
from query_parameter import QueryRequest, QueryResponse, process_query_task
|
|
|
|
# Singleton instance holder
|
|
_global_context_instance = None
|
|
|
|
|
|
def get_global_context_instance() -> GlobalContext:
|
|
"""
|
|
Factory function to get singleton GlobalContext instance.
|
|
如果实例不存在,则创建一个新的实例。
|
|
如果实例已存在,则返回现有实例。
|
|
"""
|
|
global _global_context_instance
|
|
if _global_context_instance is None:
|
|
_global_context_instance = GlobalContext()
|
|
return _global_context_instance
|
|
|
|
|
|
# 使用 asynccontextmanager 定义应用的生命周期管理
|
|
@asynccontextmanager
|
|
async def lifespan(_app: FastAPI):
|
|
"""
|
|
定义应用的生命周期管理。
|
|
在应用启动时加载模型,在应用关闭时释放资源。
|
|
"""
|
|
manager = get_global_context_instance()
|
|
await manager.load_model() # 加载模型
|
|
yield # 暂停,等待应用运行
|
|
# 应用关闭时清理模型资源
|
|
manager.unload_model()
|
|
|
|
|
|
# 创建 FastAPI 应用实例,并设置生命周期管理
|
|
app = FastAPI(title="LLM Query API", version="1.0.0", lifespan=lifespan)
|
|
|
|
|
|
# 依赖注入函数,用于获取模型管理器实例
|
|
def get_model_manager() -> GlobalContext:
|
|
"""
|
|
依赖注入函数,返回模型管理器实例。
|
|
这种方式便于测试和管理依赖关系。
|
|
"""
|
|
return get_global_context_instance()
|
|
|
|
|
|
# 定义任务进度的响应模型
|
|
class UploadProgressResponse(BaseModel):
|
|
"""
|
|
任务进度的响应模型。
|
|
包含任务 ID、状态、进度百分比和状态消息。
|
|
"""
|
|
|
|
task_id: str = Field(..., description="任务 ID")
|
|
status: str = Field(
|
|
..., description="任务状态: pending, processing, completed, failed"
|
|
)
|
|
progress: float = Field(..., ge=0.0, le=100.0, description="进度百分比")
|
|
message: str | None = Field(None, description="状态消息")
|
|
|
|
|
|
# 定义健康检查的响应模型
|
|
class HealthResponse(BaseModel):
|
|
"""
|
|
健康检查的响应模型。
|
|
包含服务状态、模型加载状态和时间戳。
|
|
"""
|
|
|
|
status: str = Field(..., description="服务状态")
|
|
model_loaded: bool = Field(..., description="模型是否已加载")
|
|
timestamp: datetime = Field(..., description="检查时间")
|
|
|
|
|
|
# 健康检查端点,用于检查服务和模型的状态
|
|
@app.get("/health", response_model=HealthResponse)
|
|
async def health_check(manager: GlobalContext = Depends(get_model_manager)):
|
|
"""
|
|
健康检查端点。
|
|
返回服务状态和模型加载状态。
|
|
"""
|
|
return HealthResponse(
|
|
status="healthy" if manager.is_model_loaded() else "unhealthy",
|
|
model_loaded=manager.is_model_loaded(),
|
|
timestamp=datetime.now(),
|
|
)
|
|
|
|
|
|
# 查询模型的端点,接收用户请求并启动后台任务
|
|
@app.post("/query", response_model=dict[str, str])
|
|
async def query_model(
|
|
request: QueryRequest,
|
|
background_tasks: BackgroundTasks,
|
|
manager: GlobalContext = Depends(get_model_manager),
|
|
):
|
|
"""
|
|
查询模型端点。
|
|
接收用户请求,启动后台任务处理查询,并返回任务 ID。
|
|
"""
|
|
if not manager.is_model_loaded():
|
|
raise HTTPException(status_code=503, detail="模型未加载,请稍后重试")
|
|
|
|
task_id = str(uuid.uuid4()) # 生成唯一任务 ID
|
|
|
|
# 初始化任务进度
|
|
manager.create_task(task_id)
|
|
|
|
# 添加后台任务,传递 manager 实例
|
|
background_tasks.add_task(process_query_task, task_id, request, manager)
|
|
|
|
return {"task_id": task_id, "message": "查询任务已提交"}
|
|
|
|
|
|
# 获取任务进度的端点
|
|
@app.get("/upload_progress/{task_id}", response_model=UploadProgressResponse)
|
|
async def get_upload_progress(
|
|
task_id: str, manager: GlobalContext = Depends(get_model_manager)
|
|
):
|
|
"""
|
|
获取任务进度端点。
|
|
返回指定任务的状态和进度信息。
|
|
"""
|
|
if not manager.task_exists(task_id):
|
|
raise HTTPException(status_code=404, detail="任务 ID 不存在")
|
|
|
|
progress_data = manager.get_task_progress(task_id)
|
|
|
|
response = UploadProgressResponse(
|
|
task_id=task_id,
|
|
status=progress_data["status"],
|
|
progress=progress_data["progress"],
|
|
message=progress_data.get("message"),
|
|
)
|
|
|
|
# 如果任务完成,返回结果提示
|
|
if progress_data["status"] == "completed" and "result" in progress_data:
|
|
response.message = "任务完成,请查看结果"
|
|
|
|
return response
|
|
|
|
|
|
# 获取查询结果的端点
|
|
@app.get("/query_result/{task_id}", response_model=QueryResponse)
|
|
async def get_query_result(
|
|
task_id: str, manager: GlobalContext = Depends(get_model_manager)
|
|
):
|
|
"""
|
|
获取查询结果端点。
|
|
返回指定任务的最终结果。
|
|
"""
|
|
if not manager.task_exists(task_id):
|
|
raise HTTPException(status_code=404, detail="任务 ID 不存在")
|
|
|
|
progress_data = manager.get_task_progress(task_id)
|
|
|
|
if progress_data["status"] != "completed":
|
|
raise HTTPException(
|
|
status_code=202, detail=f"任务状态: {progress_data['status']}"
|
|
)
|
|
|
|
if "result" not in progress_data:
|
|
raise HTTPException(status_code=500, detail="任务完成但结果不可用")
|
|
|
|
return progress_data["result"]
|
|
|
|
|
|
# 应用程序入口,使用 Uvicorn 启动服务
|
|
if __name__ == "__main__":
|
|
import uvicorn
|
|
|
|
uvicorn.run(app, host="0.0.0.0", port=8000)
|