import asyncio import uuid from contextlib import asynccontextmanager from datetime import datetime from fastapi import BackgroundTasks, FastAPI, HTTPException from pydantic import BaseModel, Field # 全局变量存储模型和进度 model = None tokenizer = None upload_progress: dict[str, dict] = {} async def load_model_on_startup(): """异步加载模型""" global model, tokenizer try: # Simulating model loading for now # Replace with actual model loading logic # from modelscope import AutoModelForCausalLM, AutoTokenizer # import torch # model_name = "Qwen/Qwen3-30B-A3B" # tokenizer = AutoTokenizer.from_pretrained(model_name) # model = AutoModelForCausalLM.from_pretrained( # model_name, torch_dtype="auto", device_map="auto" # ) # For demonstration, let's assume model loading is successful # In a real scenario, you'd assign the loaded model and tokenizer # For now, we'll just set them to non-None to simulate success model = "mock_model" # Placeholder tokenizer = "mock_tokenizer" # Placeholder print("模型加载成功 (模拟)") return True except Exception as e: print(f"模型加载失败: {e}") # Ensure model and tokenizer are None if loading fails model = None tokenizer = None return False @asynccontextmanager async def lifespan(_app: FastAPI): # Load the ML model await load_model_on_startup() yield # Clean up the ML models and release the resources global model, tokenizer model = None tokenizer = None print("模型已卸载 (模拟)") app = FastAPI(title="LLM Query API", version="1.0.0", lifespan=lifespan) class QueryRequest(BaseModel): prompt: str = Field(..., description="用户输入的提示词") max_new_tokens: int = Field( default=512, ge=1, le=32768, description="最大生成token数" ) enable_thinking: bool = Field(default=True, description="是否启用思考模式") class QueryResponse(BaseModel): task_id: str = Field(..., description="任务ID") thinking_content: str | None = Field(None, description="模型思考内容") content: str = Field(..., description="模型回复内容") timestamp: datetime = Field(..., description="响应时间") class UploadProgressResponse(BaseModel): 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(): """健康检查端点""" return HealthResponse( status="healthy" if model is not None else "unhealthy", model_loaded=model is not None, timestamp=datetime.now(), ) async def process_query_task(task_id: str, request: QueryRequest): """后台处理查询任务""" upload_progress[task_id]["status"] = "processing" for i in range(10): await asyncio.sleep(10) # Simulate processing time upload_progress[task_id]["progress"] = (i + 1) * 10.0 upload_progress[task_id]["message"] = ( f"处理进度: {upload_progress[task_id]['progress']}%" ) upload_progress[task_id]["status"] = "completed" upload_progress[task_id]["result"] = QueryResponse( task_id=task_id, thinking_content="思考中...", content=f"模型回复: {request.prompt}", timestamp=datetime.now(), ) @app.post("/query", response_model=dict[str, str]) async def query_model(request: QueryRequest, background_tasks: BackgroundTasks): """查询模型端点""" if model is None or tokenizer is None: raise HTTPException(status_code=503, detail="模型未加载,请稍后重试") task_id = str(uuid.uuid4()) # 初始化任务进度 upload_progress[task_id] = { "status": "pending", "progress": 0.0, "message": "任务已创建", } # 添加后台任务 background_tasks.add_task(process_query_task, task_id, request) return {"task_id": task_id, "message": "查询任务已提交"} @app.get("/upload_progress/{task_id}", response_model=UploadProgressResponse) async def get_upload_progress(task_id: str): """获取任务进度端点""" if task_id not in upload_progress: raise HTTPException(status_code=404, detail="任务ID不存在") progress_data = upload_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): """获取查询结果端点""" if task_id not in upload_progress: raise HTTPException(status_code=404, detail="任务ID不存在") progress_data = upload_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"] if __name__ == "__main__": import uvicorn uvicorn.run(app, host="0.0.0.0", port=8000)