config.py 26 KB

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