settings.py 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. from fastapi import APIRouter, Request, status
  2. from fastapi.responses import JSONResponse
  3. from openhands.core.logger import openhands_logger as logger
  4. from openhands.server.settings import Settings
  5. from openhands.server.shared import config, openhands_config
  6. from openhands.storage.conversation.conversation_store import ConversationStore
  7. from openhands.storage.settings.settings_store import SettingsStore
  8. from openhands.utils.import_utils import get_impl
  9. app = APIRouter(prefix='/api')
  10. SettingsStoreImpl = get_impl(SettingsStore, openhands_config.settings_store_class) # type: ignore
  11. ConversationStoreImpl = get_impl(
  12. ConversationStore, openhands_config.conversation_store_class # type: ignore
  13. )
  14. @app.get('/settings')
  15. async def load_settings(
  16. request: Request,
  17. ) -> Settings | None:
  18. github_token = ''
  19. if hasattr(request.state, 'github_token'):
  20. github_token = request.state.github_token
  21. try:
  22. settings_store = await SettingsStoreImpl.get_instance(config, github_token)
  23. settings = await settings_store.load()
  24. if settings:
  25. # For security reasons we don't ever send the api key to the client
  26. settings.llm_api_key = None
  27. return settings
  28. except Exception as e:
  29. logger.warning(f'Invalid token: {e}')
  30. return JSONResponse(
  31. status_code=status.HTTP_401_UNAUTHORIZED,
  32. content={'error': 'Invalid token'},
  33. )
  34. @app.post('/settings')
  35. async def store_settings(
  36. request: Request,
  37. settings: Settings,
  38. ) -> JSONResponse:
  39. github_token = ''
  40. if hasattr(request.state, 'github_token'):
  41. github_token = request.state.github_token
  42. try:
  43. settings_store = await SettingsStoreImpl.get_instance(config, github_token)
  44. existing_settings = await settings_store.load()
  45. if existing_settings:
  46. settings = Settings(**{**existing_settings.__dict__, **settings.__dict__})
  47. if settings.llm_api_key is None:
  48. settings.llm_api_key = existing_settings.llm_api_key
  49. await settings_store.store(settings)
  50. return JSONResponse(
  51. status_code=status.HTTP_200_OK,
  52. content={'message': 'Settings stored'},
  53. )
  54. except Exception as e:
  55. logger.warning(f'Invalid token: {e}')
  56. return JSONResponse(
  57. status_code=status.HTTP_401_UNAUTHORIZED,
  58. content={'error': 'Invalid token'},
  59. )