config.py 27 KB

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