run_infer.py 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251
  1. import asyncio
  2. import json
  3. import os
  4. from typing import Any
  5. import browsergym.miniwob # noqa F401 register miniwob 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. codeact_user_response,
  12. compatibility_for_eval_history_pairs,
  13. make_metadata,
  14. prepare_dataset,
  15. reset_logger_for_multiprocessing,
  16. run_evaluation,
  17. update_llm_config_for_completions_logging,
  18. )
  19. from openhands.controller.state.state import State
  20. from openhands.core.config import (
  21. AppConfig,
  22. SandboxConfig,
  23. get_llm_config_arg,
  24. parse_arguments,
  25. )
  26. from openhands.core.logger import openhands_logger as logger
  27. from openhands.core.main import create_runtime, run_controller
  28. from openhands.events.action import (
  29. BrowseInteractiveAction,
  30. CmdRunAction,
  31. MessageAction,
  32. )
  33. from openhands.events.observation import (
  34. BrowserOutputObservation,
  35. CmdOutputObservation,
  36. )
  37. from openhands.runtime.base import Runtime
  38. from openhands.runtime.browser.browser_env import (
  39. BROWSER_EVAL_GET_GOAL_ACTION,
  40. BROWSER_EVAL_GET_REWARDS_ACTION,
  41. )
  42. from openhands.utils.async_utils import call_async_from_sync
  43. SUPPORTED_AGENT_CLS = {'BrowsingAgent', 'CodeActAgent'}
  44. AGENT_CLS_TO_FAKE_USER_RESPONSE_FN = {
  45. 'CodeActAgent': codeact_user_response,
  46. 'BrowsingAgent': 'Continue the task. IMPORTANT: do not talk to the user until you have finished the task',
  47. }
  48. def get_config(
  49. metadata: EvalMetadata,
  50. env_id: str,
  51. ) -> AppConfig:
  52. config = AppConfig(
  53. default_agent=metadata.agent_class,
  54. run_as_openhands=False,
  55. runtime=os.environ.get('RUNTIME', 'eventstream'),
  56. max_iterations=metadata.max_iterations,
  57. sandbox=SandboxConfig(
  58. base_container_image='xingyaoww/od-eval-miniwob:v1.0',
  59. enable_auto_lint=True,
  60. use_host_network=False,
  61. browsergym_eval_env=env_id,
  62. api_key=os.environ.get('ALLHANDS_API_KEY', None),
  63. remote_runtime_api_url=os.environ.get('SANDBOX_REMOTE_RUNTIME_API_URL'),
  64. remote_runtime_init_timeout=1800,
  65. keep_runtime_alive=False,
  66. timeout=120,
  67. remote_runtime_init_timeout=1800,
  68. ),
  69. # do not mount workspace
  70. workspace_base=None,
  71. workspace_mount_path=None,
  72. )
  73. config.set_llm_config(
  74. update_llm_config_for_completions_logging(
  75. metadata.llm_config, metadata.eval_output_dir, env_id
  76. )
  77. )
  78. return config
  79. def initialize_runtime(
  80. runtime: Runtime,
  81. ) -> tuple[str, BrowserOutputObservation]:
  82. """Initialize the runtime for the agent.
  83. This function is called before the runtime is used to run the agent.
  84. """
  85. logger.info(f"{'-' * 50} BEGIN Runtime Initialization Fn {'-' * 50}")
  86. obs: CmdOutputObservation
  87. # Set instance id
  88. action = CmdRunAction(command='mkdir -p /workspace')
  89. logger.info(action, extra={'msg_type': 'ACTION'})
  90. obs = runtime.run_action(action)
  91. assert obs.exit_code == 0
  92. action = BrowseInteractiveAction(browser_actions=BROWSER_EVAL_GET_GOAL_ACTION)
  93. logger.info(action, extra={'msg_type': 'ACTION'})
  94. obs = runtime.run_action(action)
  95. logger.info(obs, extra={'msg_type': 'OBSERVATION'})
  96. goal = obs.content
  97. # Run noop to get the initial browser observation (e.g., the page URL & content)
  98. action = BrowseInteractiveAction(browser_actions='noop(1000)')
  99. logger.info(action, extra={'msg_type': 'ACTION'})
  100. obs = runtime.run_action(action)
  101. logger.info(obs, extra={'msg_type': 'OBSERVATION'})
  102. logger.info(f"{'-' * 50} END Runtime Initialization Fn {'-' * 50}")
  103. return goal, obs
  104. def complete_runtime(
  105. runtime: Runtime,
  106. ) -> dict[str, Any]:
  107. """Complete the runtime for the agent.
  108. This function is called before the runtime is used to run the agent.
  109. If you need to do something in the sandbox to get the correctness metric after
  110. the agent has run, modify this function.
  111. """
  112. logger.info(f"{'-' * 50} BEGIN Runtime Completion Fn {'-' * 50}")
  113. obs: CmdOutputObservation
  114. action = BrowseInteractiveAction(browser_actions=BROWSER_EVAL_GET_REWARDS_ACTION)
  115. logger.info(action, extra={'msg_type': 'ACTION'})
  116. obs = runtime.run_action(action)
  117. logger.info(obs, extra={'msg_type': 'OBSERVATION'})
  118. logger.info(f"{'-' * 50} END Runtime Completion Fn {'-' * 50}")
  119. return {
  120. 'rewards': json.loads(obs.content),
  121. }
  122. def process_instance(
  123. instance: pd.Series,
  124. metadata: EvalMetadata,
  125. reset_logger: bool = True,
  126. ) -> EvalOutput:
  127. env_id = instance.instance_id
  128. config = get_config(metadata, env_id)
  129. # Setup the logger properly, so you can run multi-processing to parallelize the evaluation
  130. if reset_logger:
  131. log_dir = os.path.join(metadata.eval_output_dir, 'infer_logs')
  132. reset_logger_for_multiprocessing(logger, env_id, log_dir)
  133. else:
  134. logger.info(f'Starting evaluation for instance {env_id}.')
  135. runtime = create_runtime(config)
  136. call_async_from_sync(runtime.connect)
  137. task_str, obs = initialize_runtime(runtime)
  138. task_str += (
  139. f'\nInitial browser state (output of `noop(1000)`):\n{obs.get_agent_obs_text()}'
  140. )
  141. state: State | None = asyncio.run(
  142. run_controller(
  143. config=config,
  144. initial_user_action=MessageAction(
  145. content=task_str
  146. ), # take output from initialize_runtime
  147. runtime=runtime,
  148. fake_user_response_fn=AGENT_CLS_TO_FAKE_USER_RESPONSE_FN[
  149. metadata.agent_class
  150. ],
  151. )
  152. )
  153. # ======= Attempt to evaluate the agent's environment impact =======
  154. # If you are working on some simpler benchmark that only evaluates the final model output (e.g., in a MessageAction)
  155. # You can simply get the LAST `MessageAction` from the returned `state.history` and parse it for evaluation.
  156. if state is None:
  157. raise ValueError('State should not be None.')
  158. metrics = state.metrics.get() if state.metrics else None
  159. # Instruction is the first message from the USER
  160. instruction = ''
  161. for event in state.history:
  162. if isinstance(event, MessageAction):
  163. instruction = event.content
  164. break
  165. return_val = complete_runtime(runtime)
  166. logger.info(f'Return value from complete_runtime: {return_val}')
  167. reward = max(return_val['rewards'], default=0)
  168. # history is now available as a stream of events, rather than list of pairs of (Action, Observation)
  169. # for compatibility with the existing output format, we can remake the pairs here
  170. # remove when it becomes unnecessary
  171. histories = compatibility_for_eval_history_pairs(state.history)
  172. # Save the output
  173. output = EvalOutput(
  174. instance_id=env_id,
  175. instruction=instruction,
  176. metadata=metadata,
  177. history=histories,
  178. metrics=metrics,
  179. error=state.last_error if state and state.last_error else None,
  180. test_result={
  181. 'reward': reward,
  182. },
  183. )
  184. return output
  185. if __name__ == '__main__':
  186. args = parse_arguments()
  187. dataset = pd.DataFrame(
  188. {
  189. 'instance_id': [
  190. id
  191. for id in gym.envs.registry.keys()
  192. if id.startswith('browsergym/miniwob')
  193. ]
  194. }
  195. )
  196. llm_config = None
  197. if args.llm_config:
  198. llm_config = get_llm_config_arg(args.llm_config)
  199. if llm_config is None:
  200. raise ValueError(f'Could not find LLM config: --llm_config {args.llm_config}')
  201. metadata = make_metadata(
  202. llm_config,
  203. 'miniwob',
  204. args.agent_cls,
  205. args.max_iterations,
  206. args.eval_note,
  207. args.eval_output_dir,
  208. )
  209. output_file = os.path.join(metadata.eval_output_dir, 'output.jsonl')
  210. instances = prepare_dataset(dataset, output_file, args.eval_n_limit)
  211. run_evaluation(
  212. instances, metadata, output_file, args.eval_num_workers, process_instance
  213. )