238 lines
7.7 KiB
Python
238 lines
7.7 KiB
Python
import asyncio
|
|
import uuid
|
|
from contextlib import asynccontextmanager
|
|
from datetime import datetime
|
|
|
|
from fastapi import BackgroundTasks, FastAPI, HTTPException
|
|
from pydantic import BaseModel, Field
|
|
|
|
# 全局变量存储模型和任务进度
|
|
# model 和 tokenizer 用于存储加载的机器学习模型和分词器
|
|
# upload_progress 是一个字典,用于跟踪每个任务的状态和进度
|
|
model = None
|
|
tokenizer = None
|
|
upload_progress: dict[str, dict] = {}
|
|
|
|
|
|
# 异步加载模型的函数
|
|
async def load_model_on_startup():
|
|
"""
|
|
异步加载机器学习模型。
|
|
在应用启动时调用,用于初始化模型和分词器。
|
|
"""
|
|
global model, tokenizer
|
|
try:
|
|
# 模拟模型加载逻辑
|
|
# 实际情况下,这里可以加载真实的模型和分词器,例如使用 ModelScope 或 PyTorch
|
|
# 非模型任务也可以不用加载模型
|
|
# 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"
|
|
# )
|
|
model = "mock_model" # 模拟模型对象
|
|
tokenizer = "mock_tokenizer" # 模拟分词器对象
|
|
print("模型加载成功 (模拟)")
|
|
return True
|
|
except Exception as e:
|
|
# 如果加载失败,打印错误信息并将模型和分词器设置为 None
|
|
print(f"模型加载失败: {e}")
|
|
model = None
|
|
tokenizer = None
|
|
return False
|
|
|
|
|
|
# 使用 asynccontextmanager 定义应用的生命周期管理
|
|
@asynccontextmanager
|
|
async def lifespan(_app: FastAPI):
|
|
"""
|
|
定义应用的生命周期管理。
|
|
在应用启动时加载模型,在应用关闭时释放资源。
|
|
"""
|
|
await load_model_on_startup() # 加载模型
|
|
yield # 暂停,等待应用运行
|
|
# 应用关闭时清理模型资源
|
|
global model, tokenizer
|
|
model = None
|
|
tokenizer = None
|
|
print("模型已卸载 (模拟)")
|
|
|
|
|
|
# 创建 FastAPI 应用实例,并设置生命周期管理
|
|
app = FastAPI(title="LLM Query API", version="1.0.0", lifespan=lifespan)
|
|
|
|
|
|
# 定义请求模型,用于接收用户的查询请求
|
|
class QueryRequest(BaseModel):
|
|
"""
|
|
用户查询请求的数据模型。
|
|
包含提示词、最大生成 token 数量和是否启用思考模式。
|
|
"""
|
|
|
|
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):
|
|
"""
|
|
查询结果的响应模型。
|
|
包含任务 ID、思考内容、模型回复内容和时间戳。
|
|
"""
|
|
|
|
task_id: str = Field(..., description="任务 ID")
|
|
thinking_content: str | None = Field(None, description="模型思考内容")
|
|
content: str = Field(..., description="模型回复内容")
|
|
timestamp: datetime = Field(..., description="响应时间")
|
|
|
|
|
|
# 定义任务进度的响应模型
|
|
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():
|
|
"""
|
|
健康检查端点。
|
|
返回服务状态和模型加载状态。
|
|
"""
|
|
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) # 模拟处理时间
|
|
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):
|
|
"""
|
|
查询模型端点。
|
|
接收用户请求,启动后台任务处理查询,并返回任务 ID。
|
|
"""
|
|
if model is None or tokenizer is None:
|
|
raise HTTPException(status_code=503, detail="模型未加载,请稍后重试")
|
|
|
|
task_id = str(uuid.uuid4()) # 生成唯一任务 ID
|
|
|
|
# 初始化任务进度
|
|
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"]
|
|
|
|
|
|
# 应用程序入口,使用 Uvicorn 启动服务
|
|
if __name__ == "__main__":
|
|
import uvicorn
|
|
|
|
uvicorn.run(app, host="0.0.0.0", port=8000)
|