app.py 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. import warnings
  2. from contextlib import asynccontextmanager
  3. with warnings.catch_warnings():
  4. warnings.simplefilter('ignore')
  5. from fastapi import (
  6. FastAPI,
  7. )
  8. import openhands.agenthub # noqa F401 (we import this to get the agents registered)
  9. from openhands.server.middleware import (
  10. AttachSessionMiddleware,
  11. InMemoryRateLimiter,
  12. LocalhostCORSMiddleware,
  13. NoCacheMiddleware,
  14. RateLimitMiddleware,
  15. )
  16. from openhands.server.routes.conversation import app as conversation_api_router
  17. from openhands.server.routes.feedback import app as feedback_api_router
  18. from openhands.server.routes.files import app as files_api_router
  19. from openhands.server.routes.github import app as github_api_router
  20. from openhands.server.routes.public import app as public_api_router
  21. from openhands.server.routes.security import app as security_api_router
  22. from openhands.server.routes.settings import app as settings_router
  23. from openhands.server.shared import openhands_config, session_manager
  24. from openhands.utils.import_utils import get_impl
  25. @asynccontextmanager
  26. async def _lifespan(app: FastAPI):
  27. async with session_manager:
  28. yield
  29. app = FastAPI(lifespan=_lifespan)
  30. app.add_middleware(
  31. LocalhostCORSMiddleware,
  32. allow_credentials=True,
  33. allow_methods=['*'],
  34. allow_headers=['*'],
  35. )
  36. app.add_middleware(NoCacheMiddleware)
  37. app.add_middleware(
  38. RateLimitMiddleware, rate_limiter=InMemoryRateLimiter(requests=10, seconds=1)
  39. )
  40. @app.get('/health')
  41. async def health():
  42. return 'OK'
  43. app.include_router(public_api_router)
  44. app.include_router(files_api_router)
  45. app.include_router(conversation_api_router)
  46. app.include_router(security_api_router)
  47. app.include_router(feedback_api_router)
  48. app.include_router(settings_router)
  49. app.include_router(github_api_router)
  50. AttachSessionMiddlewareImpl = get_impl(
  51. AttachSessionMiddleware, openhands_config.attach_session_middleware_path
  52. )
  53. app.middleware('http')(AttachSessionMiddlewareImpl(app, target_router=files_api_router))
  54. app.middleware('http')(
  55. AttachSessionMiddlewareImpl(app, target_router=conversation_api_router)
  56. )
  57. app.middleware('http')(
  58. AttachSessionMiddlewareImpl(app, target_router=security_api_router)
  59. )
  60. app.middleware('http')(
  61. AttachSessionMiddlewareImpl(app, target_router=feedback_api_router)
  62. )