app_config.py 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154
  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. debug: bool = False
  66. file_uploads_max_file_size_mb: int = 0
  67. file_uploads_restrict_file_types: bool = False
  68. file_uploads_allowed_extensions: list[str] = field(default_factory=lambda: ['.*'])
  69. runloop_api_key: str | None = None
  70. defaults_dict: ClassVar[dict] = {}
  71. def get_llm_config(self, name='llm') -> LLMConfig:
  72. """'llm' is the name for default config (for backward compatibility prior to 0.8)."""
  73. if name in self.llms:
  74. return self.llms[name]
  75. if name is not None and name != 'llm':
  76. logger.openhands_logger.warning(
  77. f'llm config group {name} not found, using default config'
  78. )
  79. if 'llm' not in self.llms:
  80. self.llms['llm'] = LLMConfig()
  81. return self.llms['llm']
  82. def set_llm_config(self, value: LLMConfig, name='llm') -> None:
  83. self.llms[name] = value
  84. def get_agent_config(self, name='agent') -> AgentConfig:
  85. """'agent' is the name for default config (for backward compatibility prior to 0.8)."""
  86. if name in self.agents:
  87. return self.agents[name]
  88. if 'agent' not in self.agents:
  89. self.agents['agent'] = AgentConfig()
  90. return self.agents['agent']
  91. def set_agent_config(self, value: AgentConfig, name='agent') -> None:
  92. self.agents[name] = value
  93. def get_agent_to_llm_config_map(self) -> dict[str, LLMConfig]:
  94. """Get a map of agent names to llm configs."""
  95. return {name: self.get_llm_config_from_agent(name) for name in self.agents}
  96. def get_llm_config_from_agent(self, name='agent') -> LLMConfig:
  97. agent_config: AgentConfig = self.get_agent_config(name)
  98. llm_config_name = agent_config.llm_config
  99. return self.get_llm_config(llm_config_name)
  100. def get_agent_configs(self) -> dict[str, AgentConfig]:
  101. return self.agents
  102. def __post_init__(self):
  103. """Post-initialization hook, called when the instance is created with only default values."""
  104. AppConfig.defaults_dict = self.defaults_to_dict()
  105. def defaults_to_dict(self) -> dict:
  106. """Serialize fields to a dict for the frontend, including type hints, defaults, and whether it's optional."""
  107. result = {}
  108. for f in fields(self):
  109. field_value = getattr(self, f.name)
  110. # dataclasses compute their defaults themselves
  111. if is_dataclass(type(field_value)):
  112. result[f.name] = field_value.defaults_to_dict()
  113. else:
  114. result[f.name] = get_field_info(f)
  115. return result
  116. def __str__(self):
  117. attr_str = []
  118. for f in fields(self):
  119. attr_name = f.name
  120. attr_value = getattr(self, f.name)
  121. if attr_name in [
  122. 'e2b_api_key',
  123. 'github_token',
  124. 'jwt_secret',
  125. 'modal_api_token_id',
  126. 'modal_api_token_secret',
  127. 'runloop_api_key',
  128. ]:
  129. attr_value = '******' if attr_value else None
  130. attr_str.append(f'{attr_name}={repr(attr_value)}')
  131. return f"AppConfig({', '.join(attr_str)}"
  132. def __repr__(self):
  133. return self.__str__()