run_infer.py 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292
  1. import asyncio
  2. import os
  3. from typing import Any
  4. import pandas as pd
  5. from datasets import load_dataset
  6. from tqdm import tqdm
  7. from evaluation.utils.shared import (
  8. EvalMetadata,
  9. EvalOutput,
  10. codeact_user_response,
  11. compatibility_for_eval_history_pairs,
  12. make_metadata,
  13. prepare_dataset,
  14. reset_logger_for_multiprocessing,
  15. run_evaluation,
  16. update_llm_config_for_completions_logging,
  17. )
  18. from openhands.controller.state.state import State
  19. from openhands.core.config import (
  20. AppConfig,
  21. SandboxConfig,
  22. get_llm_config_arg,
  23. get_parser,
  24. )
  25. from openhands.core.logger import openhands_logger as logger
  26. from openhands.core.main import create_runtime, run_controller
  27. from openhands.events.action import CmdRunAction, MessageAction
  28. from openhands.events.observation import CmdOutputObservation
  29. from openhands.runtime.base import Runtime
  30. from openhands.utils.async_utils import call_async_from_sync
  31. AGENT_CLS_TO_FAKE_USER_RESPONSE_FN = {
  32. 'CodeActAgent': codeact_user_response,
  33. }
  34. LOCAL_DATASET_PATH = os.path.join(os.path.dirname(__file__), 'benchmark')
  35. def format_task_dict(example, use_knowledge):
  36. task = {
  37. 'instance_id': example['instance_id'],
  38. 'task_inst': example['task_inst'],
  39. 'dataset_path': '/benchmark/datasets/'
  40. + example['dataset_folder_tree'].split('\n')[0][4:],
  41. 'dataset_folder_tree': example['dataset_folder_tree'],
  42. 'dataset_preview': example['dataset_preview'],
  43. 'pred_program_name': 'pred_' + example['gold_program_name'],
  44. }
  45. if use_knowledge:
  46. task['task_inst'] += '\n' + str(example['domain_knowledge'])
  47. return task
  48. def get_config(
  49. metadata: EvalMetadata,
  50. instance_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_budget_per_task=4,
  57. max_iterations=metadata.max_iterations,
  58. sandbox=SandboxConfig(
  59. base_container_image='docker.io/xingyaoww/openhands-eval-scienceagentbench',
  60. enable_auto_lint=True,
  61. use_host_network=False,
  62. timeout=300,
  63. api_key=os.environ.get('ALLHANDS_API_KEY', None),
  64. remote_runtime_api_url=os.environ.get('SANDBOX_REMOTE_RUNTIME_API_URL'),
  65. keep_runtime_alive=False,
  66. ),
  67. # do not mount workspace
  68. workspace_base=None,
  69. workspace_mount_path=None,
  70. )
  71. config.set_llm_config(
  72. update_llm_config_for_completions_logging(
  73. metadata.llm_config,
  74. metadata.eval_output_dir,
  75. instance_id,
  76. )
  77. )
  78. return config
  79. def initialize_runtime(
  80. runtime: Runtime,
  81. instance: pd.Series, # this argument is not required
  82. ):
  83. """Initialize the runtime for the agent.
  84. This function is called before the runtime is used to run the agent.
  85. """
  86. logger.info(f"{'-' * 50} BEGIN Runtime Initialization Fn {'-' * 50}")
  87. obs: CmdOutputObservation
  88. # Set up workspace directories
  89. action = CmdRunAction(command='mkdir -p /workspace/pred_programs')
  90. logger.info(action, extra={'msg_type': 'ACTION'})
  91. obs = runtime.run_action(action)
  92. assert obs.exit_code == 0
  93. action = CmdRunAction(command='mkdir -p /workspace/pred_results')
  94. logger.info(action, extra={'msg_type': 'ACTION'})
  95. obs = runtime.run_action(action)
  96. assert obs.exit_code == 0
  97. dataset_name = instance['dataset_folder_tree'].split('\n')[0][4:].rstrip('/')
  98. # Copy the dataset to the workspace
  99. dataset_dir = os.path.join(
  100. LOCAL_DATASET_PATH,
  101. 'datasets',
  102. dataset_name,
  103. )
  104. runtime.copy_to(dataset_dir, '/workspace/benchmark/datasets', recursive=True)
  105. # Check the dataset exists
  106. action = CmdRunAction(
  107. command='cd /workspace/benchmark/datasets && ls',
  108. keep_prompt=False,
  109. )
  110. obs = runtime.run_action(action)
  111. logger.info(obs, extra={'msg_type': 'OBSERVATION'})
  112. assert obs.exit_code == 0
  113. assert dataset_name in obs.content
  114. logger.info(f"{'-' * 50} END Runtime Initialization Fn {'-' * 50}")
  115. def complete_runtime(
  116. runtime: Runtime,
  117. instance: pd.Series,
  118. ) -> dict[str, Any]:
  119. """Complete the runtime for the agent.
  120. This function is called before the runtime is used to run the agent.
  121. If you need to do something in the sandbox to get the correctness metric after
  122. the agent has run, modify this function.
  123. """
  124. logger.info(f"{'-' * 50} BEGIN Runtime Completion Fn {'-' * 50}")
  125. obs: CmdOutputObservation
  126. test_result = {}
  127. action = CmdRunAction(command='cd /workspace')
  128. logger.info(action, extra={'msg_type': 'ACTION'})
  129. obs = runtime.run_action(action)
  130. assert obs.exit_code == 0
  131. action = CmdRunAction(
  132. command=f'cat pred_programs/{instance.pred_program_name}',
  133. keep_prompt=False,
  134. )
  135. logger.info(action, extra={'msg_type': 'ACTION'})
  136. obs = runtime.run_action(action)
  137. if obs.exit_code == 0:
  138. test_result = {'program': obs.content}
  139. else:
  140. test_result = {'program': 'ERROR'}
  141. logger.info(f"{'-' * 50} END Runtime Completion Fn {'-' * 50}")
  142. return test_result
  143. def process_instance(
  144. instance: pd.Series,
  145. metadata: EvalMetadata,
  146. reset_logger: bool = True,
  147. ) -> EvalOutput:
  148. instance_id = instance.instance_id.replace('/', '__')
  149. config = get_config(metadata, instance_id)
  150. # Set up the logger properly, so you can run multi-processing to parallelize the evaluation
  151. if reset_logger:
  152. log_dir = os.path.join(metadata.eval_output_dir, 'infer_logs')
  153. reset_logger_for_multiprocessing(logger, instance_id, log_dir)
  154. else:
  155. logger.info(f'Starting evaluation for instance {instance_id}.')
  156. instruction = f"""You are an expert Python programming assistant that helps scientist users to write high-quality code to solve their tasks.
  157. Given a user request, you are expected to write a complete program that accomplishes the requested task and save any outputs to `/workspace/pred_results/` in the correct format.
  158. Here's the user request you need to work on:
  159. {instance.task_inst}
  160. You can access the dataset at `{instance.dataset_path}`. Here is the directory structure of the dataset:
  161. ```
  162. {instance.dataset_folder_tree}
  163. ```
  164. Here are some helpful previews for the dataset file(s):
  165. {instance.dataset_preview}
  166. Please save your program as `/workspace/pred_programs/{instance.pred_program_name}`.
  167. Then, please run the program to check and fix any errors.
  168. Please do NOT run the program in the background.
  169. If the program uses some packages that are incompatible, please figure out alternative implementations and do NOT restart the environment.
  170. """
  171. runtime = create_runtime(config)
  172. call_async_from_sync(runtime.connect)
  173. initialize_runtime(runtime, instance)
  174. # Here's how you can run the agent (similar to the `main` function) and get the final task state
  175. state: State | None = asyncio.run(
  176. run_controller(
  177. config=config,
  178. initial_user_action=MessageAction(content=instruction),
  179. runtime=runtime,
  180. fake_user_response_fn=AGENT_CLS_TO_FAKE_USER_RESPONSE_FN.get(
  181. metadata.agent_class
  182. ),
  183. )
  184. )
  185. # ======= Attempt to evaluate the agent's edits =======
  186. test_result = complete_runtime(runtime, instance)
  187. # If you are working on some simpler benchmark that only evaluates the final model output (e.g., in a MessageAction)
  188. # You can simply get the LAST `MessageAction` from the returned `state.history` and parse it for evaluation.
  189. if state is None:
  190. raise ValueError('State should not be None.')
  191. metrics = state.metrics.get() if state.metrics else None
  192. # history is now available as a stream of events, rather than list of pairs of (Action, Observation)
  193. # for compatibility with the existing output format, we can remake the pairs here
  194. # remove when it becomes unnecessary
  195. histories = compatibility_for_eval_history_pairs(state.history)
  196. # Save the output
  197. output = EvalOutput(
  198. instance_id=instance.instance_id,
  199. instruction=instruction,
  200. metadata=metadata,
  201. history=histories,
  202. metrics=metrics,
  203. error=state.last_error if state and state.last_error else None,
  204. test_result=test_result,
  205. )
  206. return output
  207. if __name__ == '__main__':
  208. parser = get_parser()
  209. parser.add_argument(
  210. '--use_knowledge',
  211. type=str,
  212. default='false',
  213. choices=['true', 'false'],
  214. help='use expert-provided knowledge or not',
  215. )
  216. args, _ = parser.parse_known_args()
  217. sab_dataset = load_dataset('osunlp/ScienceAgentBench', split='validation')
  218. dataset_processed = []
  219. for example in tqdm(sab_dataset):
  220. dataset_processed.append(
  221. format_task_dict(example, args.use_knowledge == 'true')
  222. )
  223. dataset = pd.DataFrame(dataset_processed)
  224. llm_config = None
  225. if args.llm_config:
  226. llm_config = get_llm_config_arg(args.llm_config)
  227. if llm_config is None:
  228. raise ValueError(f'Could not find LLM config: --llm_config {args.llm_config}')
  229. metadata = make_metadata(
  230. llm_config,
  231. 'ScienceAgentBench',
  232. args.agent_cls,
  233. args.max_iterations,
  234. args.eval_note,
  235. args.eval_output_dir,
  236. )
  237. output_file = os.path.join(metadata.eval_output_dir, 'output.jsonl')
  238. dataset['instance_id'] = dataset['instance_id'].apply(str)
  239. instances = prepare_dataset(dataset, output_file, args.eval_n_limit)
  240. run_evaluation(
  241. instances, metadata, output_file, args.eval_num_workers, process_instance
  242. )