app_config.py 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157
  1. import uuid
  2. from dataclasses import dataclass, field, fields, is_dataclass
  3. from typing import ClassVar
  4. from openhands.core import logger
  5. from openhands.core.config.agent_config import AgentConfig
  6. from openhands.core.config.config_utils import (
  7. OH_DEFAULT_AGENT,
  8. OH_MAX_ITERATIONS,
  9. get_field_info,
  10. )
  11. from openhands.core.config.llm_config import LLMConfig
  12. from openhands.core.config.sandbox_config import SandboxConfig
  13. from openhands.core.config.security_config import SecurityConfig
  14. @dataclass
  15. class AppConfig:
  16. """Configuration for the app.
  17. Attributes:
  18. llms: Dictionary mapping LLM names to their configurations.
  19. The default configuration is stored under the 'llm' key.
  20. agents: Dictionary mapping agent names to their configurations.
  21. The default configuration is stored under the 'agent' key.
  22. default_agent: Name of the default agent to use.
  23. sandbox: Sandbox configuration settings.
  24. runtime: Runtime environment identifier.
  25. file_store: Type of file store to use.
  26. file_store_path: Path to the file store.
  27. trajectories_path: Folder path to store trajectories.
  28. workspace_base: Base path for the workspace. Defaults to `./workspace` as absolute path.
  29. workspace_mount_path: Path to mount the workspace. Defaults to `workspace_base`.
  30. workspace_mount_path_in_sandbox: Path to mount the workspace in sandbox. Defaults to `/workspace`.
  31. workspace_mount_rewrite: Path to rewrite the workspace mount path.
  32. cache_dir: Path to cache directory. Defaults to `/tmp/cache`.
  33. run_as_openhands: Whether to run as openhands.
  34. max_iterations: Maximum number of iterations allowed.
  35. max_budget_per_task: Maximum budget per task, agent stops if exceeded.
  36. e2b_api_key: E2B API key.
  37. disable_color: Whether to disable terminal colors. For terminals that don't support color.
  38. debug: Whether to enable debugging mode.
  39. file_uploads_max_file_size_mb: Maximum file upload size in MB. `0` means unlimited.
  40. file_uploads_restrict_file_types: Whether to restrict upload file types.
  41. file_uploads_allowed_extensions: Allowed file extensions. `['.*']` allows all.
  42. """
  43. llms: dict[str, LLMConfig] = field(default_factory=dict)
  44. agents: dict = field(default_factory=dict)
  45. default_agent: str = OH_DEFAULT_AGENT
  46. sandbox: SandboxConfig = field(default_factory=SandboxConfig)
  47. security: SecurityConfig = field(default_factory=SecurityConfig)
  48. runtime: str = 'eventstream'
  49. file_store: str = 'memory'
  50. file_store_path: str = '/tmp/file_store'
  51. trajectories_path: str | None = None
  52. workspace_base: str | None = None
  53. workspace_mount_path: str | None = None
  54. workspace_mount_path_in_sandbox: str = '/workspace'
  55. workspace_mount_rewrite: str | None = None
  56. cache_dir: str = '/tmp/cache'
  57. run_as_openhands: bool = True
  58. max_iterations: int = OH_MAX_ITERATIONS
  59. max_budget_per_task: float | None = None
  60. e2b_api_key: str = ''
  61. modal_api_token_id: str = ''
  62. modal_api_token_secret: str = ''
  63. disable_color: bool = False
  64. jwt_secret: str = uuid.uuid4().hex
  65. attach_session_middleware_class: str = (
  66. 'openhands.server.middleware.AttachSessionMiddleware'
  67. )
  68. debug: bool = False
  69. file_uploads_max_file_size_mb: int = 0
  70. file_uploads_restrict_file_types: bool = False
  71. file_uploads_allowed_extensions: list[str] = field(default_factory=lambda: ['.*'])
  72. runloop_api_key: str | None = None
  73. defaults_dict: ClassVar[dict] = {}
  74. def get_llm_config(self, name='llm') -> LLMConfig:
  75. """'llm' is the name for default config (for backward compatibility prior to 0.8)."""
  76. if name in self.llms:
  77. return self.llms[name]
  78. if name is not None and name != 'llm':
  79. logger.openhands_logger.warning(
  80. f'llm config group {name} not found, using default config'
  81. )
  82. if 'llm' not in self.llms:
  83. self.llms['llm'] = LLMConfig()
  84. return self.llms['llm']
  85. def set_llm_config(self, value: LLMConfig, name='llm') -> None:
  86. self.llms[name] = value
  87. def get_agent_config(self, name='agent') -> AgentConfig:
  88. """'agent' is the name for default config (for backward compatibility prior to 0.8)."""
  89. if name in self.agents:
  90. return self.agents[name]
  91. if 'agent' not in self.agents:
  92. self.agents['agent'] = AgentConfig()
  93. return self.agents['agent']
  94. def set_agent_config(self, value: AgentConfig, name='agent') -> None:
  95. self.agents[name] = value
  96. def get_agent_to_llm_config_map(self) -> dict[str, LLMConfig]:
  97. """Get a map of agent names to llm configs."""
  98. return {name: self.get_llm_config_from_agent(name) for name in self.agents}
  99. def get_llm_config_from_agent(self, name='agent') -> LLMConfig:
  100. agent_config: AgentConfig = self.get_agent_config(name)
  101. llm_config_name = agent_config.llm_config
  102. return self.get_llm_config(llm_config_name)
  103. def get_agent_configs(self) -> dict[str, AgentConfig]:
  104. return self.agents
  105. def __post_init__(self):
  106. """Post-initialization hook, called when the instance is created with only default values."""
  107. AppConfig.defaults_dict = self.defaults_to_dict()
  108. def defaults_to_dict(self) -> dict:
  109. """Serialize fields to a dict for the frontend, including type hints, defaults, and whether it's optional."""
  110. result = {}
  111. for f in fields(self):
  112. field_value = getattr(self, f.name)
  113. # dataclasses compute their defaults themselves
  114. if is_dataclass(type(field_value)):
  115. result[f.name] = field_value.defaults_to_dict()
  116. else:
  117. result[f.name] = get_field_info(f)
  118. return result
  119. def __str__(self):
  120. attr_str = []
  121. for f in fields(self):
  122. attr_name = f.name
  123. attr_value = getattr(self, f.name)
  124. if attr_name in [
  125. 'e2b_api_key',
  126. 'github_token',
  127. 'jwt_secret',
  128. 'modal_api_token_id',
  129. 'modal_api_token_secret',
  130. 'runloop_api_key',
  131. ]:
  132. attr_value = '******' if attr_value else None
  133. attr_str.append(f'{attr_name}={repr(attr_value)}')
  134. return f"AppConfig({', '.join(attr_str)}"
  135. def __repr__(self):
  136. return self.__str__()