utils.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405
  1. import argparse
  2. import os
  3. import pathlib
  4. import platform
  5. from dataclasses import is_dataclass
  6. from types import UnionType
  7. from typing import Any, MutableMapping, get_args, get_origin
  8. import toml
  9. from dotenv import load_dotenv
  10. from openhands.core import logger
  11. from openhands.core.config.agent_config import AgentConfig
  12. from openhands.core.config.app_config import AppConfig
  13. from openhands.core.config.config_utils import (
  14. OH_DEFAULT_AGENT,
  15. OH_MAX_ITERATIONS,
  16. )
  17. from openhands.core.config.llm_config import LLMConfig
  18. from openhands.core.config.sandbox_config import SandboxConfig
  19. from openhands.core.config.security_config import SecurityConfig
  20. load_dotenv()
  21. def load_from_env(cfg: AppConfig, env_or_toml_dict: dict | MutableMapping[str, str]):
  22. """Reads the env-style vars and sets config attributes based on env vars or a config.toml dict.
  23. Compatibility with vars like LLM_BASE_URL, AGENT_MEMORY_ENABLED, SANDBOX_TIMEOUT and others.
  24. Args:
  25. cfg: The AppConfig object to set attributes on.
  26. env_or_toml_dict: The environment variables or a config.toml dict.
  27. """
  28. def get_optional_type(union_type: UnionType) -> Any:
  29. """Returns the non-None type from a Union."""
  30. types = get_args(union_type)
  31. return next((t for t in types if t is not type(None)), None)
  32. # helper function to set attributes based on env vars
  33. def set_attr_from_env(sub_config: Any, prefix=''):
  34. """Set attributes of a config dataclass based on environment variables."""
  35. for field_name, field_type in sub_config.__annotations__.items():
  36. # compute the expected env var name from the prefix and field name
  37. # e.g. LLM_BASE_URL
  38. env_var_name = (prefix + field_name).upper()
  39. if is_dataclass(field_type):
  40. # nested dataclass
  41. nested_sub_config = getattr(sub_config, field_name)
  42. set_attr_from_env(nested_sub_config, prefix=field_name + '_')
  43. elif env_var_name in env_or_toml_dict:
  44. # convert the env var to the correct type and set it
  45. value = env_or_toml_dict[env_var_name]
  46. # skip empty config values (fall back to default)
  47. if not value:
  48. continue
  49. try:
  50. # if it's an optional type, get the non-None type
  51. if get_origin(field_type) is UnionType:
  52. field_type = get_optional_type(field_type)
  53. # Attempt to cast the env var to type hinted in the dataclass
  54. if field_type is bool:
  55. cast_value = str(value).lower() in ['true', '1']
  56. else:
  57. cast_value = field_type(value)
  58. setattr(sub_config, field_name, cast_value)
  59. except (ValueError, TypeError):
  60. logger.openhands_logger.error(
  61. f'Error setting env var {env_var_name}={value}: check that the value is of the right type'
  62. )
  63. # Start processing from the root of the config object
  64. set_attr_from_env(cfg)
  65. # load default LLM config from env
  66. default_llm_config = cfg.get_llm_config()
  67. set_attr_from_env(default_llm_config, 'LLM_')
  68. # load default agent config from env
  69. default_agent_config = cfg.get_agent_config()
  70. set_attr_from_env(default_agent_config, 'AGENT_')
  71. def load_from_toml(cfg: AppConfig, toml_file: str = 'config.toml'):
  72. """Load the config from the toml file. Supports both styles of config vars.
  73. Args:
  74. cfg: The AppConfig object to update attributes of.
  75. toml_file: The path to the toml file. Defaults to 'config.toml'.
  76. """
  77. # try to read the config.toml file into the config object
  78. try:
  79. with open(toml_file, 'r', encoding='utf-8') as toml_contents:
  80. toml_config = toml.load(toml_contents)
  81. except FileNotFoundError:
  82. return
  83. except toml.TomlDecodeError as e:
  84. logger.openhands_logger.warning(
  85. f'Cannot parse config from toml, toml values have not been applied.\nError: {e}',
  86. exc_info=False,
  87. )
  88. return
  89. # if there was an exception or core is not in the toml, try to use the old-style toml
  90. if 'core' not in toml_config:
  91. # re-use the env loader to set the config from env-style vars
  92. load_from_env(cfg, toml_config)
  93. return
  94. core_config = toml_config['core']
  95. # load llm configs and agent configs
  96. for key, value in toml_config.items():
  97. if isinstance(value, dict):
  98. try:
  99. if key is not None and key.lower() == 'agent':
  100. logger.openhands_logger.debug(
  101. 'Attempt to load default agent config from config toml'
  102. )
  103. non_dict_fields = {
  104. k: v for k, v in value.items() if not isinstance(v, dict)
  105. }
  106. agent_config = AgentConfig(**non_dict_fields)
  107. cfg.set_agent_config(agent_config, 'agent')
  108. for nested_key, nested_value in value.items():
  109. if isinstance(nested_value, dict):
  110. logger.openhands_logger.debug(
  111. f'Attempt to load group {nested_key} from config toml as agent config'
  112. )
  113. agent_config = AgentConfig(**nested_value)
  114. cfg.set_agent_config(agent_config, nested_key)
  115. elif key is not None and key.lower() == 'llm':
  116. logger.openhands_logger.debug(
  117. 'Attempt to load default LLM config from config toml'
  118. )
  119. llm_config = LLMConfig.from_dict(value)
  120. cfg.set_llm_config(llm_config, 'llm')
  121. for nested_key, nested_value in value.items():
  122. if isinstance(nested_value, dict):
  123. logger.openhands_logger.debug(
  124. f'Attempt to load group {nested_key} from config toml as llm config'
  125. )
  126. llm_config = LLMConfig.from_dict(nested_value)
  127. cfg.set_llm_config(llm_config, nested_key)
  128. elif key is not None and key.lower() == 'security':
  129. logger.openhands_logger.debug(
  130. 'Attempt to load security config from config toml'
  131. )
  132. security_config = SecurityConfig.from_dict(value)
  133. cfg.security = security_config
  134. elif not key.startswith('sandbox') and key.lower() != 'core':
  135. logger.openhands_logger.warning(
  136. f'Unknown key in {toml_file}: "{key}"'
  137. )
  138. except (TypeError, KeyError) as e:
  139. logger.openhands_logger.warning(
  140. f'Cannot parse config from toml, toml values have not been applied.\n Error: {e}',
  141. exc_info=False,
  142. )
  143. else:
  144. logger.openhands_logger.warning(f'Unknown key in {toml_file}: "{key}')
  145. try:
  146. # set sandbox config from the toml file
  147. sandbox_config = cfg.sandbox
  148. # migrate old sandbox configs from [core] section to sandbox config
  149. keys_to_migrate = [key for key in core_config if key.startswith('sandbox_')]
  150. for key in keys_to_migrate:
  151. new_key = key.replace('sandbox_', '')
  152. if new_key in sandbox_config.__annotations__:
  153. # read the key in sandbox and remove it from core
  154. setattr(sandbox_config, new_key, core_config.pop(key))
  155. else:
  156. logger.openhands_logger.warning(f'Unknown sandbox config: {key}')
  157. # the new style values override the old style values
  158. if 'sandbox' in toml_config:
  159. sandbox_config = SandboxConfig(**toml_config['sandbox'])
  160. # update the config object with the new values
  161. cfg.sandbox = sandbox_config
  162. for key, value in core_config.items():
  163. if hasattr(cfg, key):
  164. setattr(cfg, key, value)
  165. else:
  166. logger.openhands_logger.warning(f'Unknown core config key: {key}')
  167. except (TypeError, KeyError) as e:
  168. logger.openhands_logger.warning(
  169. f'Cannot parse config from toml, toml values have not been applied.\nError: {e}',
  170. exc_info=False,
  171. )
  172. def finalize_config(cfg: AppConfig):
  173. """More tweaks to the config after it's been loaded."""
  174. if cfg.workspace_base is not None:
  175. cfg.workspace_base = os.path.abspath(cfg.workspace_base)
  176. if cfg.workspace_mount_path is None:
  177. cfg.workspace_mount_path = cfg.workspace_base
  178. if cfg.workspace_mount_rewrite:
  179. base = cfg.workspace_base or os.getcwd()
  180. parts = cfg.workspace_mount_rewrite.split(':')
  181. cfg.workspace_mount_path = base.replace(parts[0], parts[1])
  182. # make sure log_completions_folder is an absolute path
  183. for llm in cfg.llms.values():
  184. llm.log_completions_folder = os.path.abspath(llm.log_completions_folder)
  185. if llm.embedding_base_url is None:
  186. llm.embedding_base_url = llm.base_url
  187. if cfg.sandbox.use_host_network and platform.system() == 'Darwin':
  188. logger.openhands_logger.warning(
  189. 'Please upgrade to Docker Desktop 4.29.0 or later to use host network mode on macOS. '
  190. 'See https://github.com/docker/roadmap/issues/238#issuecomment-2044688144 for more information.'
  191. )
  192. # make sure cache dir exists
  193. if cfg.cache_dir:
  194. pathlib.Path(cfg.cache_dir).mkdir(parents=True, exist_ok=True)
  195. # Utility function for command line --group argument
  196. def get_llm_config_arg(
  197. llm_config_arg: str, toml_file: str = 'config.toml'
  198. ) -> LLMConfig | None:
  199. """Get a group of llm settings from the config file.
  200. A group in config.toml can look like this:
  201. ```
  202. [llm.gpt-3.5-for-eval]
  203. model = 'gpt-3.5-turbo'
  204. api_key = '...'
  205. temperature = 0.5
  206. num_retries = 8
  207. ...
  208. ```
  209. The user-defined group name, like "gpt-3.5-for-eval", is the argument to this function. The function will load the LLMConfig object
  210. with the settings of this group, from the config file, and set it as the LLMConfig object for the app.
  211. Note that the group must be under "llm" group, or in other words, the group name must start with "llm.".
  212. Args:
  213. llm_config_arg: The group of llm settings to get from the config.toml file.
  214. toml_file: Path to the configuration file to read from. Defaults to 'config.toml'.
  215. Returns:
  216. LLMConfig: The LLMConfig object with the settings from the config file.
  217. """
  218. # keep only the name, just in case
  219. llm_config_arg = llm_config_arg.strip('[]')
  220. # truncate the prefix, just in case
  221. if llm_config_arg.startswith('llm.'):
  222. llm_config_arg = llm_config_arg[4:]
  223. logger.openhands_logger.debug(f'Loading llm config from {llm_config_arg}')
  224. # load the toml file
  225. try:
  226. with open(toml_file, 'r', encoding='utf-8') as toml_contents:
  227. toml_config = toml.load(toml_contents)
  228. except FileNotFoundError as e:
  229. logger.openhands_logger.error(f'Config file not found: {e}')
  230. return None
  231. except toml.TomlDecodeError as e:
  232. logger.openhands_logger.error(
  233. f'Cannot parse llm group from {llm_config_arg}. Exception: {e}'
  234. )
  235. return None
  236. # update the llm config with the specified section
  237. if 'llm' in toml_config and llm_config_arg in toml_config['llm']:
  238. return LLMConfig.from_dict(toml_config['llm'][llm_config_arg])
  239. logger.openhands_logger.debug(f'Loading from toml failed for {llm_config_arg}')
  240. return None
  241. # Command line arguments
  242. def get_parser() -> argparse.ArgumentParser:
  243. """Get the parser for the command line arguments."""
  244. parser = argparse.ArgumentParser(description='Run an agent with a specific task')
  245. parser.add_argument(
  246. '--config-file',
  247. type=str,
  248. default='config.toml',
  249. help='Path to the config file (default: config.toml in the current directory)',
  250. )
  251. parser.add_argument(
  252. '-d',
  253. '--directory',
  254. type=str,
  255. help='The working directory for the agent',
  256. )
  257. parser.add_argument(
  258. '-t',
  259. '--task',
  260. type=str,
  261. default='',
  262. help='The task for the agent to perform',
  263. )
  264. parser.add_argument(
  265. '-f',
  266. '--file',
  267. type=str,
  268. help='Path to a file containing the task. Overrides -t if both are provided.',
  269. )
  270. parser.add_argument(
  271. '-c',
  272. '--agent-cls',
  273. default=OH_DEFAULT_AGENT,
  274. type=str,
  275. help='Name of the default agent to use',
  276. )
  277. parser.add_argument(
  278. '-i',
  279. '--max-iterations',
  280. default=OH_MAX_ITERATIONS,
  281. type=int,
  282. help='The maximum number of iterations to run the agent',
  283. )
  284. parser.add_argument(
  285. '-b',
  286. '--max-budget-per-task',
  287. type=float,
  288. help='The maximum budget allowed per task, beyond which the agent will stop.',
  289. )
  290. # --eval configs are for evaluations only
  291. parser.add_argument(
  292. '--eval-output-dir',
  293. default='evaluation/evaluation_outputs/outputs',
  294. type=str,
  295. help='The directory to save evaluation output',
  296. )
  297. parser.add_argument(
  298. '--eval-n-limit',
  299. default=None,
  300. type=int,
  301. help='The number of instances to evaluate',
  302. )
  303. parser.add_argument(
  304. '--eval-num-workers',
  305. default=4,
  306. type=int,
  307. help='The number of workers to use for evaluation',
  308. )
  309. parser.add_argument(
  310. '--eval-note',
  311. default=None,
  312. type=str,
  313. help='The note to add to the evaluation directory',
  314. )
  315. parser.add_argument(
  316. '-l',
  317. '--llm-config',
  318. default=None,
  319. type=str,
  320. 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',
  321. )
  322. parser.add_argument(
  323. '-n',
  324. '--name',
  325. default='default',
  326. type=str,
  327. help='Name for the session',
  328. )
  329. parser.add_argument(
  330. '--eval-ids',
  331. default=None,
  332. type=str,
  333. help='The comma-separated list (in quotes) of IDs of the instances to evaluate',
  334. )
  335. return parser
  336. def parse_arguments() -> argparse.Namespace:
  337. """Parse the command line arguments."""
  338. parser = get_parser()
  339. parsed_args, _ = parser.parse_known_args()
  340. return parsed_args
  341. def load_app_config(
  342. set_logging_levels: bool = True, config_file: str = 'config.toml'
  343. ) -> AppConfig:
  344. """Load the configuration from the specified config file and environment variables.
  345. Args:
  346. set_logging_levels: Whether to set the global variables for logging levels.
  347. config_file: Path to the config file. Defaults to 'config.toml' in the current directory.
  348. """
  349. config = AppConfig()
  350. load_from_toml(config, config_file)
  351. load_from_env(config, os.environ)
  352. finalize_config(config)
  353. if set_logging_levels:
  354. logger.DEBUG = config.debug
  355. logger.DISABLE_COLOR_PRINTING = config.disable_color
  356. return config