config.py 28 KB

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