test_config.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540
  1. import os
  2. import pytest
  3. from opendevin.core.config import (
  4. AgentConfig,
  5. AppConfig,
  6. LLMConfig,
  7. UndefinedString,
  8. finalize_config,
  9. get_llm_config_arg,
  10. load_from_env,
  11. load_from_toml,
  12. )
  13. @pytest.fixture
  14. def setup_env():
  15. # Create old-style and new-style TOML files
  16. with open('old_style_config.toml', 'w') as f:
  17. f.write('[default]\nLLM_MODEL="GPT-4"\n')
  18. with open('new_style_config.toml', 'w') as f:
  19. f.write('[app]\nLLM_MODEL="GPT-3"\n')
  20. yield
  21. # Cleanup TOML files after the test
  22. os.remove('old_style_config.toml')
  23. os.remove('new_style_config.toml')
  24. @pytest.fixture
  25. def temp_toml_file(tmp_path):
  26. # Fixture to create a temporary directory and TOML file for testing
  27. tmp_toml_file = os.path.join(tmp_path, 'config.toml')
  28. yield tmp_toml_file
  29. @pytest.fixture
  30. def default_config(monkeypatch):
  31. # Fixture to provide a default AppConfig instance
  32. AppConfig.reset()
  33. yield AppConfig()
  34. def test_compat_env_to_config(monkeypatch, setup_env):
  35. # Use `monkeypatch` to set environment variables for this specific test
  36. monkeypatch.setenv('WORKSPACE_BASE', '/repos/opendevin/workspace')
  37. monkeypatch.setenv('LLM_API_KEY', 'sk-proj-rgMV0...')
  38. monkeypatch.setenv('LLM_MODEL', 'gpt-4o')
  39. monkeypatch.setenv('AGENT_MEMORY_MAX_THREADS', '4')
  40. monkeypatch.setenv('AGENT_MEMORY_ENABLED', 'True')
  41. monkeypatch.setenv('DEFAULT_AGENT', 'CodeActAgent')
  42. monkeypatch.setenv('SANDBOX_TIMEOUT', '10')
  43. config = AppConfig()
  44. load_from_env(config, os.environ)
  45. assert config.workspace_base == '/repos/opendevin/workspace'
  46. assert isinstance(config.get_llm_config(), LLMConfig)
  47. assert config.get_llm_config().api_key == 'sk-proj-rgMV0...'
  48. assert config.get_llm_config().model == 'gpt-4o'
  49. assert isinstance(config.get_agent_config(), AgentConfig)
  50. assert isinstance(config.get_agent_config().memory_max_threads, int)
  51. assert config.get_agent_config().memory_max_threads == 4
  52. assert config.get_agent_config().memory_enabled is True
  53. assert config.default_agent == 'CodeActAgent'
  54. assert config.sandbox.timeout == 10
  55. def test_load_from_old_style_env(monkeypatch, default_config):
  56. # Test loading configuration from old-style environment variables using monkeypatch
  57. monkeypatch.setenv('LLM_API_KEY', 'test-api-key')
  58. monkeypatch.setenv('AGENT_MEMORY_ENABLED', 'True')
  59. monkeypatch.setenv('DEFAULT_AGENT', 'PlannerAgent')
  60. monkeypatch.setenv('WORKSPACE_BASE', '/opt/files/workspace')
  61. monkeypatch.setenv('SANDBOX_CONTAINER_IMAGE', 'custom_image')
  62. load_from_env(default_config, os.environ)
  63. assert default_config.get_llm_config().api_key == 'test-api-key'
  64. assert default_config.get_agent_config().memory_enabled is True
  65. assert default_config.default_agent == 'PlannerAgent'
  66. assert default_config.workspace_base == '/opt/files/workspace'
  67. assert (
  68. default_config.workspace_mount_path is UndefinedString.UNDEFINED
  69. ) # before finalize_config
  70. assert (
  71. default_config.workspace_mount_path_in_sandbox is not UndefinedString.UNDEFINED
  72. )
  73. assert default_config.sandbox.container_image == 'custom_image'
  74. def test_load_from_new_style_toml(default_config, temp_toml_file):
  75. # Test loading configuration from a new-style TOML file
  76. with open(temp_toml_file, 'w', encoding='utf-8') as toml_file:
  77. toml_file.write(
  78. """
  79. [llm]
  80. model = "test-model"
  81. api_key = "toml-api-key"
  82. [llm.cheap]
  83. model = "some-cheap-model"
  84. api_key = "cheap-model-api-key"
  85. [agent]
  86. memory_enabled = true
  87. [agent.BrowsingAgent]
  88. llm_config = "cheap"
  89. memory_enabled = false
  90. [sandbox]
  91. timeout = 1
  92. [core]
  93. workspace_base = "/opt/files2/workspace"
  94. default_agent = "TestAgent"
  95. """
  96. )
  97. load_from_toml(default_config, temp_toml_file)
  98. # default llm & agent configs
  99. assert default_config.default_agent == 'TestAgent'
  100. assert default_config.get_llm_config().model == 'test-model'
  101. assert default_config.get_llm_config().api_key == 'toml-api-key'
  102. assert default_config.get_agent_config().memory_enabled is True
  103. # undefined agent config inherits default ones
  104. assert (
  105. default_config.get_llm_config_from_agent('CodeActAgent')
  106. == default_config.get_llm_config()
  107. )
  108. assert default_config.get_agent_config('CodeActAgent').memory_enabled is True
  109. # defined agent config overrides default ones
  110. assert default_config.get_llm_config_from_agent(
  111. 'BrowsingAgent'
  112. ) == default_config.get_llm_config('cheap')
  113. assert (
  114. default_config.get_llm_config_from_agent('BrowsingAgent').model
  115. == 'some-cheap-model'
  116. )
  117. assert default_config.get_agent_config('BrowsingAgent').memory_enabled is False
  118. assert default_config.workspace_base == '/opt/files2/workspace'
  119. assert default_config.sandbox.timeout == 1
  120. # before finalize_config, workspace_mount_path is UndefinedString.UNDEFINED if it was not set
  121. assert default_config.workspace_mount_path is UndefinedString.UNDEFINED
  122. assert (
  123. default_config.workspace_mount_path_in_sandbox is not UndefinedString.UNDEFINED
  124. )
  125. assert default_config.workspace_mount_path_in_sandbox == '/workspace'
  126. finalize_config(default_config)
  127. # after finalize_config, workspace_mount_path is set to the absolute path of workspace_base
  128. # if it was undefined
  129. assert default_config.workspace_mount_path == '/opt/files2/workspace'
  130. def test_compat_load_sandbox_from_toml(default_config: AppConfig, temp_toml_file: str):
  131. # test loading configuration from a new-style TOML file
  132. # uses a toml file with sandbox_vars instead of a sandbox section
  133. with open(temp_toml_file, 'w', encoding='utf-8') as toml_file:
  134. toml_file.write(
  135. """
  136. [llm]
  137. model = "test-model"
  138. [agent]
  139. memory_enabled = true
  140. [core]
  141. workspace_base = "/opt/files2/workspace"
  142. sandbox_timeout = 500
  143. sandbox_container_image = "node:14"
  144. sandbox_user_id = 1001
  145. default_agent = "TestAgent"
  146. """
  147. )
  148. load_from_toml(default_config, temp_toml_file)
  149. assert default_config.get_llm_config().model == 'test-model'
  150. assert default_config.get_llm_config_from_agent().model == 'test-model'
  151. assert default_config.default_agent == 'TestAgent'
  152. assert default_config.get_agent_config().memory_enabled is True
  153. assert default_config.workspace_base == '/opt/files2/workspace'
  154. assert default_config.sandbox.timeout == 500
  155. assert default_config.sandbox.container_image == 'node:14'
  156. assert default_config.sandbox.user_id == 1001
  157. assert default_config.workspace_mount_path_in_sandbox == '/workspace'
  158. finalize_config(default_config)
  159. # app config doesn't have fields sandbox_*
  160. assert not hasattr(default_config, 'sandbox_timeout')
  161. assert not hasattr(default_config, 'sandbox_container_image')
  162. assert not hasattr(default_config, 'sandbox_user_id')
  163. # after finalize_config, workspace_mount_path is set to the absolute path of workspace_base
  164. # if it was undefined
  165. assert default_config.workspace_mount_path == '/opt/files2/workspace'
  166. def test_env_overrides_compat_toml(monkeypatch, default_config, temp_toml_file):
  167. # test that environment variables override TOML values using monkeypatch
  168. # uses a toml file with sandbox_vars instead of a sandbox section
  169. with open(temp_toml_file, 'w', encoding='utf-8') as toml_file:
  170. toml_file.write("""
  171. [llm]
  172. model = "test-model"
  173. api_key = "toml-api-key"
  174. [core]
  175. workspace_base = "/opt/files3/workspace"
  176. disable_color = true
  177. sandbox_timeout = 500
  178. sandbox_user_id = 1001
  179. """)
  180. monkeypatch.setenv('LLM_API_KEY', 'env-api-key')
  181. monkeypatch.setenv('WORKSPACE_BASE', 'UNDEFINED')
  182. monkeypatch.setenv('SANDBOX_TIMEOUT', '1000')
  183. monkeypatch.setenv('SANDBOX_USER_ID', '1002')
  184. load_from_toml(default_config, temp_toml_file)
  185. # before finalize_config, workspace_mount_path is UndefinedString.UNDEFINED if it was not set
  186. assert default_config.workspace_mount_path is UndefinedString.UNDEFINED
  187. load_from_env(default_config, os.environ)
  188. assert os.environ.get('LLM_MODEL') is None
  189. assert default_config.get_llm_config().model == 'test-model'
  190. assert default_config.get_llm_config('llm').model == 'test-model'
  191. assert default_config.get_llm_config_from_agent().model == 'test-model'
  192. assert default_config.get_llm_config().api_key == 'env-api-key'
  193. # after we set workspace_base to 'UNDEFINED' in the environment,
  194. # workspace_base should be set to that
  195. # workspace_mount path is still UndefinedString.UNDEFINED
  196. assert default_config.workspace_base is not UndefinedString.UNDEFINED
  197. assert default_config.workspace_base == 'UNDEFINED'
  198. assert default_config.workspace_mount_path is UndefinedString.UNDEFINED
  199. assert default_config.workspace_mount_path == 'UNDEFINED'
  200. assert default_config.disable_color is True
  201. assert default_config.sandbox.timeout == 1000
  202. assert default_config.sandbox.user_id == 1002
  203. finalize_config(default_config)
  204. # after finalize_config, workspace_mount_path is set to absolute path of workspace_base if it was undefined
  205. assert default_config.workspace_mount_path == os.getcwd() + '/UNDEFINED'
  206. def test_env_overrides_sandbox_toml(monkeypatch, default_config, temp_toml_file):
  207. # test that environment variables override TOML values using monkeypatch
  208. # uses a toml file with a sandbox section
  209. with open(temp_toml_file, 'w', encoding='utf-8') as toml_file:
  210. toml_file.write("""
  211. [llm]
  212. model = "test-model"
  213. api_key = "toml-api-key"
  214. [core]
  215. workspace_base = "/opt/files3/workspace"
  216. [sandbox]
  217. timeout = 500
  218. user_id = 1001
  219. """)
  220. monkeypatch.setenv('LLM_API_KEY', 'env-api-key')
  221. monkeypatch.setenv('WORKSPACE_BASE', 'UNDEFINED')
  222. monkeypatch.setenv('SANDBOX_TIMEOUT', '1000')
  223. monkeypatch.setenv('SANDBOX_USER_ID', '1002')
  224. load_from_toml(default_config, temp_toml_file)
  225. # before finalize_config, workspace_mount_path is UndefinedString.UNDEFINED if it was not set
  226. assert default_config.workspace_mount_path is UndefinedString.UNDEFINED
  227. # before load_from_env, values are set to the values from the toml file
  228. assert default_config.get_llm_config().api_key == 'toml-api-key'
  229. assert default_config.sandbox.timeout == 500
  230. assert default_config.sandbox.user_id == 1001
  231. load_from_env(default_config, os.environ)
  232. # values from env override values from toml
  233. assert os.environ.get('LLM_MODEL') is None
  234. assert default_config.get_llm_config().model == 'test-model'
  235. assert default_config.get_llm_config().api_key == 'env-api-key'
  236. assert default_config.sandbox.timeout == 1000
  237. assert default_config.sandbox.user_id == 1002
  238. finalize_config(default_config)
  239. # after finalize_config, workspace_mount_path is set to absolute path of workspace_base if it was undefined
  240. assert default_config.workspace_mount_path == os.getcwd() + '/UNDEFINED'
  241. def test_sandbox_config_from_toml(default_config, temp_toml_file):
  242. # Test loading configuration from a new-style TOML file
  243. with open(temp_toml_file, 'w', encoding='utf-8') as toml_file:
  244. toml_file.write(
  245. """
  246. [core]
  247. workspace_base = "/opt/files/workspace"
  248. [llm]
  249. model = "test-model"
  250. [sandbox]
  251. timeout = 1
  252. container_image = "custom_image"
  253. user_id = 1001
  254. """
  255. )
  256. load_from_toml(default_config, temp_toml_file)
  257. load_from_env(default_config, os.environ)
  258. finalize_config(default_config)
  259. assert default_config.get_llm_config().model == 'test-model'
  260. assert default_config.sandbox.timeout == 1
  261. assert default_config.sandbox.container_image == 'custom_image'
  262. assert default_config.sandbox.user_id == 1001
  263. def test_defaults_dict_after_updates(default_config):
  264. # Test that `defaults_dict` retains initial values after updates.
  265. initial_defaults = default_config.defaults_dict
  266. assert (
  267. initial_defaults['workspace_mount_path']['default'] is UndefinedString.UNDEFINED
  268. )
  269. assert initial_defaults['default_agent']['default'] == 'CodeActAgent'
  270. updated_config = AppConfig()
  271. updated_config.get_llm_config().api_key = 'updated-api-key'
  272. updated_config.get_llm_config('llm').api_key = 'updated-api-key'
  273. updated_config.get_llm_config_from_agent('agent').api_key = 'updated-api-key'
  274. updated_config.get_llm_config_from_agent('PlannerAgent').api_key = 'updated-api-key'
  275. updated_config.default_agent = 'PlannerAgent'
  276. defaults_after_updates = updated_config.defaults_dict
  277. assert defaults_after_updates['default_agent']['default'] == 'CodeActAgent'
  278. assert (
  279. defaults_after_updates['workspace_mount_path']['default']
  280. is UndefinedString.UNDEFINED
  281. )
  282. assert defaults_after_updates['sandbox']['timeout']['default'] == 120
  283. assert (
  284. defaults_after_updates['sandbox']['container_image']['default']
  285. == 'nikolaik/python-nodejs:python3.11-nodejs22'
  286. )
  287. assert defaults_after_updates == initial_defaults
  288. def test_invalid_toml_format(monkeypatch, temp_toml_file, default_config):
  289. # Invalid TOML format doesn't break the configuration
  290. monkeypatch.setenv('LLM_MODEL', 'gpt-5-turbo-1106')
  291. monkeypatch.setenv('WORKSPACE_MOUNT_PATH', '/home/user/project')
  292. monkeypatch.delenv('LLM_API_KEY', raising=False)
  293. with open(temp_toml_file, 'w', encoding='utf-8') as toml_file:
  294. toml_file.write('INVALID TOML CONTENT')
  295. load_from_toml(default_config)
  296. load_from_env(default_config, os.environ)
  297. default_config.jwt_secret = None # prevent leak
  298. for llm in default_config.llms.values():
  299. llm.api_key = None # prevent leak
  300. assert default_config.get_llm_config().model == 'gpt-5-turbo-1106'
  301. assert default_config.get_llm_config().custom_llm_provider is None
  302. assert default_config.workspace_mount_path == '/home/user/project'
  303. def test_finalize_config(default_config):
  304. # Test finalize config
  305. assert default_config.workspace_mount_path is UndefinedString.UNDEFINED
  306. finalize_config(default_config)
  307. assert default_config.workspace_mount_path == os.path.abspath(
  308. default_config.workspace_base
  309. )
  310. # tests for workspace, mount path, path in sandbox, cache dir
  311. def test_workspace_mount_path_default(default_config):
  312. assert default_config.workspace_mount_path is UndefinedString.UNDEFINED
  313. finalize_config(default_config)
  314. assert default_config.workspace_mount_path == os.path.abspath(
  315. default_config.workspace_base
  316. )
  317. def test_workspace_mount_rewrite(default_config, monkeypatch):
  318. default_config.workspace_base = '/home/user/project'
  319. default_config.workspace_mount_rewrite = '/home/user:/sandbox'
  320. monkeypatch.setattr('os.getcwd', lambda: '/current/working/directory')
  321. finalize_config(default_config)
  322. assert default_config.workspace_mount_path == '/sandbox/project'
  323. def test_embedding_base_url_default(default_config):
  324. default_config.get_llm_config().base_url = 'https://api.exampleapi.com'
  325. finalize_config(default_config)
  326. assert (
  327. default_config.get_llm_config().embedding_base_url
  328. == 'https://api.exampleapi.com'
  329. )
  330. def test_cache_dir_creation(default_config, tmpdir):
  331. default_config.cache_dir = str(tmpdir.join('test_cache'))
  332. finalize_config(default_config)
  333. assert os.path.exists(default_config.cache_dir)
  334. def test_api_keys_repr_str():
  335. # Test LLMConfig
  336. llm_config = LLMConfig(
  337. api_key='my_api_key',
  338. aws_access_key_id='my_access_key',
  339. aws_secret_access_key='my_secret_key',
  340. )
  341. assert "api_key='******'" in repr(llm_config)
  342. assert "aws_access_key_id='******'" in repr(llm_config)
  343. assert "aws_secret_access_key='******'" in repr(llm_config)
  344. assert "api_key='******'" in str(llm_config)
  345. assert "aws_access_key_id='******'" in str(llm_config)
  346. assert "aws_secret_access_key='******'" in str(llm_config)
  347. # Check that no other attrs in LLMConfig have 'key' or 'token' in their name
  348. # This will fail when new attrs are added, and attract attention
  349. known_key_token_attrs_llm = [
  350. 'api_key',
  351. 'aws_access_key_id',
  352. 'aws_secret_access_key',
  353. 'input_cost_per_token',
  354. 'output_cost_per_token',
  355. ]
  356. for attr_name in dir(LLMConfig):
  357. if (
  358. not attr_name.startswith('__')
  359. and attr_name not in known_key_token_attrs_llm
  360. ):
  361. assert (
  362. 'key' not in attr_name.lower()
  363. ), f"Unexpected attribute '{attr_name}' contains 'key' in LLMConfig"
  364. assert (
  365. 'token' not in attr_name.lower() or 'tokens' in attr_name.lower()
  366. ), f"Unexpected attribute '{attr_name}' contains 'token' in LLMConfig"
  367. # Test AgentConfig
  368. # No attrs in AgentConfig have 'key' or 'token' in their name
  369. agent_config = AgentConfig(memory_enabled=True, memory_max_threads=4)
  370. for attr_name in dir(AgentConfig):
  371. if not attr_name.startswith('__'):
  372. assert (
  373. 'key' not in attr_name.lower()
  374. ), f"Unexpected attribute '{attr_name}' contains 'key' in AgentConfig"
  375. assert (
  376. 'token' not in attr_name.lower() or 'tokens' in attr_name.lower()
  377. ), f"Unexpected attribute '{attr_name}' contains 'token' in AgentConfig"
  378. # Test AppConfig
  379. app_config = AppConfig(
  380. llms={'llm': llm_config},
  381. agents={'agent': agent_config},
  382. e2b_api_key='my_e2b_api_key',
  383. jwt_secret='my_jwt_secret',
  384. )
  385. assert "e2b_api_key='******'" in repr(app_config)
  386. assert "e2b_api_key='******'" in str(app_config)
  387. assert "jwt_secret='******'" in repr(app_config)
  388. assert "jwt_secret='******'" in str(app_config)
  389. # Check that no other attrs in AppConfig have 'key' or 'token' in their name
  390. # This will fail when new attrs are added, and attract attention
  391. known_key_token_attrs_app = ['e2b_api_key']
  392. for attr_name in dir(AppConfig):
  393. if (
  394. not attr_name.startswith('__')
  395. and attr_name not in known_key_token_attrs_app
  396. ):
  397. assert (
  398. 'key' not in attr_name.lower()
  399. ), f"Unexpected attribute '{attr_name}' contains 'key' in AppConfig"
  400. assert (
  401. 'token' not in attr_name.lower() or 'tokens' in attr_name.lower()
  402. ), f"Unexpected attribute '{attr_name}' contains 'token' in AppConfig"
  403. def test_max_iterations_and_max_budget_per_task_from_toml(temp_toml_file):
  404. temp_toml = """
  405. [core]
  406. max_iterations = 100
  407. max_budget_per_task = 4.0
  408. """
  409. config = AppConfig()
  410. with open(temp_toml_file, 'w') as f:
  411. f.write(temp_toml)
  412. load_from_toml(config, temp_toml_file)
  413. assert config.max_iterations == 100
  414. assert config.max_budget_per_task == 4.0
  415. def test_get_llm_config_arg(temp_toml_file):
  416. temp_toml = """
  417. [core]
  418. max_iterations = 100
  419. max_budget_per_task = 4.0
  420. [llm.gpt3]
  421. model="gpt-3.5-turbo"
  422. api_key="redacted"
  423. embedding_model="openai"
  424. [llm.gpt4o]
  425. model="gpt-4o"
  426. api_key="redacted"
  427. embedding_model="openai"
  428. """
  429. with open(temp_toml_file, 'w') as f:
  430. f.write(temp_toml)
  431. llm_config = get_llm_config_arg('gpt3', temp_toml_file)
  432. assert llm_config.model == 'gpt-3.5-turbo'
  433. assert llm_config.embedding_model == 'openai'