utils.py 16 KB

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