run_infer.py 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232
  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 openhands.controller.state.state import State
  17. from openhands.core.config import (
  18. AppConfig,
  19. SandboxConfig,
  20. get_llm_config_arg,
  21. parse_arguments,
  22. )
  23. from openhands.core.logger import openhands_logger as logger
  24. from openhands.core.main import create_runtime, run_controller
  25. from openhands.events.action import (
  26. BrowseInteractiveAction,
  27. CmdRunAction,
  28. MessageAction,
  29. )
  30. from openhands.events.observation import CmdOutputObservation
  31. from openhands.runtime.browser.browser_env import (
  32. BROWSER_EVAL_GET_GOAL_ACTION,
  33. BROWSER_EVAL_GET_REWARDS_ACTION,
  34. )
  35. from openhands.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_openhands=False,
  48. runtime='eventstream',
  49. max_iterations=metadata.max_iterations,
  50. sandbox=SandboxConfig(
  51. base_container_image='python:3.11-bookworm',
  52. enable_auto_lint=True,
  53. use_host_network=False,
  54. browsergym_eval_env=env_id,
  55. 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. 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 = 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 = 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. 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 = 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. 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 = create_runtime(config, sid=env_id)
  125. task_str = initialize_runtime(runtime)
  126. state: State | None = asyncio.run(
  127. run_controller(
  128. config=config,
  129. task_str=task_str,
  130. runtime=runtime,
  131. )
  132. )
  133. # ======= Attempt to evaluate the agent's environment impact =======
  134. # If you are working on some simpler benchmark that only evaluates the final model output (e.g., in a MessageAction)
  135. # You can simply get the LAST `MessageAction` from the returned `state.history` and parse it for evaluation.
  136. if state is None:
  137. raise ValueError('State should not be None.')
  138. metrics = state.metrics.get() if state.metrics else None
  139. # Instruction is the first message from the USER
  140. instruction = ''
  141. for event in state.history.get_events():
  142. if isinstance(event, MessageAction):
  143. instruction = event.content
  144. break
  145. return_val = complete_runtime(runtime)
  146. logger.info(f'Return value from complete_runtime: {return_val}')
  147. reward = max(return_val['rewards'])
  148. # history is now available as a stream of events, rather than list of pairs of (Action, Observation)
  149. # for compatibility with the existing output format, we can remake the pairs here
  150. # remove when it becomes unnecessary
  151. histories = state.history.compatibility_for_eval_history_pairs()
  152. # Save the output
  153. output = EvalOutput(
  154. instance_id=env_id,
  155. instruction=instruction,
  156. metadata=metadata,
  157. history=histories,
  158. metrics=metrics,
  159. error=state.last_error if state and state.last_error else None,
  160. test_result={
  161. 'reward': reward,
  162. },
  163. )
  164. return output
  165. if __name__ == '__main__':
  166. args = parse_arguments()
  167. dataset = pd.DataFrame(
  168. {
  169. 'instance_id': [
  170. id
  171. for id in gym.envs.registry.keys()
  172. if id.startswith('browsergym/webarena')
  173. ]
  174. }
  175. )
  176. llm_config = None
  177. if args.llm_config:
  178. llm_config = get_llm_config_arg(args.llm_config)
  179. if llm_config is None:
  180. raise ValueError(f'Could not find LLM config: --llm_config {args.llm_config}')
  181. metadata = make_metadata(
  182. llm_config,
  183. args.dataset_name,
  184. args.agent_cls,
  185. args.max_iterations,
  186. args.eval_note,
  187. args.eval_output_dir,
  188. )
  189. output_file = os.path.join(metadata.eval_output_dir, 'output.jsonl')
  190. instances = prepare_dataset(dataset, output_file, args.eval_n_limit)
  191. run_evaluation(
  192. instances,
  193. metadata,
  194. output_file,
  195. args.eval_num_workers,
  196. process_instance,
  197. )