config.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571
  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, 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(metaclass=Singleton):
  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. temperature: The temperature for the API.
  36. top_p: The top p for the API.
  37. 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.
  38. 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).
  39. max_output_tokens: The maximum number of output tokens. This is sent to the LLM.
  40. input_cost_per_token: The cost per input token. This will available in logs for the user to check.
  41. output_cost_per_token: The cost per output token. This will available in logs for the user to check.
  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. temperature: float = 0
  58. top_p: float = 0.5
  59. custom_llm_provider: str | None = None
  60. max_input_tokens: int | None = None
  61. max_output_tokens: int | None = None
  62. input_cost_per_token: float | None = None
  63. output_cost_per_token: float | None = None
  64. def defaults_to_dict(self) -> dict:
  65. """
  66. Serialize fields to a dict for the frontend, including type hints, defaults, and whether it's optional.
  67. """
  68. dict = {}
  69. for f in fields(self):
  70. dict[f.name] = get_field_info(f)
  71. return dict
  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(metaclass=Singleton):
  85. """
  86. Configuration for the agent.
  87. Attributes:
  88. name: The name of the agent.
  89. memory_enabled: Whether long-term memory (embeddings) is enabled.
  90. memory_max_threads: The maximum number of threads indexing at the same time for embeddings.
  91. """
  92. name: str = 'CodeActAgent'
  93. memory_enabled: bool = False
  94. memory_max_threads: int = 2
  95. def defaults_to_dict(self) -> dict:
  96. """
  97. Serialize fields to a dict for the frontend, including type hints, defaults, and whether it's optional.
  98. """
  99. dict = {}
  100. for f in fields(self):
  101. dict[f.name] = get_field_info(f)
  102. return dict
  103. class UndefinedString(str, Enum):
  104. UNDEFINED = 'UNDEFINED'
  105. @dataclass
  106. class AppConfig(metaclass=Singleton):
  107. """
  108. Configuration for the app.
  109. Attributes:
  110. llm: The LLM configuration.
  111. agent: The agent configuration.
  112. runtime: The runtime environment.
  113. file_store: The file store to use.
  114. file_store_path: The path to the file store.
  115. workspace_base: The base path for the workspace. Defaults to ./workspace as an absolute path.
  116. workspace_mount_path: The path to mount the workspace. This is set to the workspace base by default.
  117. workspace_mount_path_in_sandbox: The path to mount the workspace in the sandbox. Defaults to /workspace.
  118. workspace_mount_rewrite: The path to rewrite the workspace mount path to.
  119. cache_dir: The path to the cache directory. Defaults to /tmp/cache.
  120. sandbox_container_image: The container image to use for the sandbox.
  121. run_as_devin: Whether to run as devin.
  122. max_iterations: The maximum number of iterations.
  123. max_budget_per_task: The maximum budget allowed per task, beyond which the agent will stop.
  124. e2b_api_key: The E2B API key.
  125. sandbox_type: The type of sandbox to use. Options are: ssh, exec, e2b, local.
  126. use_host_network: Whether to use the host network.
  127. ssh_hostname: The SSH hostname.
  128. disable_color: Whether to disable color. For terminals that don't support color.
  129. sandbox_user_id: The user ID for the sandbox.
  130. sandbox_timeout: The timeout for the sandbox.
  131. debug: Whether to enable debugging.
  132. 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.
  133. file_uploads_max_file_size_mb: Maximum file size for uploads in megabytes. 0 means no limit.
  134. file_uploads_restrict_file_types: Whether to restrict file types for file uploads. Defaults to False.
  135. file_uploads_allowed_extensions: List of allowed file extensions for uploads. ['.*'] means all extensions are allowed.
  136. """
  137. llm: LLMConfig = field(default_factory=LLMConfig)
  138. agent: AgentConfig = field(default_factory=AgentConfig)
  139. runtime: str = 'server'
  140. file_store: str = 'memory'
  141. file_store_path: str = '/tmp/file_store'
  142. workspace_base: str = os.path.join(os.getcwd(), 'workspace')
  143. workspace_mount_path: str = (
  144. UndefinedString.UNDEFINED # this path should always be set when config is fully loaded
  145. )
  146. workspace_mount_path_in_sandbox: str = '/workspace'
  147. workspace_mount_rewrite: str | None = None
  148. cache_dir: str = '/tmp/cache'
  149. sandbox_container_image: str = 'ghcr.io/opendevin/sandbox' + (
  150. f':{os.getenv("OPEN_DEVIN_BUILD_VERSION")}'
  151. if os.getenv('OPEN_DEVIN_BUILD_VERSION')
  152. else ':main'
  153. )
  154. run_as_devin: bool = True
  155. max_iterations: int = 100
  156. max_budget_per_task: float | None = None
  157. e2b_api_key: str = ''
  158. sandbox_type: str = 'ssh' # Can be 'ssh', 'exec', or 'e2b'
  159. use_host_network: bool = False
  160. ssh_hostname: str = 'localhost'
  161. disable_color: bool = False
  162. sandbox_user_id: int = os.getuid() if hasattr(os, 'getuid') else 1000
  163. sandbox_timeout: int = 120
  164. initialize_plugins: bool = True
  165. persist_sandbox: bool = False
  166. ssh_port: int = 63710
  167. ssh_password: str | None = None
  168. jwt_secret: str = uuid.uuid4().hex
  169. debug: bool = False
  170. enable_auto_lint: bool = (
  171. False # once enabled, OpenDevin would lint files after editing
  172. )
  173. file_uploads_max_file_size_mb: int = 0
  174. file_uploads_restrict_file_types: bool = False
  175. file_uploads_allowed_extensions: list[str] = field(default_factory=lambda: ['.*'])
  176. defaults_dict: ClassVar[dict] = {}
  177. def __post_init__(self):
  178. """
  179. Post-initialization hook, called when the instance is created with only default values.
  180. """
  181. AppConfig.defaults_dict = self.defaults_to_dict()
  182. def defaults_to_dict(self) -> dict:
  183. """
  184. Serialize fields to a dict for the frontend, including type hints, defaults, and whether it's optional.
  185. """
  186. dict = {}
  187. for f in fields(self):
  188. field_value = getattr(self, f.name)
  189. # dataclasses compute their defaults themselves
  190. if is_dataclass(type(field_value)):
  191. dict[f.name] = field_value.defaults_to_dict()
  192. else:
  193. dict[f.name] = get_field_info(f)
  194. return dict
  195. def __str__(self):
  196. attr_str = []
  197. for f in fields(self):
  198. attr_name = f.name
  199. attr_value = getattr(self, f.name)
  200. if attr_name in [
  201. 'e2b_api_key',
  202. 'github_token',
  203. 'jwt_secret',
  204. 'ssh_password',
  205. ]:
  206. attr_value = '******' if attr_value else None
  207. attr_str.append(f'{attr_name}={repr(attr_value)}')
  208. return f"AppConfig({', '.join(attr_str)}"
  209. def __repr__(self):
  210. return self.__str__()
  211. def get_field_info(field):
  212. """
  213. Extract information about a dataclass field: type, optional, and default.
  214. Args:
  215. field: The field to extract information from.
  216. Returns: A dict with the field's type, whether it's optional, and its default value.
  217. """
  218. field_type = field.type
  219. optional = False
  220. # for types like str | None, find the non-None type and set optional to True
  221. # this is useful for the frontend to know if a field is optional
  222. # and to show the correct type in the UI
  223. # Note: this only works for UnionTypes with None as one of the types
  224. if get_origin(field_type) is UnionType:
  225. types = get_args(field_type)
  226. non_none_arg = next((t for t in types if t is not type(None)), None)
  227. if non_none_arg is not None:
  228. field_type = non_none_arg
  229. optional = True
  230. # type name in a pretty format
  231. type_name = (
  232. field_type.__name__ if hasattr(field_type, '__name__') else str(field_type)
  233. )
  234. # default is always present
  235. default = field.default
  236. # return a schema with the useful info for frontend
  237. return {'type': type_name.lower(), 'optional': optional, 'default': default}
  238. def load_from_env(config: AppConfig, env_or_toml_dict: dict | os._Environ):
  239. """Reads the env-style vars and sets config attributes based on env vars or a config.toml dict.
  240. Compatibility with vars like LLM_BASE_URL, AGENT_MEMORY_ENABLED and others.
  241. Args:
  242. config: The AppConfig object to set attributes on.
  243. env_or_toml_dict: The environment variables or a config.toml dict.
  244. """
  245. def get_optional_type(union_type: UnionType) -> Any:
  246. """Returns the non-None type from an Union."""
  247. types = get_args(union_type)
  248. return next((t for t in types if t is not type(None)), None)
  249. # helper function to set attributes based on env vars
  250. def set_attr_from_env(sub_config: Any, prefix=''):
  251. """Set attributes of a config dataclass based on environment variables."""
  252. for field_name, field_type in sub_config.__annotations__.items():
  253. # compute the expected env var name from the prefix and field name
  254. # e.g. LLM_BASE_URL
  255. env_var_name = (prefix + field_name).upper()
  256. if is_dataclass(field_type):
  257. # nested dataclass
  258. nested_sub_config = getattr(sub_config, field_name)
  259. # the agent field: the env var for agent.name is just 'AGENT'
  260. if field_name == 'agent' and 'AGENT' in env_or_toml_dict:
  261. setattr(nested_sub_config, 'name', env_or_toml_dict[env_var_name])
  262. set_attr_from_env(nested_sub_config, prefix=field_name + '_')
  263. elif env_var_name in env_or_toml_dict:
  264. # convert the env var to the correct type and set it
  265. value = env_or_toml_dict[env_var_name]
  266. try:
  267. # if it's an optional type, get the non-None type
  268. if get_origin(field_type) is UnionType:
  269. field_type = get_optional_type(field_type)
  270. # Attempt to cast the env var to type hinted in the dataclass
  271. if field_type is bool:
  272. cast_value = str(value).lower() in ['true', '1']
  273. else:
  274. cast_value = field_type(value)
  275. setattr(sub_config, field_name, cast_value)
  276. except (ValueError, TypeError):
  277. logger.error(
  278. f'Error setting env var {env_var_name}={value}: check that the value is of the right type'
  279. )
  280. # Start processing from the root of the config object
  281. set_attr_from_env(config)
  282. def load_from_toml(config: AppConfig, toml_file: str = 'config.toml'):
  283. """Load the config from the toml file. Supports both styles of config vars.
  284. Args:
  285. config: The AppConfig object to update attributes of.
  286. """
  287. # try to read the config.toml file into the config object
  288. toml_config = {}
  289. try:
  290. with open(toml_file, 'r', encoding='utf-8') as toml_contents:
  291. toml_config = toml.load(toml_contents)
  292. except FileNotFoundError as e:
  293. logger.info(f'Config file not found: {e}')
  294. return
  295. except toml.TomlDecodeError as e:
  296. logger.warning(
  297. f'Cannot parse config from toml, toml values have not been applied.\nError: {e}',
  298. exc_info=False,
  299. )
  300. return
  301. # if there was an exception or core is not in the toml, try to use the old-style toml
  302. if 'core' not in toml_config:
  303. # re-use the env loader to set the config from env-style vars
  304. load_from_env(config, toml_config)
  305. return
  306. core_config = toml_config['core']
  307. try:
  308. # set llm config from the toml file
  309. llm_config = config.llm
  310. if 'llm' in toml_config:
  311. llm_config = LLMConfig(**toml_config['llm'])
  312. # set agent config from the toml file
  313. agent_config = config.agent
  314. if 'agent' in toml_config:
  315. agent_config = AgentConfig(**toml_config['agent'])
  316. # update the config object with the new values
  317. config = AppConfig(llm=llm_config, agent=agent_config, **core_config)
  318. except (TypeError, KeyError) as e:
  319. logger.warning(
  320. f'Cannot parse config from toml, toml values have not been applied.\nError: {e}',
  321. exc_info=False,
  322. )
  323. def finalize_config(config: AppConfig):
  324. """
  325. More tweaks to the config after it's been loaded.
  326. """
  327. # Set workspace_mount_path if not set by the user
  328. if config.workspace_mount_path is UndefinedString.UNDEFINED:
  329. config.workspace_mount_path = os.path.abspath(config.workspace_base)
  330. config.workspace_base = os.path.abspath(config.workspace_base)
  331. # In local there is no sandbox, the workspace will have the same pwd as the host
  332. if config.sandbox_type == 'local':
  333. config.workspace_mount_path_in_sandbox = config.workspace_mount_path
  334. if config.workspace_mount_rewrite: # and not config.workspace_mount_path:
  335. # TODO why do we need to check if workspace_mount_path is None?
  336. base = config.workspace_base or os.getcwd()
  337. parts = config.workspace_mount_rewrite.split(':')
  338. config.workspace_mount_path = base.replace(parts[0], parts[1])
  339. if config.llm.embedding_base_url is None:
  340. config.llm.embedding_base_url = config.llm.base_url
  341. if config.use_host_network and platform.system() == 'Darwin':
  342. logger.warning(
  343. 'Please upgrade to Docker Desktop 4.29.0 or later to use host network mode on macOS. '
  344. 'See https://github.com/docker/roadmap/issues/238#issuecomment-2044688144 for more information.'
  345. )
  346. # make sure cache dir exists
  347. if config.cache_dir:
  348. pathlib.Path(config.cache_dir).mkdir(parents=True, exist_ok=True)
  349. config = AppConfig()
  350. load_from_toml(config)
  351. load_from_env(config, os.environ)
  352. finalize_config(config)
  353. # Utility function for command line --group argument
  354. def get_llm_config_arg(llm_config_arg: str):
  355. """
  356. Get a group of llm settings from the config file.
  357. A group in config.toml can look like this:
  358. ```
  359. [gpt-3.5-for-eval]
  360. model = 'gpt-3.5-turbo'
  361. api_key = '...'
  362. temperature = 0.5
  363. num_retries = 10
  364. ...
  365. ```
  366. The user-defined group name, like "gpt-3.5-for-eval", is the argument to this function. The function will load the LLMConfig object
  367. with the settings of this group, from the config file, and set it as the LLMConfig object for the app.
  368. Args:
  369. llm_config_arg: The group of llm settings to get from the config.toml file.
  370. Returns:
  371. LLMConfig: The LLMConfig object with the settings from the config file.
  372. """
  373. # keep only the name, just in case
  374. llm_config_arg = llm_config_arg.strip('[]')
  375. logger.info(f'Loading llm config from {llm_config_arg}')
  376. # load the toml file
  377. try:
  378. with open('config.toml', 'r', encoding='utf-8') as toml_file:
  379. toml_config = toml.load(toml_file)
  380. except FileNotFoundError as e:
  381. logger.error(f'Config file not found: {e}')
  382. return None
  383. except toml.TomlDecodeError as e:
  384. logger.error(f'Cannot parse llm group from {llm_config_arg}. Exception: {e}')
  385. return None
  386. # update the llm config with the specified section
  387. if llm_config_arg in toml_config:
  388. return LLMConfig(**toml_config[llm_config_arg])
  389. logger.debug(f'Loading from toml failed for {llm_config_arg}')
  390. return None
  391. # Command line arguments
  392. def get_parser():
  393. """
  394. Get the parser for the command line arguments.
  395. """
  396. parser = argparse.ArgumentParser(description='Run an agent with a specific task')
  397. parser.add_argument(
  398. '-d',
  399. '--directory',
  400. type=str,
  401. help='The working directory for the agent',
  402. )
  403. parser.add_argument(
  404. '-t', '--task', type=str, default='', help='The task for the agent to perform'
  405. )
  406. parser.add_argument(
  407. '-f',
  408. '--file',
  409. type=str,
  410. help='Path to a file containing the task. Overrides -t if both are provided.',
  411. )
  412. parser.add_argument(
  413. '-c',
  414. '--agent-cls',
  415. default=config.agent.name,
  416. type=str,
  417. help='The agent class to use',
  418. )
  419. parser.add_argument(
  420. '-m',
  421. '--model-name',
  422. default=config.llm.model,
  423. type=str,
  424. help='The (litellm) model name to use',
  425. )
  426. parser.add_argument(
  427. '-i',
  428. '--max-iterations',
  429. default=config.max_iterations,
  430. type=int,
  431. help='The maximum number of iterations to run the agent',
  432. )
  433. parser.add_argument(
  434. '-b',
  435. '--max-budget-per-task',
  436. default=config.max_budget_per_task,
  437. type=float,
  438. help='The maximum budget allowed per task, beyond which the agent will stop.',
  439. )
  440. # --eval configs are for evaluations only
  441. parser.add_argument(
  442. '--eval-output-dir',
  443. default='evaluation/evaluation_outputs/outputs',
  444. type=str,
  445. help='The directory to save evaluation output',
  446. )
  447. parser.add_argument(
  448. '--eval-n-limit',
  449. default=None,
  450. type=int,
  451. help='The number of instances to evaluate',
  452. )
  453. parser.add_argument(
  454. '--eval-num-workers',
  455. default=4,
  456. type=int,
  457. help='The number of workers to use for evaluation',
  458. )
  459. parser.add_argument(
  460. '--eval-note',
  461. default=None,
  462. type=str,
  463. help='The note to add to the evaluation directory',
  464. )
  465. parser.add_argument(
  466. '-l',
  467. '--llm-config',
  468. default=None,
  469. type=str,
  470. help='The group of llm settings, e.g. a [llama3] section in the toml file. Overrides model if both are provided.',
  471. )
  472. return parser
  473. def parse_arguments():
  474. """
  475. Parse the command line arguments.
  476. """
  477. parser = get_parser()
  478. args, _ = parser.parse_known_args()
  479. if args.directory:
  480. config.workspace_base = os.path.abspath(args.directory)
  481. print(f'Setting workspace base to {config.workspace_base}')
  482. return args
  483. args = parse_arguments()