run_infer.py 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233
  1. import asyncio
  2. import json
  3. import os
  4. from typing import Any
  5. import browsergym.webarena # noqa F401 register webarena tasks as gym environments
  6. import gymnasium as gym
  7. import pandas as pd
  8. from evaluation.utils.shared import (
  9. EvalMetadata,
  10. EvalOutput,
  11. make_metadata,
  12. prepare_dataset,
  13. reset_logger_for_multiprocessing,
  14. run_evaluation,
  15. )
  16. from opendevin.controller.state.state import State
  17. from opendevin.core.config import (
  18. AppConfig,
  19. SandboxConfig,
  20. get_llm_config_arg,
  21. parse_arguments,
  22. )
  23. from opendevin.core.logger import opendevin_logger as logger
  24. from opendevin.core.main import create_runtime, run_controller
  25. from opendevin.events.action import (
  26. BrowseInteractiveAction,
  27. CmdRunAction,
  28. MessageAction,
  29. )
  30. from opendevin.events.observation import CmdOutputObservation
  31. from opendevin.runtime.browser.browser_env import (
  32. BROWSER_EVAL_GET_GOAL_ACTION,
  33. BROWSER_EVAL_GET_REWARDS_ACTION,
  34. )
  35. from opendevin.runtime.runtime import Runtime
  36. SUPPORTED_AGENT_CLS = {'BrowsingAgent'}
  37. def get_config(
  38. metadata: EvalMetadata,
  39. env_id: str,
  40. ) -> AppConfig:
  41. base_url = os.environ.get('WEBARENA_BASE_URL', None)
  42. openai_api_key = os.environ.get('OPENAI_API_KEY', None)
  43. assert base_url is not None, 'WEBARENA_BASE_URL must be set'
  44. assert openai_api_key is not None, 'OPENAI_API_KEY must be set'
  45. config = AppConfig(
  46. default_agent=metadata.agent_class,
  47. run_as_devin=False,
  48. runtime='eventstream',
  49. max_iterations=metadata.max_iterations,
  50. sandbox=SandboxConfig(
  51. container_image='python:3.11-bookworm',
  52. enable_auto_lint=True,
  53. use_host_network=False,
  54. browsergym_eval_env=env_id,
  55. od_runtime_startup_env_vars={
  56. 'BASE_URL': base_url,
  57. 'OPENAI_API_KEY': openai_api_key,
  58. 'SHOPPING': f'{base_url}:7770/',
  59. 'SHOPPING_ADMIN': f'{base_url}:7780/admin',
  60. 'REDDIT': f'{base_url}:9999',
  61. 'GITLAB': f'{base_url}:8023',
  62. 'WIKIPEDIA': f'{base_url}:8888/wikipedia_en_all_maxi_2022-05/A/User:The_other_Kiwix_guy/Landing',
  63. 'MAP': f'{base_url}:3000',
  64. 'HOMEPAGE': f'{base_url}:4399',
  65. },
  66. ),
  67. # do not mount workspace
  68. workspace_base=None,
  69. workspace_mount_path=None,
  70. )
  71. config.set_llm_config(metadata.llm_config)
  72. return config
  73. async def initialize_runtime(
  74. runtime: Runtime,
  75. ) -> dict:
  76. """Initialize the runtime for the agent.
  77. This function is called before the runtime is used to run the agent.
  78. """
  79. logger.info(f"{'-' * 50} BEGIN Runtime Initialization Fn {'-' * 50}")
  80. obs: CmdOutputObservation
  81. # Set instance id
  82. action = CmdRunAction(command='mkdir -p /workspace')
  83. logger.info(action, extra={'msg_type': 'ACTION'})
  84. obs = await runtime.run_action(action)
  85. assert obs.exit_code == 0
  86. action = BrowseInteractiveAction(browser_actions=BROWSER_EVAL_GET_GOAL_ACTION)
  87. logger.info(action, extra={'msg_type': 'ACTION'})
  88. obs = await runtime.run_action(action)
  89. logger.info(obs, extra={'msg_type': 'OBSERVATION'})
  90. goal = obs.content
  91. logger.info(f"{'-' * 50} END Runtime Initialization Fn {'-' * 50}")
  92. return goal
  93. async def complete_runtime(
  94. runtime: Runtime,
  95. ) -> dict[str, Any]:
  96. """Complete the runtime for the agent.
  97. This function is called before the runtime is used to run the agent.
  98. If you need to do something in the sandbox to get the correctness metric after
  99. the agent has run, modify this function.
  100. """
  101. logger.info(f"{'-' * 50} BEGIN Runtime Completion Fn {'-' * 50}")
  102. obs: CmdOutputObservation
  103. action = BrowseInteractiveAction(browser_actions=BROWSER_EVAL_GET_REWARDS_ACTION)
  104. logger.info(action, extra={'msg_type': 'ACTION'})
  105. obs = await runtime.run_action(action)
  106. logger.info(obs, extra={'msg_type': 'OBSERVATION'})
  107. logger.info(f"{'-' * 50} END Runtime Completion Fn {'-' * 50}")
  108. return {
  109. 'rewards': json.loads(obs.content),
  110. }
  111. async def process_instance(
  112. instance: pd.Series,
  113. metadata: EvalMetadata,
  114. reset_logger: bool = True,
  115. ):
  116. env_id = instance.instance_id
  117. config = get_config(metadata, env_id)
  118. # Setup the logger properly, so you can run multi-processing to parallelize the evaluation
  119. if reset_logger:
  120. log_dir = os.path.join(metadata.eval_output_dir, 'infer_logs')
  121. reset_logger_for_multiprocessing(logger, env_id, log_dir)
  122. else:
  123. logger.info(f'Starting evaluation for instance {env_id}.')
  124. runtime = await create_runtime(config, sid=env_id)
  125. task_str = await initialize_runtime(runtime)
  126. state: State | None = await run_controller(
  127. config=config,
  128. task_str=task_str,
  129. runtime=runtime,
  130. )
  131. # ======= Attempt to evaluate the agent's environment impact =======
  132. # If you are working on some simpler benchmark that only evaluates the final model output (e.g., in a MessageAction)
  133. # You can simply get the LAST `MessageAction` from the returned `state.history` and parse it for evaluation.
  134. if state is None:
  135. raise ValueError('State should not be None.')
  136. metrics = state.metrics.get() if state.metrics else None
  137. # Instruction is the first message from the USER
  138. instruction = ''
  139. for event in state.history.get_events():
  140. if isinstance(event, MessageAction):
  141. instruction = event.content
  142. break
  143. return_val = await complete_runtime(runtime)
  144. logger.info(f'Return value from complete_runtime: {return_val}')
  145. reward = max(return_val['rewards'])
  146. # history is now available as a stream of events, rather than list of pairs of (Action, Observation)
  147. # for compatibility with the existing output format, we can remake the pairs here
  148. # remove when it becomes unnecessary
  149. histories = state.history.compatibility_for_eval_history_pairs()
  150. # Save the output
  151. output = EvalOutput(
  152. instance_id=env_id,
  153. instruction=instruction,
  154. metadata=metadata,
  155. history=histories,
  156. metrics=metrics,
  157. error=state.last_error if state and state.last_error else None,
  158. test_result={
  159. 'reward': reward,
  160. },
  161. )
  162. return output
  163. if __name__ == '__main__':
  164. args = parse_arguments()
  165. dataset = pd.DataFrame(
  166. {
  167. 'instance_id': [
  168. id
  169. for id in gym.envs.registry.keys()
  170. if id.startswith('browsergym/webarena')
  171. ]
  172. }
  173. )
  174. llm_config = None
  175. if args.llm_config:
  176. llm_config = get_llm_config_arg(args.llm_config)
  177. if llm_config is None:
  178. raise ValueError(f'Could not find LLM config: --llm_config {args.llm_config}')
  179. metadata = make_metadata(
  180. llm_config,
  181. args.dataset_name,
  182. args.agent_cls,
  183. args.max_iterations,
  184. args.eval_note,
  185. args.eval_output_dir,
  186. )
  187. output_file = os.path.join(metadata.eval_output_dir, 'output.jsonl')
  188. instances = prepare_dataset(dataset, output_file, args.eval_n_limit)
  189. asyncio.run(
  190. run_evaluation(
  191. instances,
  192. metadata,
  193. output_file,
  194. args.eval_num_workers,
  195. process_instance,
  196. )
  197. )