添加中文注释

This commit is contained in:
2025-05-23 15:09:01 +08:00
parent 8e968c17cc
commit 34d9353084
3 changed files with 94 additions and 29 deletions
+2
View File
@@ -0,0 +1,2 @@
export VIRTUAL_ENV=.venv
layout python3
+10
View File
@@ -0,0 +1,10 @@
# Python-generated files
__pycache__/
*.py[oc]
build/
dist/
wheels/
*.egg-info
# Virtual environments
.venv
+82 -29
View File
@@ -6,18 +6,25 @@ 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:
# Simulating model loading for now
# Replace with actual model loading logic
# 模拟模型加载逻辑
# 实际情况下,这里可以加载真实的模型和分词器,例如使用 ModelScope 或 PyTorch
# 非模型任务也可以不用加载模型
# from modelscope import AutoModelForCausalLM, AutoTokenizer
# import torch
# model_name = "Qwen/Qwen3-30B-A3B"
@@ -25,53 +32,73 @@ async def load_model_on_startup():
# 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
model = "mock_model" # 模拟模型对象
tokenizer = "mock_tokenizer" # 模拟分词器对象
print("模型加载成功 (模拟)")
return True
except Exception as e:
# 如果加载失败,打印错误信息并将模型和分词器设置为 None
print(f"模型加载失败: {e}")
# Ensure model and tokenizer are None if loading fails
model = None
tokenizer = None
return False
# 使用 asynccontextmanager 定义应用的生命周期管理
@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
"""
定义应用的生命周期管理。
在应用启动时加载模型,在应用关闭时释放资源。
"""
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数"
default=512, ge=1, le=32768, description="最大生成 token 数"
)
enable_thinking: bool = Field(default=True, description="是否启用思考模式")
# 定义响应模型,用于返回查询结果
class QueryResponse(BaseModel):
task_id: str = Field(..., description="任务ID")
"""
查询结果的响应模型。
包含任务 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):
task_id: str = Field(..., description="任务ID")
"""
任务进度的响应模型。
包含任务 ID、状态、进度百分比和状态消息。
"""
task_id: str = Field(..., description="任务 ID")
status: str = Field(
..., description="任务状态: pending, processing, completed, failed"
)
@@ -79,15 +106,25 @@ class UploadProgressResponse(BaseModel):
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,
@@ -95,17 +132,21 @@ async def health_check():
)
# 后台任务函数,用于处理查询请求
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
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,
@@ -115,13 +156,17 @@ async def process_query_task(task_id: str, request: QueryRequest):
)
# 查询模型的端点,接收用户请求并启动后台任务
@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())
task_id = str(uuid.uuid4()) # 生成唯一任务 ID
# 初始化任务进度
upload_progress[task_id] = {
@@ -136,11 +181,15 @@ async def query_model(request: QueryRequest, background_tasks: BackgroundTasks):
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不存在")
raise HTTPException(status_code=404, detail="任务 ID 不存在")
progress_data = upload_progress[task_id]
@@ -151,19 +200,22 @@ async def get_upload_progress(task_id: str):
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不存在")
raise HTTPException(status_code=404, detail="任务 ID 不存在")
progress_data = upload_progress[task_id]
@@ -178,6 +230,7 @@ async def get_query_result(task_id: str):
return progress_data["result"]
# 应用程序入口,使用 Uvicorn 启动服务
if __name__ == "__main__":
import uvicorn