lifespan_manager.py 1.0 KB

1234567891011121314151617181920212223242526272829
  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. @asynccontextmanager
  7. async def lifespan(app: FastAPI):
  8. """应用生命周期管理"""
  9. try:
  10. # 启动时检查注册状态,但不阻止启动
  11. registration_status = await registration_manager.check_registration()
  12. if not registration_status:
  13. chat_logger.warning("⚠️ 服务启动:注册检查未通过,/chat接口将受限")
  14. else:
  15. chat_logger.info("✅ 服务启动:注册检查通过")
  16. await agent_manager.initialize()
  17. chat_logger.info("🚀🚀 AI助手服务启动")
  18. yield
  19. finally:
  20. cleared_count = await agent_manager.shutdown()
  21. chat_logger.info(f"🛑🛑🛑 AI助手服务停止,清理了 {cleared_count} 个Agent实例")
  22. def create_lifespan():
  23. """创建生命周期管理器"""
  24. return lifespan