split for some files

This commit is contained in:
2025-05-25 14:16:56 +08:00
parent 34d9353084
commit 98fe64748a
3 changed files with 213 additions and 104 deletions
+101
View File
@@ -0,0 +1,101 @@
from typing import Any, Dict
class GlobalContext:
"""
模型管理器类,负责管理模型状态和任务进度。
使用依赖注入替代全局变量,提供更好的代码结构和可测试性。
"""
def __init__(self):
self.model = None
self.tokenizer = None
self.upload_progress: Dict[str, Dict[str, Any]] = {}
async def load_model(self) -> bool:
"""
异步加载机器学习模型。
在应用启动时调用,用于初始化模型和分词器。
"""
try:
# 模拟模型加载逻辑
# 实际情况下,这里可以加载真实的模型和分词器,例如使用 ModelScope 或 PyTorch
# 非模型任务也可以不用加载模型
# from modelscope import AutoModelForCausalLM, AutoTokenizer
# import torch
# model_name = "Qwen/Qwen3-30B-A3B"
# self.tokenizer = AutoTokenizer.from_pretrained(model_name)
# self.model = AutoModelForCausalLM.from_pretrained(
# model_name, torch_dtype="auto", device_map="auto"
# )
self.model = "mock_model" # 模拟模型对象
self.tokenizer = "mock_tokenizer" # 模拟分词器对象
print("模型加载成功 (模拟)")
return True
except Exception as e:
# 如果加载失败,打印错误信息并将模型和分词器设置为 None
print(f"模型加载失败: {e}")
self.model = None
self.tokenizer = None
return False
def unload_model(self):
"""
卸载模型并释放资源。
"""
self.model = None
self.tokenizer = None
print("模型已卸载 (模拟)")
def is_model_loaded(self) -> bool:
"""
检查模型是否已加载。
"""
return self.model is not None and self.tokenizer is not None
def create_task(self, task_id: str):
"""
创建新任务并初始化进度。
"""
self.upload_progress[task_id] = {
"status": "pending",
"progress": 0.0,
"message": "任务已创建",
}
def update_task_progress(
self, task_id: str, progress: float, message: str | None = None
):
"""
更新任务进度。
"""
if task_id in self.upload_progress:
self.upload_progress[task_id]["progress"] = progress
if message:
self.upload_progress[task_id]["message"] = message
def set_task_status(self, task_id: str, status: str):
"""
设置任务状态。
"""
if task_id in self.upload_progress:
self.upload_progress[task_id]["status"] = status
def set_task_result(self, task_id: str, result: Any):
"""
设置任务结果。
"""
if task_id in self.upload_progress:
self.upload_progress[task_id]["result"] = result
def get_task_progress(self, task_id: str) -> Dict[str, Any]:
"""
获取任务进度数据。
"""
return self.upload_progress.get(task_id) # type: ignore
def task_exists(self, task_id: str) -> bool:
"""
检查任务是否存在。
"""
return task_id in self.upload_progress
+44 -104
View File
@@ -1,47 +1,27 @@
import asyncio
import uuid import uuid
from contextlib import asynccontextmanager from contextlib import asynccontextmanager
from datetime import datetime from datetime import datetime
from fastapi import BackgroundTasks, FastAPI, HTTPException from fastapi import BackgroundTasks, Depends, FastAPI, HTTPException
from pydantic import BaseModel, Field from pydantic import BaseModel, Field
# 全局变量存储模型和任务进度 from global_context import GlobalContext
# model 和 tokenizer 用于存储加载的机器学习模型和分词器 from query_parameter import QueryRequest, QueryResponse, process_query_task
# upload_progress 是一个字典,用于跟踪每个任务的状态和进度
model = None # Singleton instance holder
tokenizer = None _global_context_instance = None
upload_progress: dict[str, dict] = {}
# 异步加载模型的函数 def get_global_context_instance() -> GlobalContext:
async def load_model_on_startup():
""" """
异步加载机器学习模型。 Factory function to get singleton GlobalContext instance.
在应用启动时调用,用于初始化模型和分词器。 如果实例不存在,则创建一个新的实例。
如果实例已存在,则返回现有实例。
""" """
global model, tokenizer global _global_context_instance
try: if _global_context_instance is None:
# 模拟模型加载逻辑 _global_context_instance = GlobalContext()
# 实际情况下,这里可以加载真实的模型和分词器,例如使用 ModelScope 或 PyTorch return _global_context_instance
# 非模型任务也可以不用加载模型
# 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 定义应用的生命周期管理
@@ -51,44 +31,24 @@ async def lifespan(_app: FastAPI):
定义应用的生命周期管理。 定义应用的生命周期管理。
在应用启动时加载模型,在应用关闭时释放资源。 在应用启动时加载模型,在应用关闭时释放资源。
""" """
await load_model_on_startup() # 加载模型 manager = get_global_context_instance()
await manager.load_model() # 加载模型
yield # 暂停,等待应用运行 yield # 暂停,等待应用运行
# 应用关闭时清理模型资源 # 应用关闭时清理模型资源
global model, tokenizer manager.unload_model()
model = None
tokenizer = None
print("模型已卸载 (模拟)")
# 创建 FastAPI 应用实例,并设置生命周期管理 # 创建 FastAPI 应用实例,并设置生命周期管理
app = FastAPI(title="LLM Query API", version="1.0.0", lifespan=lifespan) app = FastAPI(title="LLM Query API", version="1.0.0", lifespan=lifespan)
# 定义请求模型,用于接收用户的查询请求 # 依赖注入函数,用于获取模型管理器实例
class QueryRequest(BaseModel): def get_model_manager() -> GlobalContext:
""" """
用户查询请求的数据模型。 依赖注入函数,返回模型管理器实例。
包含提示词、最大生成 token 数量和是否启用思考模式。 这种方式便于测试和管理依赖关系。
""" """
return get_global_context_instance()
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="响应时间")
# 定义任务进度的响应模型 # 定义任务进度的响应模型
@@ -120,78 +80,56 @@ class HealthResponse(BaseModel):
# 健康检查端点,用于检查服务和模型的状态 # 健康检查端点,用于检查服务和模型的状态
@app.get("/health", response_model=HealthResponse) @app.get("/health", response_model=HealthResponse)
async def health_check(): async def health_check(manager: GlobalContext = Depends(get_model_manager)):
""" """
健康检查端点。 健康检查端点。
返回服务状态和模型加载状态。 返回服务状态和模型加载状态。
""" """
return HealthResponse( return HealthResponse(
status="healthy" if model is not None else "unhealthy", status="healthy" if manager.is_model_loaded() else "unhealthy",
model_loaded=model is not None, model_loaded=manager.is_model_loaded(),
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(), timestamp=datetime.now(),
) )
# 查询模型的端点,接收用户请求并启动后台任务 # 查询模型的端点,接收用户请求并启动后台任务
@app.post("/query", response_model=dict[str, str]) @app.post("/query", response_model=dict[str, str])
async def query_model(request: QueryRequest, background_tasks: BackgroundTasks): async def query_model(
request: QueryRequest,
background_tasks: BackgroundTasks,
manager: GlobalContext = Depends(get_model_manager),
):
""" """
查询模型端点。 查询模型端点。
接收用户请求,启动后台任务处理查询,并返回任务 ID。 接收用户请求,启动后台任务处理查询,并返回任务 ID。
""" """
if model is None or tokenizer is None: if not manager.is_model_loaded():
raise HTTPException(status_code=503, detail="模型未加载,请稍后重试") raise HTTPException(status_code=503, detail="模型未加载,请稍后重试")
task_id = str(uuid.uuid4()) # 生成唯一任务 ID task_id = str(uuid.uuid4()) # 生成唯一任务 ID
# 初始化任务进度 # 初始化任务进度
upload_progress[task_id] = { manager.create_task(task_id)
"status": "pending",
"progress": 0.0,
"message": "任务已创建",
}
# 添加后台任务 # 添加后台任务,传递 manager 实例
background_tasks.add_task(process_query_task, task_id, request) background_tasks.add_task(process_query_task, task_id, request, manager)
return {"task_id": task_id, "message": "查询任务已提交"} return {"task_id": task_id, "message": "查询任务已提交"}
# 获取任务进度的端点 # 获取任务进度的端点
@app.get("/upload_progress/{task_id}", response_model=UploadProgressResponse) @app.get("/upload_progress/{task_id}", response_model=UploadProgressResponse)
async def get_upload_progress(task_id: str): async def get_upload_progress(
task_id: str, manager: GlobalContext = Depends(get_model_manager)
):
""" """
获取任务进度端点。 获取任务进度端点。
返回指定任务的状态和进度信息。 返回指定任务的状态和进度信息。
""" """
if task_id not in upload_progress: if not manager.task_exists(task_id):
raise HTTPException(status_code=404, detail="任务 ID 不存在") raise HTTPException(status_code=404, detail="任务 ID 不存在")
progress_data = upload_progress[task_id] progress_data = manager.get_task_progress(task_id)
response = UploadProgressResponse( response = UploadProgressResponse(
task_id=task_id, task_id=task_id,
@@ -209,15 +147,17 @@ async def get_upload_progress(task_id: str):
# 获取查询结果的端点 # 获取查询结果的端点
@app.get("/query_result/{task_id}", response_model=QueryResponse) @app.get("/query_result/{task_id}", response_model=QueryResponse)
async def get_query_result(task_id: str): async def get_query_result(
task_id: str, manager: GlobalContext = Depends(get_model_manager)
):
""" """
获取查询结果端点。 获取查询结果端点。
返回指定任务的最终结果。 返回指定任务的最终结果。
""" """
if task_id not in upload_progress: if not manager.task_exists(task_id):
raise HTTPException(status_code=404, detail="任务 ID 不存在") raise HTTPException(status_code=404, detail="任务 ID 不存在")
progress_data = upload_progress[task_id] progress_data = manager.get_task_progress(task_id)
if progress_data["status"] != "completed": if progress_data["status"] != "completed":
raise HTTPException( raise HTTPException(
+68
View File
@@ -0,0 +1,68 @@
import asyncio
from datetime import datetime
from pydantic import BaseModel, Field
from global_context import GlobalContext
# 定义请求模型,用于接收用户的查询请求
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="响应时间")
async def process_query_task(
task_id: str, request: QueryRequest, manager: GlobalContext
):
"""
后台处理查询任务。
模拟处理过程并更新任务进度。
"""
manager.set_task_status(task_id, "processing")
for i in range(10):
await asyncio.sleep(10) # 模拟处理时间
progress = (i + 1) * 10.0
manager.update_task_progress(
task_id,
progress,
f"处理进度: {progress}%",
)
# os.system("python detect.py")
# with open(".....json", "r") as f:
# data = f.read()
# res = json.loads(f)
# 任务完成后,更新状态并存储结果
manager.set_task_status(task_id, "completed")
result = QueryResponse(
task_id=task_id,
thinking_content="思考中...",
content=f"模型回复: {request.prompt}",
timestamp=datetime.now(),
)
manager.set_task_result(task_id, result)