main.py 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164
  1. """
  2. InnoCore API 主应用
  3. """
  4. from fastapi import FastAPI, HTTPException, Depends, BackgroundTasks
  5. from fastapi.middleware.cors import CORSMiddleware
  6. from fastapi.responses import JSONResponse
  7. from contextlib import asynccontextmanager
  8. import logging
  9. import uvicorn
  10. from core.config import get_config
  11. from core.database import db_manager
  12. from core.vector_store import vector_store_manager
  13. from agents.controller import agent_controller
  14. from .routes import papers, users, tasks, analysis, writing, citations, workflow
  15. # 配置日志
  16. logging.basicConfig(level=logging.INFO)
  17. logger = logging.getLogger(__name__)
  18. @asynccontextmanager
  19. async def lifespan(app: FastAPI):
  20. """应用生命周期管理"""
  21. # 启动时初始化
  22. logger.info("正在启动InnoCore AI...")
  23. # 初始化数据库(可选)
  24. try:
  25. await db_manager.initialize()
  26. logger.info("数据库初始化完成")
  27. except Exception as e:
  28. logger.warning(f"数据库初始化失败(将以无数据库模式运行): {str(e)}")
  29. # 初始化向量存储(可选)
  30. try:
  31. await vector_store_manager.initialize()
  32. logger.info("向量存储初始化完成")
  33. except Exception as e:
  34. logger.warning(f"向量存储初始化失败(将以无向量存储模式运行): {str(e)}")
  35. # 初始化智能体控制器(可选)
  36. try:
  37. await agent_controller.initialize()
  38. logger.info("智能体控制器初始化完成")
  39. # 启动任务处理器
  40. import asyncio
  41. asyncio.create_task(agent_controller.start_task_processor())
  42. logger.info("任务处理器已启动")
  43. except Exception as e:
  44. logger.warning(f"智能体控制器初始化失败: {str(e)}")
  45. logger.info("InnoCore AI 启动完成")
  46. yield
  47. # 关闭时清理
  48. logger.info("正在关闭InnoCore AI...")
  49. await agent_controller.shutdown()
  50. await db_manager.close()
  51. await vector_store_manager.close()
  52. logger.info("InnoCore AI已关闭")
  53. # 创建FastAPI应用
  54. app = FastAPI(
  55. title="InnoCore AI API",
  56. description="智能科研创新助手API",
  57. version="0.1.0",
  58. lifespan=lifespan
  59. )
  60. # 配置CORS
  61. config = get_config()
  62. app.add_middleware(
  63. CORSMiddleware,
  64. allow_origins=["*"], # 生产环境应该限制具体域名
  65. allow_credentials=True,
  66. allow_methods=["*"],
  67. allow_headers=["*"],
  68. )
  69. # 注册路由
  70. app.include_router(papers.router, prefix="/api/v1/papers", tags=["papers"])
  71. app.include_router(users.router, prefix="/api/v1/users", tags=["users"])
  72. app.include_router(tasks.router, prefix="/api/v1/tasks", tags=["tasks"])
  73. app.include_router(analysis.router, prefix="/api/v1/analysis", tags=["analysis"])
  74. app.include_router(writing.router, prefix="/api/v1/writing", tags=["writing"])
  75. app.include_router(citations.router, prefix="/api/v1/citations", tags=["citations"])
  76. app.include_router(workflow.router, prefix="/api/v1/workflow", tags=["workflow"])
  77. # 挂载静态文件
  78. from fastapi.staticfiles import StaticFiles
  79. from fastapi.responses import FileResponse
  80. import os
  81. # 获取项目根目录
  82. BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
  83. FRONTEND_DIR = os.path.join(BASE_DIR, "frontend")
  84. # 挂载静态资源
  85. if os.path.exists(os.path.join(FRONTEND_DIR, "static")):
  86. app.mount("/static", StaticFiles(directory=os.path.join(FRONTEND_DIR, "static")), name="static")
  87. # 根路径 - 返回前端页面
  88. @app.get("/")
  89. async def root():
  90. """根路径 - 返回前端首页"""
  91. index_path = os.path.join(FRONTEND_DIR, "index.html")
  92. if os.path.exists(index_path):
  93. return FileResponse(index_path)
  94. return {
  95. "message": "Welcome to InnoCore AI API",
  96. "version": "0.1.0",
  97. "status": "running"
  98. }
  99. # 健康检查
  100. @app.get("/health")
  101. async def health_check():
  102. """健康检查"""
  103. try:
  104. # 检查各组件状态
  105. agent_status = await agent_controller.get_agent_status()
  106. return {
  107. "status": "healthy",
  108. "timestamp": "2024-01-01T00:00:00Z",
  109. "components": {
  110. "database": "connected",
  111. "vector_store": "connected",
  112. "agents": agent_status
  113. }
  114. }
  115. except Exception as e:
  116. return JSONResponse(
  117. status_code=503,
  118. content={
  119. "status": "unhealthy",
  120. "error": str(e)
  121. }
  122. )
  123. # 全局异常处理
  124. @app.exception_handler(Exception)
  125. async def global_exception_handler(request, exc):
  126. """全局异常处理器"""
  127. logger.error(f"全局异常: {str(exc)}")
  128. return JSONResponse(
  129. status_code=500,
  130. content={
  131. "error": "Internal server error",
  132. "message": str(exc) if config.debug else "Something went wrong"
  133. }
  134. )
  135. if __name__ == "__main__":
  136. uvicorn.run(
  137. "innocore_ai.api.main:app",
  138. host="0.0.0.0",
  139. port=8000,
  140. reload=config.debug,
  141. log_level="info"
  142. )