utils.py 15 KB

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