| 123456789101112131415161718192021222324252627282930313233 |
- from contextlib import asynccontextmanager
- from fastapi import FastAPI
- from core.agent_manager import agent_manager
- from utils.registration_manager import registration_manager
- from utils.logger import chat_logger
- from core.chat_result_manager import chat_result_manager
- @asynccontextmanager
- async def lifespan(app: FastAPI):
- """应用生命周期管理"""
- try:
- # 启动时检查注册状态,但不阻止启动
- registration_status = await registration_manager.check_registration()
- if not registration_status:
- chat_logger.warning("服务启动:注册检查未通过,/chat接口将受限")
- else:
- chat_logger.info("服务启动:注册检查通过")
- await agent_manager.initialize()
- chat_logger.info("AI助手服务启动")
- yield
- finally:
- cleared_count = await agent_manager.shutdown()
- # 清理聊天结果管理器
- chat_result_manager.close()
- chat_result_manager.cleanup_old_tasks(max_days=7)
- chat_logger.info(f"AI助手服务停止")
- def create_lifespan():
- """创建生命周期管理器"""
- return lifespan
|