lifespan_manager.py 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738
  1. from contextlib import asynccontextmanager
  2. from fastapi import FastAPI
  3. from core.agent_manager import agent_manager
  4. from utils.registration_manager import registration_manager
  5. from utils.logger import chat_logger
  6. from core.chat_result_manager import chat_result_manager
  7. from core.worker_manager import init_worker_cache
  8. @asynccontextmanager
  9. async def lifespan(app: FastAPI):
  10. """应用生命周期管理"""
  11. try:
  12. # 启动时检查注册状态,但不阻止启动
  13. registration_status = await registration_manager.check_registration()
  14. if not registration_status:
  15. chat_logger.warning("服务启动:注册检查未通过,/chat接口将受限")
  16. else:
  17. chat_logger.info("服务启动:注册检查通过")
  18. await agent_manager.initialize()
  19. # 初始化Worker缓存
  20. init_worker_cache()
  21. chat_logger.info("AI助手服务启动")
  22. yield
  23. finally:
  24. cleared_count = await agent_manager.shutdown()
  25. # 清理聊天结果管理器
  26. chat_result_manager.close()
  27. chat_result_manager.cleanup_old_tasks(max_days=7)
  28. chat_logger.info(f"AI助手服务停止")
  29. def create_lifespan():
  30. """创建生命周期管理器"""
  31. return lifespan