run_infer.py 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250
  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. ),
  68. # do not mount workspace
  69. workspace_base=None,
  70. workspace_mount_path=None,
  71. )
  72. config.set_llm_config(
  73. update_llm_config_for_completions_logging(
  74. metadata.llm_config, metadata.eval_output_dir, env_id
  75. )
  76. )
  77. return config
  78. def initialize_runtime(
  79. runtime: Runtime,
  80. ) -> tuple[str, BrowserOutputObservation]:
  81. """Initialize the runtime for the agent.
  82. This function is called before the runtime is used to run the agent.
  83. """
  84. logger.info(f"{'-' * 50} BEGIN Runtime Initialization Fn {'-' * 50}")
  85. obs: CmdOutputObservation
  86. # Set instance id
  87. action = CmdRunAction(command='mkdir -p /workspace')
  88. logger.info(action, extra={'msg_type': 'ACTION'})
  89. obs = runtime.run_action(action)
  90. assert obs.exit_code == 0
  91. action = BrowseInteractiveAction(browser_actions=BROWSER_EVAL_GET_GOAL_ACTION)
  92. logger.info(action, extra={'msg_type': 'ACTION'})
  93. obs = runtime.run_action(action)
  94. logger.info(obs, extra={'msg_type': 'OBSERVATION'})
  95. goal = obs.content
  96. # Run noop to get the initial browser observation (e.g., the page URL & content)
  97. action = BrowseInteractiveAction(browser_actions='noop(1000)')
  98. logger.info(action, extra={'msg_type': 'ACTION'})
  99. obs = runtime.run_action(action)
  100. logger.info(obs, extra={'msg_type': 'OBSERVATION'})
  101. logger.info(f"{'-' * 50} END Runtime Initialization Fn {'-' * 50}")
  102. return goal, obs
  103. def complete_runtime(
  104. runtime: Runtime,
  105. ) -> dict[str, Any]:
  106. """Complete the runtime for the agent.
  107. This function is called before the runtime is used to run the agent.
  108. If you need to do something in the sandbox to get the correctness metric after
  109. the agent has run, modify this function.
  110. """
  111. logger.info(f"{'-' * 50} BEGIN Runtime Completion Fn {'-' * 50}")
  112. obs: CmdOutputObservation
  113. action = BrowseInteractiveAction(browser_actions=BROWSER_EVAL_GET_REWARDS_ACTION)
  114. logger.info(action, extra={'msg_type': 'ACTION'})
  115. obs = runtime.run_action(action)
  116. logger.info(obs, extra={'msg_type': 'OBSERVATION'})
  117. logger.info(f"{'-' * 50} END Runtime Completion Fn {'-' * 50}")
  118. return {
  119. 'rewards': json.loads(obs.content),
  120. }
  121. def process_instance(
  122. instance: pd.Series,
  123. metadata: EvalMetadata,
  124. reset_logger: bool = True,
  125. ) -> EvalOutput:
  126. env_id = instance.instance_id
  127. config = get_config(metadata, env_id)
  128. # Setup the logger properly, so you can run multi-processing to parallelize the evaluation
  129. if reset_logger:
  130. log_dir = os.path.join(metadata.eval_output_dir, 'infer_logs')
  131. reset_logger_for_multiprocessing(logger, env_id, log_dir)
  132. else:
  133. logger.info(f'Starting evaluation for instance {env_id}.')
  134. runtime = create_runtime(config)
  135. call_async_from_sync(runtime.connect)
  136. task_str, obs = initialize_runtime(runtime)
  137. task_str += (
  138. f'\nInitial browser state (output of `noop(1000)`):\n{obs.get_agent_obs_text()}'
  139. )
  140. state: State | None = asyncio.run(
  141. run_controller(
  142. config=config,
  143. initial_user_action=MessageAction(
  144. content=task_str
  145. ), # take output from initialize_runtime
  146. runtime=runtime,
  147. fake_user_response_fn=AGENT_CLS_TO_FAKE_USER_RESPONSE_FN[
  148. metadata.agent_class
  149. ],
  150. )
  151. )
  152. # ======= Attempt to evaluate the agent's environment impact =======
  153. # If you are working on some simpler benchmark that only evaluates the final model output (e.g., in a MessageAction)
  154. # You can simply get the LAST `MessageAction` from the returned `state.history` and parse it for evaluation.
  155. if state is None:
  156. raise ValueError('State should not be None.')
  157. metrics = state.metrics.get() if state.metrics else None
  158. # Instruction is the first message from the USER
  159. instruction = ''
  160. for event in state.history:
  161. if isinstance(event, MessageAction):
  162. instruction = event.content
  163. break
  164. return_val = complete_runtime(runtime)
  165. logger.info(f'Return value from complete_runtime: {return_val}')
  166. reward = max(return_val['rewards'], default=0)
  167. # history is now available as a stream of events, rather than list of pairs of (Action, Observation)
  168. # for compatibility with the existing output format, we can remake the pairs here
  169. # remove when it becomes unnecessary
  170. histories = compatibility_for_eval_history_pairs(state.history)
  171. # Save the output
  172. output = EvalOutput(
  173. instance_id=env_id,
  174. instruction=instruction,
  175. metadata=metadata,
  176. history=histories,
  177. metrics=metrics,
  178. error=state.last_error if state and state.last_error else None,
  179. test_result={
  180. 'reward': reward,
  181. },
  182. )
  183. return output
  184. if __name__ == '__main__':
  185. args = parse_arguments()
  186. dataset = pd.DataFrame(
  187. {
  188. 'instance_id': [
  189. id
  190. for id in gym.envs.registry.keys()
  191. if id.startswith('browsergym/miniwob')
  192. ]
  193. }
  194. )
  195. llm_config = None
  196. if args.llm_config:
  197. llm_config = get_llm_config_arg(args.llm_config)
  198. if llm_config is None:
  199. raise ValueError(f'Could not find LLM config: --llm_config {args.llm_config}')
  200. metadata = make_metadata(
  201. llm_config,
  202. 'miniwob',
  203. args.agent_cls,
  204. args.max_iterations,
  205. args.eval_note,
  206. args.eval_output_dir,
  207. )
  208. output_file = os.path.join(metadata.eval_output_dir, 'output.jsonl')
  209. instances = prepare_dataset(dataset, output_file, args.eval_n_limit)
  210. run_evaluation(
  211. instances, metadata, output_file, args.eval_num_workers, process_instance
  212. )