main.py 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. """
  2. FastAPI 应用入口 - 英语句子扩写智能体
  3. """
  4. from fastapi import FastAPI, Request
  5. from fastapi.middleware.cors import CORSMiddleware
  6. from fastapi.responses import JSONResponse
  7. import sys
  8. import os
  9. # 添加当前目录(backend)到 Python 路径
  10. sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
  11. from routers.expand import router as expand_router
  12. # 创建 FastAPI 应用
  13. app = FastAPI(
  14. title="英语句子扩写智能体 API",
  15. description="基于多智能体协作的英语写作教练应用",
  16. version="1.0.0"
  17. )
  18. # 配置 CORS
  19. app.add_middleware(
  20. CORSMiddleware,
  21. allow_origins=["*"], # 允许所有来源(开发环境)
  22. allow_credentials=True,
  23. allow_methods=["*"], # 允许所有 HTTP 方法
  24. allow_headers=["*"], # 允许所有请求头
  25. )
  26. # 包含路由
  27. app.include_router(expand_router)
  28. # 统一异常处理
  29. @app.exception_handler(Exception)
  30. async def global_exception_handler(request: Request, exc: Exception):
  31. """全局异常处理器"""
  32. return JSONResponse(
  33. status_code=500,
  34. content={
  35. "detail": str(exc),
  36. "type": type(exc).__name__
  37. }
  38. )
  39. # 根路径
  40. @app.get("/")
  41. async def root():
  42. """根路径"""
  43. return {
  44. "message": "英语句子扩写智能体 API",
  45. "version": "1.0.0",
  46. "docs": "/docs"
  47. }
  48. # 健康检查
  49. @app.get("/health")
  50. async def health_check():
  51. """健康检查"""
  52. return {"status": "ok"}
  53. if __name__ == "__main__":
  54. import uvicorn
  55. uvicorn.run(app, host="0.0.0.0", port=8000)