config.py 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774
  1. import argparse
  2. import os
  3. import pathlib
  4. import platform
  5. import uuid
  6. from dataclasses import dataclass, field, fields, is_dataclass
  7. from enum import Enum
  8. from types import UnionType
  9. from typing import Any, ClassVar, MutableMapping, get_args, get_origin
  10. import toml
  11. from dotenv import load_dotenv
  12. from openhands.core import logger
  13. from openhands.core.utils import Singleton
  14. load_dotenv()
  15. LLM_SENSITIVE_FIELDS = ['api_key', 'aws_access_key_id', 'aws_secret_access_key']
  16. _DEFAULT_AGENT = 'CodeActAgent'
  17. _MAX_ITERATIONS = 100
  18. @dataclass
  19. class LLMConfig:
  20. """Configuration for the LLM model.
  21. Attributes:
  22. model: The model to use.
  23. api_key: The API key to use.
  24. base_url: The base URL for the API. This is necessary for local LLMs. It is also used for Azure embeddings.
  25. api_version: The version of the API.
  26. embedding_model: The embedding model to use.
  27. embedding_base_url: The base URL for the embedding API.
  28. embedding_deployment_name: The name of the deployment for the embedding API. This is used for Azure OpenAI.
  29. aws_access_key_id: The AWS access key ID.
  30. aws_secret_access_key: The AWS secret access key.
  31. aws_region_name: The AWS region name.
  32. num_retries: The number of retries to attempt.
  33. retry_multiplier: The multiplier for the exponential backoff.
  34. retry_min_wait: The minimum time to wait between retries, in seconds. This is exponential backoff minimum. For models with very low limits, this can be set to 15-20.
  35. retry_max_wait: The maximum time to wait between retries, in seconds. This is exponential backoff maximum.
  36. timeout: The timeout for the API.
  37. max_message_chars: The approximate max number of characters in the content of an event included in the prompt to the LLM. Larger observations are truncated.
  38. temperature: The temperature for the API.
  39. top_p: The top p for the API.
  40. custom_llm_provider: The custom LLM provider to use. This is undocumented in openhands, and normally not used. It is documented on the litellm side.
  41. max_input_tokens: The maximum number of input tokens. Note that this is currently unused, and the value at runtime is actually the total tokens in OpenAI (e.g. 128,000 tokens for GPT-4).
  42. max_output_tokens: The maximum number of output tokens. This is sent to the LLM.
  43. input_cost_per_token: The cost per input token. This will available in logs for the user to check.
  44. output_cost_per_token: The cost per output token. This will available in logs for the user to check.
  45. ollama_base_url: The base URL for the OLLAMA API.
  46. drop_params: Drop any unmapped (unsupported) params without causing an exception.
  47. """
  48. model: str = 'gpt-4o'
  49. api_key: str | None = None
  50. base_url: str | None = None
  51. api_version: str | None = None
  52. embedding_model: str = 'local'
  53. embedding_base_url: str | None = None
  54. embedding_deployment_name: str | None = None
  55. aws_access_key_id: str | None = None
  56. aws_secret_access_key: str | None = None
  57. aws_region_name: str | None = None
  58. num_retries: int = 10
  59. retry_multiplier: float = 2
  60. retry_min_wait: int = 3
  61. retry_max_wait: int = 300
  62. timeout: int | None = None
  63. max_message_chars: int = 10_000 # maximum number of characters in an observation's content when sent to the llm
  64. temperature: float = 0
  65. top_p: float = 0.5
  66. custom_llm_provider: str | None = None
  67. max_input_tokens: int | None = None
  68. max_output_tokens: int | None = None
  69. input_cost_per_token: float | None = None
  70. output_cost_per_token: float | None = None
  71. ollama_base_url: str | None = None
  72. drop_params: bool | None = None
  73. def defaults_to_dict(self) -> dict:
  74. """Serialize fields to a dict for the frontend, including type hints, defaults, and whether it's optional."""
  75. result = {}
  76. for f in fields(self):
  77. result[f.name] = get_field_info(f)
  78. return result
  79. def __str__(self):
  80. attr_str = []
  81. for f in fields(self):
  82. attr_name = f.name
  83. attr_value = getattr(self, f.name)
  84. if attr_name in LLM_SENSITIVE_FIELDS:
  85. attr_value = '******' if attr_value else None
  86. attr_str.append(f'{attr_name}={repr(attr_value)}')
  87. return f"LLMConfig({', '.join(attr_str)})"
  88. def __repr__(self):
  89. return self.__str__()
  90. def to_safe_dict(self):
  91. """Return a dict with the sensitive fields replaced with ******."""
  92. ret = self.__dict__.copy()
  93. for k, v in ret.items():
  94. if k in LLM_SENSITIVE_FIELDS:
  95. ret[k] = '******' if v else None
  96. return ret
  97. def set_missing_attributes(self):
  98. """Set any missing attributes to their default values."""
  99. for field_name, field_obj in self.__dataclass_fields__.items():
  100. if not hasattr(self, field_name):
  101. setattr(self, field_name, field_obj.default)
  102. @dataclass
  103. class AgentConfig:
  104. """Configuration for the agent.
  105. Attributes:
  106. micro_agent_name: The name of the micro agent to use for this agent.
  107. memory_enabled: Whether long-term memory (embeddings) is enabled.
  108. memory_max_threads: The maximum number of threads indexing at the same time for embeddings.
  109. llm_config: The name of the llm config to use. If specified, this will override global llm config.
  110. """
  111. micro_agent_name: str | None = None
  112. memory_enabled: bool = False
  113. memory_max_threads: int = 2
  114. llm_config: str | None = None
  115. def defaults_to_dict(self) -> dict:
  116. """Serialize fields to a dict for the frontend, including type hints, defaults, and whether it's optional."""
  117. result = {}
  118. for f in fields(self):
  119. result[f.name] = get_field_info(f)
  120. return result
  121. @dataclass
  122. class SecurityConfig(metaclass=Singleton):
  123. """Configuration for security related functionalities.
  124. Attributes:
  125. confirmation_mode: Whether to enable confirmation mode.
  126. security_analyzer: The security analyzer to use.
  127. """
  128. confirmation_mode: bool = False
  129. security_analyzer: str | None = None
  130. def defaults_to_dict(self) -> dict:
  131. """Serialize fields to a dict for the frontend, including type hints, defaults, and whether it's optional."""
  132. dict = {}
  133. for f in fields(self):
  134. dict[f.name] = get_field_info(f)
  135. return dict
  136. def __str__(self):
  137. attr_str = []
  138. for f in fields(self):
  139. attr_name = f.name
  140. attr_value = getattr(self, f.name)
  141. attr_str.append(f'{attr_name}={repr(attr_value)}')
  142. return f"SecurityConfig({', '.join(attr_str)})"
  143. def __repr__(self):
  144. return self.__str__()
  145. @dataclass
  146. class SandboxConfig(metaclass=Singleton):
  147. """Configuration for the sandbox.
  148. Attributes:
  149. api_hostname: The hostname for the EventStream Runtime API.
  150. base_container_image: The base container image from which to build the runtime image.
  151. runtime_container_image: The runtime container image to use.
  152. user_id: The user ID for the sandbox.
  153. timeout: The timeout for the sandbox.
  154. enable_auto_lint: Whether to enable auto-lint.
  155. use_host_network: Whether to use the host network.
  156. initialize_plugins: Whether to initialize plugins.
  157. runtime_extra_deps: The extra dependencies to install in the runtime image (typically used for evaluation).
  158. This will be rendered into the end of the Dockerfile that builds the runtime image.
  159. It can contain any valid shell commands (e.g., pip install numpy).
  160. The path to the interpreter is available as $OD_INTERPRETER_PATH,
  161. which can be used to install dependencies for the OD-specific Python interpreter.
  162. runtime_startup_env_vars: The environment variables to set at the launch of the runtime.
  163. This is a dictionary of key-value pairs.
  164. This is useful for setting environment variables that are needed by the runtime.
  165. For example, for specifying the base url of website for browsergym evaluation.
  166. browsergym_eval_env: The BrowserGym environment to use for evaluation.
  167. Default is None for general purpose browsing. Check evaluation/miniwob and evaluation/webarena for examples.
  168. """
  169. api_hostname: str = 'localhost'
  170. base_container_image: str | None = (
  171. 'nikolaik/python-nodejs:python3.11-nodejs22' # default to nikolaik/python-nodejs:python3.11-nodejs22 for eventstream runtime
  172. )
  173. runtime_container_image: str | None = None
  174. user_id: int = os.getuid() if hasattr(os, 'getuid') else 1000
  175. timeout: int = 120
  176. enable_auto_lint: bool = (
  177. False # once enabled, OpenHands would lint files after editing
  178. )
  179. use_host_network: bool = False
  180. initialize_plugins: bool = True
  181. runtime_extra_deps: str | None = None
  182. runtime_startup_env_vars: dict[str, str] = field(default_factory=dict)
  183. browsergym_eval_env: str | None = None
  184. def defaults_to_dict(self) -> dict:
  185. """Serialize fields to a dict for the frontend, including type hints, defaults, and whether it's optional."""
  186. dict = {}
  187. for f in fields(self):
  188. dict[f.name] = get_field_info(f)
  189. return dict
  190. def __str__(self):
  191. attr_str = []
  192. for f in fields(self):
  193. attr_name = f.name
  194. attr_value = getattr(self, f.name)
  195. attr_str.append(f'{attr_name}={repr(attr_value)}')
  196. return f"SandboxConfig({', '.join(attr_str)})"
  197. def __repr__(self):
  198. return self.__str__()
  199. class UndefinedString(str, Enum):
  200. UNDEFINED = 'UNDEFINED'
  201. @dataclass
  202. class AppConfig(metaclass=Singleton):
  203. """Configuration for the app.
  204. Attributes:
  205. llms: A dictionary of name -> LLM configuration. Default config is under 'llm' key.
  206. agents: A dictionary of name -> Agent configuration. Default config is under 'agent' key.
  207. default_agent: The name of the default agent to use.
  208. sandbox: The sandbox configuration.
  209. runtime: The runtime environment.
  210. file_store: The file store to use.
  211. file_store_path: The path to the file store.
  212. workspace_base: The base path for the workspace. Defaults to ./workspace as an absolute path.
  213. workspace_mount_path: The path to mount the workspace. This is set to the workspace base by default.
  214. workspace_mount_path_in_sandbox: The path to mount the workspace in the sandbox. Defaults to /workspace.
  215. workspace_mount_rewrite: The path to rewrite the workspace mount path to.
  216. cache_dir: The path to the cache directory. Defaults to /tmp/cache.
  217. run_as_openhands: Whether to run as openhands.
  218. max_iterations: The maximum number of iterations.
  219. max_budget_per_task: The maximum budget allowed per task, beyond which the agent will stop.
  220. e2b_api_key: The E2B API key.
  221. disable_color: Whether to disable color. For terminals that don't support color.
  222. debug: Whether to enable debugging.
  223. enable_cli_session: Whether to enable saving and restoring the session when run from CLI.
  224. file_uploads_max_file_size_mb: Maximum file size for uploads in megabytes. 0 means no limit.
  225. file_uploads_restrict_file_types: Whether to restrict file types for file uploads. Defaults to False.
  226. file_uploads_allowed_extensions: List of allowed file extensions for uploads. ['.*'] means all extensions are allowed.
  227. """
  228. llms: dict[str, LLMConfig] = field(default_factory=dict)
  229. agents: dict = field(default_factory=dict)
  230. default_agent: str = _DEFAULT_AGENT
  231. sandbox: SandboxConfig = field(default_factory=SandboxConfig)
  232. security: SecurityConfig = field(default_factory=SecurityConfig)
  233. runtime: str = 'eventstream'
  234. file_store: str = 'memory'
  235. file_store_path: str = '/tmp/file_store'
  236. # TODO: clean up workspace path after the removal of ServerRuntime
  237. workspace_base: str = os.path.join(os.getcwd(), 'workspace')
  238. workspace_mount_path: str | None = (
  239. UndefinedString.UNDEFINED # this path should always be set when config is fully loaded
  240. ) # when set to None, do not mount the workspace
  241. workspace_mount_path_in_sandbox: str = '/workspace'
  242. workspace_mount_rewrite: str | None = None
  243. cache_dir: str = '/tmp/cache'
  244. run_as_openhands: bool = True
  245. max_iterations: int = _MAX_ITERATIONS
  246. max_budget_per_task: float | None = None
  247. e2b_api_key: str = ''
  248. disable_color: bool = False
  249. jwt_secret: str = uuid.uuid4().hex
  250. debug: bool = False
  251. enable_cli_session: bool = False
  252. file_uploads_max_file_size_mb: int = 0
  253. file_uploads_restrict_file_types: bool = False
  254. file_uploads_allowed_extensions: list[str] = field(default_factory=lambda: ['.*'])
  255. defaults_dict: ClassVar[dict] = {}
  256. def get_llm_config(self, name='llm') -> LLMConfig:
  257. """Llm is the name for default config (for backward compatibility prior to 0.8)"""
  258. if name in self.llms:
  259. return self.llms[name]
  260. if name is not None and name != 'llm':
  261. logger.openhands_logger.warning(
  262. f'llm config group {name} not found, using default config'
  263. )
  264. if 'llm' not in self.llms:
  265. self.llms['llm'] = LLMConfig()
  266. return self.llms['llm']
  267. def set_llm_config(self, value: LLMConfig, name='llm'):
  268. self.llms[name] = value
  269. def get_agent_config(self, name='agent') -> AgentConfig:
  270. """Agent is the name for default config (for backward compability prior to 0.8)"""
  271. if name in self.agents:
  272. return self.agents[name]
  273. if 'agent' not in self.agents:
  274. self.agents['agent'] = AgentConfig()
  275. return self.agents['agent']
  276. def set_agent_config(self, value: AgentConfig, name='agent'):
  277. self.agents[name] = value
  278. def get_agent_to_llm_config_map(self) -> dict[str, LLMConfig]:
  279. """Get a map of agent names to llm configs."""
  280. return {name: self.get_llm_config_from_agent(name) for name in self.agents}
  281. def get_llm_config_from_agent(self, name='agent') -> LLMConfig:
  282. agent_config: AgentConfig = self.get_agent_config(name)
  283. llm_config_name = agent_config.llm_config
  284. return self.get_llm_config(llm_config_name)
  285. def get_agent_configs(self) -> dict[str, AgentConfig]:
  286. return self.agents
  287. def __post_init__(self):
  288. """Post-initialization hook, called when the instance is created with only default values."""
  289. AppConfig.defaults_dict = self.defaults_to_dict()
  290. def defaults_to_dict(self) -> dict:
  291. """Serialize fields to a dict for the frontend, including type hints, defaults, and whether it's optional."""
  292. result = {}
  293. for f in fields(self):
  294. field_value = getattr(self, f.name)
  295. # dataclasses compute their defaults themselves
  296. if is_dataclass(type(field_value)):
  297. result[f.name] = field_value.defaults_to_dict()
  298. else:
  299. result[f.name] = get_field_info(f)
  300. return result
  301. def __str__(self):
  302. attr_str = []
  303. for f in fields(self):
  304. attr_name = f.name
  305. attr_value = getattr(self, f.name)
  306. if attr_name in [
  307. 'e2b_api_key',
  308. 'github_token',
  309. 'jwt_secret',
  310. ]:
  311. attr_value = '******' if attr_value else None
  312. attr_str.append(f'{attr_name}={repr(attr_value)}')
  313. return f"AppConfig({', '.join(attr_str)}"
  314. def __repr__(self):
  315. return self.__str__()
  316. def get_field_info(f):
  317. """Extract information about a dataclass field: type, optional, and default.
  318. Args:
  319. f: The field to extract information from.
  320. Returns: A dict with the field's type, whether it's optional, and its default value.
  321. """
  322. field_type = f.type
  323. optional = False
  324. # for types like str | None, find the non-None type and set optional to True
  325. # this is useful for the frontend to know if a field is optional
  326. # and to show the correct type in the UI
  327. # Note: this only works for UnionTypes with None as one of the types
  328. if get_origin(field_type) is UnionType:
  329. types = get_args(field_type)
  330. non_none_arg = next((t for t in types if t is not type(None)), None)
  331. if non_none_arg is not None:
  332. field_type = non_none_arg
  333. optional = True
  334. # type name in a pretty format
  335. type_name = (
  336. field_type.__name__ if hasattr(field_type, '__name__') else str(field_type)
  337. )
  338. # default is always present
  339. default = f.default
  340. # return a schema with the useful info for frontend
  341. return {'type': type_name.lower(), 'optional': optional, 'default': default}
  342. def load_from_env(cfg: AppConfig, env_or_toml_dict: dict | MutableMapping[str, str]):
  343. """Reads the env-style vars and sets config attributes based on env vars or a config.toml dict.
  344. Compatibility with vars like LLM_BASE_URL, AGENT_MEMORY_ENABLED, SANDBOX_TIMEOUT and others.
  345. Args:
  346. cfg: The AppConfig object to set attributes on.
  347. env_or_toml_dict: The environment variables or a config.toml dict.
  348. """
  349. def get_optional_type(union_type: UnionType) -> Any:
  350. """Returns the non-None type from a Union."""
  351. types = get_args(union_type)
  352. return next((t for t in types if t is not type(None)), None)
  353. # helper function to set attributes based on env vars
  354. def set_attr_from_env(sub_config: Any, prefix=''):
  355. """Set attributes of a config dataclass based on environment variables."""
  356. for field_name, field_type in sub_config.__annotations__.items():
  357. # compute the expected env var name from the prefix and field name
  358. # e.g. LLM_BASE_URL
  359. env_var_name = (prefix + field_name).upper()
  360. if is_dataclass(field_type):
  361. # nested dataclass
  362. nested_sub_config = getattr(sub_config, field_name)
  363. set_attr_from_env(nested_sub_config, prefix=field_name + '_')
  364. elif env_var_name in env_or_toml_dict:
  365. # convert the env var to the correct type and set it
  366. value = env_or_toml_dict[env_var_name]
  367. # skip empty config values (fall back to default)
  368. if not value:
  369. continue
  370. try:
  371. # if it's an optional type, get the non-None type
  372. if get_origin(field_type) is UnionType:
  373. field_type = get_optional_type(field_type)
  374. # Attempt to cast the env var to type hinted in the dataclass
  375. if field_type is bool:
  376. cast_value = str(value).lower() in ['true', '1']
  377. else:
  378. cast_value = field_type(value)
  379. setattr(sub_config, field_name, cast_value)
  380. except (ValueError, TypeError):
  381. logger.openhands_logger.error(
  382. f'Error setting env var {env_var_name}={value}: check that the value is of the right type'
  383. )
  384. # Start processing from the root of the config object
  385. set_attr_from_env(cfg)
  386. # load default LLM config from env
  387. default_llm_config = cfg.get_llm_config()
  388. set_attr_from_env(default_llm_config, 'LLM_')
  389. # load default agent config from env
  390. default_agent_config = cfg.get_agent_config()
  391. set_attr_from_env(default_agent_config, 'AGENT_')
  392. def load_from_toml(cfg: AppConfig, toml_file: str = 'config.toml'):
  393. """Load the config from the toml file. Supports both styles of config vars.
  394. Args:
  395. cfg: The AppConfig object to update attributes of.
  396. toml_file: The path to the toml file. Defaults to 'config.toml'.
  397. """
  398. # try to read the config.toml file into the config object
  399. try:
  400. with open(toml_file, 'r', encoding='utf-8') as toml_contents:
  401. toml_config = toml.load(toml_contents)
  402. except FileNotFoundError:
  403. return
  404. except toml.TomlDecodeError as e:
  405. logger.openhands_logger.warning(
  406. f'Cannot parse config from toml, toml values have not been applied.\nError: {e}',
  407. exc_info=False,
  408. )
  409. return
  410. # if there was an exception or core is not in the toml, try to use the old-style toml
  411. if 'core' not in toml_config:
  412. # re-use the env loader to set the config from env-style vars
  413. load_from_env(cfg, toml_config)
  414. return
  415. core_config = toml_config['core']
  416. # load llm configs and agent configs
  417. for key, value in toml_config.items():
  418. if isinstance(value, dict):
  419. try:
  420. if key is not None and key.lower() == 'agent':
  421. logger.openhands_logger.info(
  422. 'Attempt to load default agent config from config toml'
  423. )
  424. non_dict_fields = {
  425. k: v for k, v in value.items() if not isinstance(v, dict)
  426. }
  427. agent_config = AgentConfig(**non_dict_fields)
  428. cfg.set_agent_config(agent_config, 'agent')
  429. for nested_key, nested_value in value.items():
  430. if isinstance(nested_value, dict):
  431. logger.openhands_logger.info(
  432. f'Attempt to load group {nested_key} from config toml as agent config'
  433. )
  434. agent_config = AgentConfig(**nested_value)
  435. cfg.set_agent_config(agent_config, nested_key)
  436. elif key is not None and key.lower() == 'llm':
  437. logger.openhands_logger.info(
  438. 'Attempt to load default LLM config from config toml'
  439. )
  440. non_dict_fields = {
  441. k: v for k, v in value.items() if not isinstance(v, dict)
  442. }
  443. llm_config = LLMConfig(**non_dict_fields)
  444. cfg.set_llm_config(llm_config, 'llm')
  445. for nested_key, nested_value in value.items():
  446. if isinstance(nested_value, dict):
  447. logger.openhands_logger.info(
  448. f'Attempt to load group {nested_key} from config toml as llm config'
  449. )
  450. llm_config = LLMConfig(**nested_value)
  451. cfg.set_llm_config(llm_config, nested_key)
  452. elif not key.startswith('sandbox') and key.lower() != 'core':
  453. logger.openhands_logger.warning(
  454. f'Unknown key in {toml_file}: "{key}"'
  455. )
  456. except (TypeError, KeyError) as e:
  457. logger.openhands_logger.warning(
  458. f'Cannot parse config from toml, toml values have not been applied.\n Error: {e}',
  459. exc_info=False,
  460. )
  461. else:
  462. logger.openhands_logger.warning(f'Unknown key in {toml_file}: "{key}')
  463. try:
  464. # set sandbox config from the toml file
  465. sandbox_config = cfg.sandbox
  466. # migrate old sandbox configs from [core] section to sandbox config
  467. keys_to_migrate = [key for key in core_config if key.startswith('sandbox_')]
  468. for key in keys_to_migrate:
  469. new_key = key.replace('sandbox_', '')
  470. if new_key in sandbox_config.__annotations__:
  471. # read the key in sandbox and remove it from core
  472. setattr(sandbox_config, new_key, core_config.pop(key))
  473. else:
  474. logger.openhands_logger.warning(f'Unknown sandbox config: {key}')
  475. # the new style values override the old style values
  476. if 'sandbox' in toml_config:
  477. sandbox_config = SandboxConfig(**toml_config['sandbox'])
  478. # update the config object with the new values
  479. AppConfig(sandbox=sandbox_config, **core_config)
  480. except (TypeError, KeyError) as e:
  481. logger.openhands_logger.warning(
  482. f'Cannot parse config from toml, toml values have not been applied.\nError: {e}',
  483. exc_info=False,
  484. )
  485. def finalize_config(cfg: AppConfig):
  486. """More tweaks to the config after it's been loaded."""
  487. # Set workspace_mount_path if not set by the user
  488. if cfg.workspace_mount_path is UndefinedString.UNDEFINED:
  489. cfg.workspace_mount_path = os.path.abspath(cfg.workspace_base)
  490. cfg.workspace_base = os.path.abspath(cfg.workspace_base)
  491. if cfg.workspace_mount_rewrite: # and not config.workspace_mount_path:
  492. # TODO why do we need to check if workspace_mount_path is None?
  493. base = cfg.workspace_base or os.getcwd()
  494. parts = cfg.workspace_mount_rewrite.split(':')
  495. cfg.workspace_mount_path = base.replace(parts[0], parts[1])
  496. for llm in cfg.llms.values():
  497. if llm.embedding_base_url is None:
  498. llm.embedding_base_url = llm.base_url
  499. if cfg.sandbox.use_host_network and platform.system() == 'Darwin':
  500. logger.openhands_logger.warning(
  501. 'Please upgrade to Docker Desktop 4.29.0 or later to use host network mode on macOS. '
  502. 'See https://github.com/docker/roadmap/issues/238#issuecomment-2044688144 for more information.'
  503. )
  504. # make sure cache dir exists
  505. if cfg.cache_dir:
  506. pathlib.Path(cfg.cache_dir).mkdir(parents=True, exist_ok=True)
  507. # Utility function for command line --group argument
  508. def get_llm_config_arg(
  509. llm_config_arg: str, toml_file: str = 'config.toml'
  510. ) -> LLMConfig | None:
  511. """Get a group of llm settings from the config file.
  512. A group in config.toml can look like this:
  513. ```
  514. [llm.gpt-3.5-for-eval]
  515. model = 'gpt-3.5-turbo'
  516. api_key = '...'
  517. temperature = 0.5
  518. num_retries = 10
  519. ...
  520. ```
  521. The user-defined group name, like "gpt-3.5-for-eval", is the argument to this function. The function will load the LLMConfig object
  522. with the settings of this group, from the config file, and set it as the LLMConfig object for the app.
  523. Note that the group must be under "llm" group, or in other words, the group name must start with "llm.".
  524. Args:
  525. llm_config_arg: The group of llm settings to get from the config.toml file.
  526. Returns:
  527. LLMConfig: The LLMConfig object with the settings from the config file.
  528. """
  529. # keep only the name, just in case
  530. llm_config_arg = llm_config_arg.strip('[]')
  531. # truncate the prefix, just in case
  532. if llm_config_arg.startswith('llm.'):
  533. llm_config_arg = llm_config_arg[4:]
  534. logger.openhands_logger.info(f'Loading llm config from {llm_config_arg}')
  535. # load the toml file
  536. try:
  537. with open(toml_file, 'r', encoding='utf-8') as toml_contents:
  538. toml_config = toml.load(toml_contents)
  539. except FileNotFoundError as e:
  540. logger.openhands_logger.error(f'Config file not found: {e}')
  541. return None
  542. except toml.TomlDecodeError as e:
  543. logger.openhands_logger.error(
  544. f'Cannot parse llm group from {llm_config_arg}. Exception: {e}'
  545. )
  546. return None
  547. # update the llm config with the specified section
  548. if 'llm' in toml_config and llm_config_arg in toml_config['llm']:
  549. return LLMConfig(**toml_config['llm'][llm_config_arg])
  550. logger.openhands_logger.debug(f'Loading from toml failed for {llm_config_arg}')
  551. return None
  552. # Command line arguments
  553. def get_parser() -> argparse.ArgumentParser:
  554. """Get the parser for the command line arguments."""
  555. parser = argparse.ArgumentParser(description='Run an agent with a specific task')
  556. parser.add_argument(
  557. '-d',
  558. '--directory',
  559. type=str,
  560. help='The working directory for the agent',
  561. )
  562. parser.add_argument(
  563. '-t',
  564. '--task',
  565. type=str,
  566. default='',
  567. help='The task for the agent to perform',
  568. )
  569. parser.add_argument(
  570. '-f',
  571. '--file',
  572. type=str,
  573. help='Path to a file containing the task. Overrides -t if both are provided.',
  574. )
  575. parser.add_argument(
  576. '-c',
  577. '--agent-cls',
  578. default=_DEFAULT_AGENT,
  579. type=str,
  580. help='Name of the default agent to use',
  581. )
  582. parser.add_argument(
  583. '-i',
  584. '--max-iterations',
  585. default=_MAX_ITERATIONS,
  586. type=int,
  587. help='The maximum number of iterations to run the agent',
  588. )
  589. parser.add_argument(
  590. '-b',
  591. '--max-budget-per-task',
  592. type=float,
  593. help='The maximum budget allowed per task, beyond which the agent will stop.',
  594. )
  595. # --eval configs are for evaluations only
  596. parser.add_argument(
  597. '--eval-output-dir',
  598. default='evaluation/evaluation_outputs/outputs',
  599. type=str,
  600. help='The directory to save evaluation output',
  601. )
  602. parser.add_argument(
  603. '--eval-n-limit',
  604. default=None,
  605. type=int,
  606. help='The number of instances to evaluate',
  607. )
  608. parser.add_argument(
  609. '--eval-num-workers',
  610. default=4,
  611. type=int,
  612. help='The number of workers to use for evaluation',
  613. )
  614. parser.add_argument(
  615. '--eval-note',
  616. default=None,
  617. type=str,
  618. help='The note to add to the evaluation directory',
  619. )
  620. parser.add_argument(
  621. '-l',
  622. '--llm-config',
  623. default=None,
  624. type=str,
  625. help='Replace default LLM ([llm] section in config.toml) config with the specified LLM config, e.g. "llama3" for [llm.llama3] section in config.toml',
  626. )
  627. parser.add_argument(
  628. '-n',
  629. '--name',
  630. default='default',
  631. type=str,
  632. help='Name for the session',
  633. )
  634. parser.add_argument(
  635. '--eval-ids',
  636. default=None,
  637. type=str,
  638. help='The comma-separated list (in quotes) of IDs of the instances to evaluate',
  639. )
  640. return parser
  641. def parse_arguments() -> argparse.Namespace:
  642. """Parse the command line arguments."""
  643. parser = get_parser()
  644. parsed_args, _ = parser.parse_known_args()
  645. return parsed_args
  646. def load_app_config(set_logging_levels: bool = True) -> AppConfig:
  647. """Load the configuration from the config.toml file and environment variables.
  648. Args:
  649. set_logger_levels: Whether to set the global variables for logging levels.
  650. """
  651. config = AppConfig()
  652. load_from_toml(config)
  653. load_from_env(config, os.environ)
  654. finalize_config(config)
  655. if set_logging_levels:
  656. logger.DEBUG = config.debug
  657. logger.DISABLE_COLOR_PRINTING = config.disable_color
  658. return config