config.py 20 KB

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