run_infer.py 7.7 KB

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