main.py 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. """
  2. 文献启明星 API 服务器
  3. FastAPI应用程序入口
  4. """
  5. import logging
  6. import uvicorn
  7. from fastapi import FastAPI, HTTPException
  8. from fastapi.middleware.cors import CORSMiddleware
  9. from pathlib import Path
  10. import sys
  11. import os
  12. # 添加项目根目录到Python路径
  13. sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
  14. from backend.api import research, chat, auth, users, chat_history, research_history
  15. from backend.config import CORS_ORIGINS, BASE_DIR
  16. from backend.core.models import Base
  17. from backend.core.database import engine
  18. # 创建数据库表
  19. Base.metadata.create_all(bind=engine)
  20. # 配置日志
  21. logging.basicConfig(
  22. level=logging.INFO,
  23. format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
  24. handlers=[
  25. logging.StreamHandler(),
  26. logging.FileHandler(Path(BASE_DIR) / "lightstar_api.log")
  27. ]
  28. )
  29. logger = logging.getLogger(__name__)
  30. # 创建FastAPI应用
  31. app = FastAPI(
  32. title="LightStar API",
  33. description="文献启明星 - 科研调研智能体API服务",
  34. version="0.1.0",
  35. docs_url=None, # 禁用Swagger UI
  36. redoc_url=None # 禁用ReDoc
  37. )
  38. # 配置CORS - 使用 config.py 中的设置
  39. app.add_middleware(
  40. CORSMiddleware,
  41. allow_origins=CORS_ORIGINS, # 使用配置文件中定义的域名列表
  42. allow_credentials=True,
  43. allow_methods=["*"],
  44. allow_headers=["*"],
  45. )
  46. # 注册路由
  47. app.include_router(research.router, prefix="/api")
  48. app.include_router(chat.router, prefix="/api")
  49. app.include_router(auth.router, prefix="/api")
  50. app.include_router(users.router, prefix="/api")
  51. app.include_router(chat_history.router, prefix="/api")
  52. app.include_router(research_history.router, prefix="/api")
  53. # 健康检查端点
  54. @app.get("/health")
  55. async def health_check():
  56. return {"status": "healthy", "version": "0.1.0"}
  57. # API信息端点
  58. @app.get("/")
  59. async def root():
  60. return {
  61. "name": "LightStar API",
  62. "description": "文献启明星 - 科研调研智能体API服务",
  63. "version": "0.1.0",
  64. "endpoints": [
  65. "/api/auth/token",
  66. "/api/auth/register",
  67. "/api/users/profile",
  68. "/api/chat-history",
  69. "/api/research-history",
  70. "/api/research/process",
  71. "/api/chat/send-message"
  72. ]
  73. }
  74. # 启动服务器
  75. if __name__ == "__main__":
  76. logger.info("Starting LightStar API server")
  77. # 使用模块的绝对路径确保可以从任何目录启动
  78. uvicorn.run("backend.main:app", host="0.0.0.0", port=8000, reload=True)