config.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563
  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-3.5-turbo'
  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. persist_sandbox: bool = False
  160. ssh_port: int = 63710
  161. ssh_password: str | None = None
  162. github_token: str | None = None
  163. jwt_secret: str = uuid.uuid4().hex
  164. debug: bool = False
  165. enable_auto_lint: bool = (
  166. False # once enabled, OpenDevin would lint files after editing
  167. )
  168. defaults_dict: ClassVar[dict] = {}
  169. def __post_init__(self):
  170. """
  171. Post-initialization hook, called when the instance is created with only default values.
  172. """
  173. AppConfig.defaults_dict = self.defaults_to_dict()
  174. def defaults_to_dict(self) -> dict:
  175. """
  176. Serialize fields to a dict for the frontend, including type hints, defaults, and whether it's optional.
  177. """
  178. dict = {}
  179. for f in fields(self):
  180. field_value = getattr(self, f.name)
  181. # dataclasses compute their defaults themselves
  182. if is_dataclass(type(field_value)):
  183. dict[f.name] = field_value.defaults_to_dict()
  184. else:
  185. dict[f.name] = get_field_info(f)
  186. return dict
  187. def __str__(self):
  188. attr_str = []
  189. for f in fields(self):
  190. attr_name = f.name
  191. attr_value = getattr(self, f.name)
  192. if attr_name in ['e2b_api_key', 'github_token']:
  193. attr_value = '******' if attr_value else None
  194. attr_str.append(f'{attr_name}={repr(attr_value)}')
  195. return f"AppConfig({', '.join(attr_str)}"
  196. def __repr__(self):
  197. return self.__str__()
  198. def get_field_info(field):
  199. """
  200. Extract information about a dataclass field: type, optional, and default.
  201. Args:
  202. field: The field to extract information from.
  203. Returns: A dict with the field's type, whether it's optional, and its default value.
  204. """
  205. field_type = field.type
  206. optional = False
  207. # for types like str | None, find the non-None type and set optional to True
  208. # this is useful for the frontend to know if a field is optional
  209. # and to show the correct type in the UI
  210. # Note: this only works for UnionTypes with None as one of the types
  211. if get_origin(field_type) is UnionType:
  212. types = get_args(field_type)
  213. non_none_arg = next((t for t in types if t is not type(None)), None)
  214. if non_none_arg is not None:
  215. field_type = non_none_arg
  216. optional = True
  217. # type name in a pretty format
  218. type_name = (
  219. field_type.__name__ if hasattr(field_type, '__name__') else str(field_type)
  220. )
  221. # default is always present
  222. default = field.default
  223. # return a schema with the useful info for frontend
  224. return {'type': type_name.lower(), 'optional': optional, 'default': default}
  225. def load_from_env(config: AppConfig, env_or_toml_dict: dict | os._Environ):
  226. """Reads the env-style vars and sets config attributes based on env vars or a config.toml dict.
  227. Compatibility with vars like LLM_BASE_URL, AGENT_MEMORY_ENABLED and others.
  228. Args:
  229. config: The AppConfig object to set attributes on.
  230. env_or_toml_dict: The environment variables or a config.toml dict.
  231. """
  232. def get_optional_type(union_type: UnionType) -> Any:
  233. """Returns the non-None type from an Union."""
  234. types = get_args(union_type)
  235. return next((t for t in types if t is not type(None)), None)
  236. # helper function to set attributes based on env vars
  237. def set_attr_from_env(sub_config: Any, prefix=''):
  238. """Set attributes of a config dataclass based on environment variables."""
  239. for field_name, field_type in sub_config.__annotations__.items():
  240. # compute the expected env var name from the prefix and field name
  241. # e.g. LLM_BASE_URL
  242. env_var_name = (prefix + field_name).upper()
  243. if is_dataclass(field_type):
  244. # nested dataclass
  245. nested_sub_config = getattr(sub_config, field_name)
  246. # the agent field: the env var for agent.name is just 'AGENT'
  247. if field_name == 'agent' and 'AGENT' in env_or_toml_dict:
  248. setattr(nested_sub_config, 'name', env_or_toml_dict[env_var_name])
  249. set_attr_from_env(nested_sub_config, prefix=field_name + '_')
  250. elif env_var_name in env_or_toml_dict:
  251. # convert the env var to the correct type and set it
  252. value = env_or_toml_dict[env_var_name]
  253. try:
  254. # if it's an optional type, get the non-None type
  255. if get_origin(field_type) is UnionType:
  256. field_type = get_optional_type(field_type)
  257. # Attempt to cast the env var to type hinted in the dataclass
  258. if field_type is bool:
  259. cast_value = str(value).lower() in ['true', '1']
  260. else:
  261. cast_value = field_type(value)
  262. setattr(sub_config, field_name, cast_value)
  263. except (ValueError, TypeError):
  264. logger.error(
  265. f'Error setting env var {env_var_name}={value}: check that the value is of the right type'
  266. )
  267. # Start processing from the root of the config object
  268. set_attr_from_env(config)
  269. def load_from_toml(config: AppConfig, toml_file: str = 'config.toml'):
  270. """Load the config from the toml file. Supports both styles of config vars.
  271. Args:
  272. config: The AppConfig object to update attributes of.
  273. """
  274. # try to read the config.toml file into the config object
  275. toml_config = {}
  276. try:
  277. with open(toml_file, 'r', encoding='utf-8') as toml_contents:
  278. toml_config = toml.load(toml_contents)
  279. except FileNotFoundError:
  280. # the file is optional, we don't need to do anything
  281. return
  282. except toml.TomlDecodeError:
  283. logger.warning(
  284. 'Cannot parse config from toml, toml values have not been applied.',
  285. exc_info=False,
  286. )
  287. return
  288. # if there was an exception or core is not in the toml, try to use the old-style toml
  289. if 'core' not in toml_config:
  290. # re-use the env loader to set the config from env-style vars
  291. load_from_env(config, toml_config)
  292. return
  293. core_config = toml_config['core']
  294. try:
  295. # set llm config from the toml file
  296. llm_config = config.llm
  297. if 'llm' in toml_config:
  298. llm_config = LLMConfig(**toml_config['llm'])
  299. # set agent config from the toml file
  300. agent_config = config.agent
  301. if 'agent' in toml_config:
  302. agent_config = AgentConfig(**toml_config['agent'])
  303. # update the config object with the new values
  304. config = AppConfig(llm=llm_config, agent=agent_config, **core_config)
  305. except (TypeError, KeyError):
  306. logger.warning(
  307. 'Cannot parse config from toml, toml values have not been applied.',
  308. exc_info=False,
  309. )
  310. def finalize_config(config: AppConfig):
  311. """
  312. More tweaks to the config after it's been loaded.
  313. """
  314. # Set workspace_mount_path if not set by the user
  315. if config.workspace_mount_path is None:
  316. config.workspace_mount_path = os.path.abspath(config.workspace_base)
  317. config.workspace_base = os.path.abspath(config.workspace_base)
  318. # In local there is no sandbox, the workspace will have the same pwd as the host
  319. if config.sandbox_type == 'local':
  320. config.workspace_mount_path_in_sandbox = config.workspace_mount_path
  321. if config.workspace_mount_rewrite: # and not config.workspace_mount_path:
  322. # TODO why do we need to check if workspace_mount_path is None?
  323. base = config.workspace_base or os.getcwd()
  324. parts = config.workspace_mount_rewrite.split(':')
  325. config.workspace_mount_path = base.replace(parts[0], parts[1])
  326. if config.llm.embedding_base_url is None:
  327. config.llm.embedding_base_url = config.llm.base_url
  328. if config.use_host_network and platform.system() == 'Darwin':
  329. logger.warning(
  330. 'Please upgrade to Docker Desktop 4.29.0 or later to use host network mode on macOS. '
  331. 'See https://github.com/docker/roadmap/issues/238#issuecomment-2044688144 for more information.'
  332. )
  333. # make sure cache dir exists
  334. if config.cache_dir:
  335. pathlib.Path(config.cache_dir).mkdir(parents=True, exist_ok=True)
  336. config = AppConfig()
  337. load_from_toml(config)
  338. load_from_env(config, os.environ)
  339. finalize_config(config)
  340. # Utility function for command line --group argument
  341. def get_llm_config_arg(llm_config_arg: str):
  342. """
  343. Get a group of llm settings from the config file.
  344. A group in config.toml can look like this:
  345. ```
  346. [gpt-3.5-for-eval]
  347. model = 'gpt-3.5-turbo'
  348. api_key = '...'
  349. temperature = 0.5
  350. num_retries = 10
  351. ...
  352. ```
  353. The user-defined group name, like "gpt-3.5-for-eval", is the argument to this function. The function will load the LLMConfig object
  354. with the settings of this group, from the config file, and set it as the LLMConfig object for the app.
  355. Args:
  356. llm_config_arg: The group of llm settings to get from the config.toml file.
  357. Returns:
  358. LLMConfig: The LLMConfig object with the settings from the config file.
  359. """
  360. # keep only the name, just in case
  361. llm_config_arg = llm_config_arg.strip('[]')
  362. logger.info(f'Loading llm config from {llm_config_arg}')
  363. # load the toml file
  364. try:
  365. with open('config.toml', 'r', encoding='utf-8') as toml_file:
  366. toml_config = toml.load(toml_file)
  367. except FileNotFoundError as e:
  368. logger.error(f'Config file not found: {e}')
  369. return None
  370. except toml.TomlDecodeError as e:
  371. logger.error(f'Cannot parse llm group from {llm_config_arg}. Exception: {e}')
  372. return None
  373. # update the llm config with the specified section
  374. if llm_config_arg in toml_config:
  375. return LLMConfig(**toml_config[llm_config_arg])
  376. logger.debug(f'Loading from toml failed for {llm_config_arg}')
  377. return None
  378. # Command line arguments
  379. def get_parser():
  380. """
  381. Get the parser for the command line arguments.
  382. """
  383. parser = argparse.ArgumentParser(description='Run an agent with a specific task')
  384. parser.add_argument(
  385. '-d',
  386. '--directory',
  387. type=str,
  388. help='The working directory for the agent',
  389. )
  390. parser.add_argument(
  391. '-t', '--task', type=str, default='', help='The task for the agent to perform'
  392. )
  393. parser.add_argument(
  394. '-f',
  395. '--file',
  396. type=str,
  397. help='Path to a file containing the task. Overrides -t if both are provided.',
  398. )
  399. parser.add_argument(
  400. '-c',
  401. '--agent-cls',
  402. default=config.agent.name,
  403. type=str,
  404. help='The agent class to use',
  405. )
  406. parser.add_argument(
  407. '-m',
  408. '--model-name',
  409. default=config.llm.model,
  410. type=str,
  411. help='The (litellm) model name to use',
  412. )
  413. parser.add_argument(
  414. '-i',
  415. '--max-iterations',
  416. default=config.max_iterations,
  417. type=int,
  418. help='The maximum number of iterations to run the agent',
  419. )
  420. parser.add_argument(
  421. '-b',
  422. '--max-budget-per-task',
  423. default=config.max_budget_per_task,
  424. type=float,
  425. help='The maximum budget allowed per task, beyond which the agent will stop.',
  426. )
  427. parser.add_argument(
  428. '-n',
  429. '--max-chars',
  430. default=config.llm.max_chars,
  431. type=int,
  432. help='The maximum number of characters to send to and receive from LLM per task',
  433. )
  434. # --eval configs are for evaluations only
  435. parser.add_argument(
  436. '--eval-output-dir',
  437. default='evaluation/evaluation_outputs/outputs',
  438. type=str,
  439. help='The directory to save evaluation output',
  440. )
  441. parser.add_argument(
  442. '--eval-n-limit',
  443. default=None,
  444. type=int,
  445. help='The number of instances to evaluate',
  446. )
  447. parser.add_argument(
  448. '--eval-num-workers',
  449. default=4,
  450. type=int,
  451. help='The number of workers to use for evaluation',
  452. )
  453. parser.add_argument(
  454. '--eval-note',
  455. default=None,
  456. type=str,
  457. help='The note to add to the evaluation directory',
  458. )
  459. parser.add_argument(
  460. '-l',
  461. '--llm-config',
  462. default=None,
  463. type=str,
  464. help='The group of llm settings, e.g. a [llama3] section in the toml file. Overrides model if both are provided.',
  465. )
  466. return parser
  467. def parse_arguments():
  468. """
  469. Parse the command line arguments.
  470. """
  471. parser = get_parser()
  472. args, _ = parser.parse_known_args()
  473. if args.directory:
  474. config.workspace_base = os.path.abspath(args.directory)
  475. print(f'Setting workspace base to {config.workspace_base}')
  476. return args
  477. args = parse_arguments()