app_config.py 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152
  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: A dictionary of name -> LLM configuration. Default config is under 'llm' key.
  19. agents: A dictionary of name -> Agent configuration. Default config is under 'agent' key.
  20. default_agent: The name of the default agent to use.
  21. sandbox: The sandbox configuration.
  22. runtime: The runtime environment.
  23. file_store: The file store to use.
  24. file_store_path: The path to the file store.
  25. trajectories_path: The folder path to store trajectories.
  26. workspace_base: The base path for the workspace. Defaults to ./workspace as an absolute path.
  27. workspace_mount_path: The path to mount the workspace. This is set to the workspace base by default.
  28. workspace_mount_path_in_sandbox: The path to mount the workspace in the sandbox. Defaults to /workspace.
  29. workspace_mount_rewrite: The path to rewrite the workspace mount path to.
  30. cache_dir: The path to the cache directory. Defaults to /tmp/cache.
  31. run_as_openhands: Whether to run as openhands.
  32. max_iterations: The maximum number of iterations.
  33. max_budget_per_task: The maximum budget allowed per task, beyond which the agent will stop.
  34. e2b_api_key: The E2B API key.
  35. disable_color: Whether to disable color. For terminals that don't support color.
  36. debug: Whether to enable debugging.
  37. file_uploads_max_file_size_mb: Maximum file size for uploads in megabytes. 0 means no limit.
  38. file_uploads_restrict_file_types: Whether to restrict file types for file uploads. Defaults to False.
  39. file_uploads_allowed_extensions: List of allowed file extensions for uploads. ['.*'] means all extensions are allowed.
  40. """
  41. llms: dict[str, LLMConfig] = field(default_factory=dict)
  42. agents: dict = field(default_factory=dict)
  43. default_agent: str = OH_DEFAULT_AGENT
  44. sandbox: SandboxConfig = field(default_factory=SandboxConfig)
  45. security: SecurityConfig = field(default_factory=SecurityConfig)
  46. runtime: str = 'eventstream'
  47. file_store: str = 'memory'
  48. file_store_path: str = '/tmp/file_store'
  49. trajectories_path: str | None = None
  50. workspace_base: str | None = None
  51. workspace_mount_path: str | None = None
  52. workspace_mount_path_in_sandbox: str = '/workspace'
  53. workspace_mount_rewrite: str | None = None
  54. cache_dir: str = '/tmp/cache'
  55. run_as_openhands: bool = True
  56. max_iterations: int = OH_MAX_ITERATIONS
  57. max_budget_per_task: float | None = None
  58. e2b_api_key: str = ''
  59. modal_api_token_id: str = ''
  60. modal_api_token_secret: str = ''
  61. disable_color: bool = False
  62. jwt_secret: str = uuid.uuid4().hex
  63. debug: bool = False
  64. file_uploads_max_file_size_mb: int = 0
  65. file_uploads_restrict_file_types: bool = False
  66. file_uploads_allowed_extensions: list[str] = field(default_factory=lambda: ['.*'])
  67. runloop_api_key: str | None = None
  68. defaults_dict: ClassVar[dict] = {}
  69. def get_llm_config(self, name='llm') -> LLMConfig:
  70. """Llm is the name for default config (for backward compatibility prior to 0.8)"""
  71. if name in self.llms:
  72. return self.llms[name]
  73. if name is not None and name != 'llm':
  74. logger.openhands_logger.warning(
  75. f'llm config group {name} not found, using default config'
  76. )
  77. if 'llm' not in self.llms:
  78. self.llms['llm'] = LLMConfig()
  79. return self.llms['llm']
  80. def set_llm_config(self, value: LLMConfig, name='llm'):
  81. self.llms[name] = value
  82. def get_agent_config(self, name='agent') -> AgentConfig:
  83. """Agent is the name for default config (for backward compability prior to 0.8)"""
  84. if name in self.agents:
  85. return self.agents[name]
  86. if 'agent' not in self.agents:
  87. self.agents['agent'] = AgentConfig()
  88. return self.agents['agent']
  89. def set_agent_config(self, value: AgentConfig, name='agent'):
  90. self.agents[name] = value
  91. def get_agent_to_llm_config_map(self) -> dict[str, LLMConfig]:
  92. """Get a map of agent names to llm configs."""
  93. return {name: self.get_llm_config_from_agent(name) for name in self.agents}
  94. def get_llm_config_from_agent(self, name='agent') -> LLMConfig:
  95. agent_config: AgentConfig = self.get_agent_config(name)
  96. llm_config_name = agent_config.llm_config
  97. return self.get_llm_config(llm_config_name)
  98. def get_agent_configs(self) -> dict[str, AgentConfig]:
  99. return self.agents
  100. def __post_init__(self):
  101. """Post-initialization hook, called when the instance is created with only default values."""
  102. AppConfig.defaults_dict = self.defaults_to_dict()
  103. def defaults_to_dict(self) -> dict:
  104. """Serialize fields to a dict for the frontend, including type hints, defaults, and whether it's optional."""
  105. result = {}
  106. for f in fields(self):
  107. field_value = getattr(self, f.name)
  108. # dataclasses compute their defaults themselves
  109. if is_dataclass(type(field_value)):
  110. result[f.name] = field_value.defaults_to_dict()
  111. else:
  112. result[f.name] = get_field_info(f)
  113. return result
  114. def __str__(self):
  115. attr_str = []
  116. for f in fields(self):
  117. attr_name = f.name
  118. attr_value = getattr(self, f.name)
  119. if attr_name in [
  120. 'e2b_api_key',
  121. 'github_token',
  122. 'jwt_secret',
  123. 'modal_api_token_id',
  124. 'modal_api_token_secret',
  125. 'runloop_api_key',
  126. ]:
  127. attr_value = '******' if attr_value else None
  128. attr_str.append(f'{attr_name}={repr(attr_value)}')
  129. return f"AppConfig({', '.join(attr_str)}"
  130. def __repr__(self):
  131. return self.__str__()