run_infer.py 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217
  1. import asyncio
  2. import os
  3. from typing import Any
  4. import pandas as pd
  5. from evaluation.toolqa.utils import encode_question, eval_answer, get_data
  6. from evaluation.utils.shared import (
  7. EvalMetadata,
  8. EvalOutput,
  9. codeact_user_response,
  10. make_metadata,
  11. prepare_dataset,
  12. reset_logger_for_multiprocessing,
  13. run_evaluation,
  14. )
  15. from openhands.controller.state.state import State
  16. from openhands.core.config import (
  17. AppConfig,
  18. SandboxConfig,
  19. get_llm_config_arg,
  20. get_parser,
  21. )
  22. from openhands.core.logger import openhands_logger as logger
  23. from openhands.core.main import create_runtime, run_controller
  24. from openhands.events.action import CmdRunAction
  25. from openhands.events.observation import CmdOutputObservation
  26. from openhands.runtime.runtime import Runtime
  27. AGENT_CLS_TO_FAKE_USER_RESPONSE_FN = {
  28. 'CodeActAgent': codeact_user_response,
  29. }
  30. AGENT_CLS_TO_INST_SUFFIX = {
  31. 'CodeActAgent': 'When you think you have completed the request, please run the following command: <execute_bash> exit </execute_bash>.\n'
  32. }
  33. def get_config(
  34. metadata: EvalMetadata,
  35. ) -> AppConfig:
  36. config = AppConfig(
  37. default_agent=metadata.agent_class,
  38. run_as_openhands=False,
  39. runtime='eventstream',
  40. max_iterations=metadata.max_iterations,
  41. sandbox=SandboxConfig(
  42. base_container_image='python:3.11-bookworm',
  43. enable_auto_lint=True,
  44. use_host_network=False,
  45. ),
  46. # do not mount workspace
  47. workspace_base=None,
  48. workspace_mount_path=None,
  49. )
  50. config.set_llm_config(metadata.llm_config)
  51. return config
  52. async def initialize_runtime(runtime: Runtime):
  53. """Initialize the runtime for the agent.
  54. This function is called before the runtime is used to run the agent.
  55. """
  56. logger.info(f"{'-' * 50} BEGIN Runtime Initialization Fn {'-' * 50}")
  57. obs: CmdOutputObservation
  58. # Set instance id
  59. action = CmdRunAction(command='mkdir -p /workspace')
  60. logger.info(action, extra={'msg_type': 'ACTION'})
  61. obs = await runtime.run_action(action)
  62. assert obs.exit_code == 0
  63. action = CmdRunAction(command='cd /workspace')
  64. logger.info(action, extra={'msg_type': 'ACTION'})
  65. obs = await runtime.run_action(action)
  66. assert obs.exit_code == 0
  67. await runtime.add_env_vars({'WOLFRAM_ALPHA_APPID': args.wolfram_alpha_appid})
  68. logger.info(f"{'-' * 50} END Runtime Initialization Fn {'-' * 50}")
  69. async def process_instance(
  70. instance: Any, metadata: EvalMetadata, reset_logger: bool = True
  71. ):
  72. config = get_config(metadata)
  73. qid = instance.qid
  74. question = instance.question
  75. answer = instance.answer
  76. # Setup the logger properly, so you can run multi-processing to parallelize the evaluation
  77. if reset_logger:
  78. log_dir = os.path.join(metadata.eval_output_dir, 'infer_logs')
  79. reset_logger_for_multiprocessing(logger, qid, log_dir)
  80. else:
  81. logger.info(f'Starting evaluation for instance {qid}.')
  82. # Prepare instruction
  83. instruction = encode_question(question)
  84. instruction += 'IMPORTANT: You should ONLY interact with the environment provided to you AND NEVER ASK FOR HUMAN HELP.\n'
  85. # NOTE: You can actually set slightly different instruction for different agents
  86. instruction += AGENT_CLS_TO_INST_SUFFIX[metadata.agent_class]
  87. logger.info(f'Instruction:\n{instruction}', extra={'msg_type': 'OBSERVATION'})
  88. runtime = await create_runtime(config, sid=qid)
  89. await initialize_runtime(runtime)
  90. # Here's how you can run the agent (similar to the `main` function) and get the final task state
  91. state: State | None = await run_controller(
  92. config=config,
  93. task_str=instruction,
  94. runtime=runtime,
  95. fake_user_response_fn=AGENT_CLS_TO_FAKE_USER_RESPONSE_FN[metadata.agent_class],
  96. )
  97. # ======= Attempt to evaluate the agent's edits =======
  98. # If you are working on simpler benchmark that only evaluates the final model output (e.g., in a MessageAction)
  99. # You can simply get the LAST `MessageAction` from the returned `state.history` and parse it for evaluation.
  100. if state is None:
  101. raise ValueError('State should not be None.')
  102. # retrieve the last message from the agent
  103. model_answer_raw = state.history.get_last_agent_message()
  104. # attempt to parse model_answer
  105. correct = eval_answer(str(model_answer_raw), str(answer))
  106. logger.info(f'Final message: {model_answer_raw} | Correctness: {correct}')
  107. metrics = state.metrics.get() if state.metrics else None
  108. # history is now available as a stream of events, rather than list of pairs of (Action, Observation)
  109. # for compatibility with the existing output format, we can remake the pairs here
  110. # remove when it becomes unnecessary
  111. histories = state.history.compatibility_for_eval_history_pairs()
  112. # Save the output
  113. output = EvalOutput(
  114. instance_id=qid,
  115. test_result={
  116. 'model_answer_raw': model_answer_raw,
  117. 'correct': correct,
  118. },
  119. metadata=metadata,
  120. history=histories,
  121. metrics=metrics,
  122. error=state.last_error if state and state.last_error else None,
  123. )
  124. return output
  125. if __name__ == '__main__':
  126. parser = get_parser()
  127. parser.add_argument(
  128. '--dataset',
  129. type=str,
  130. help='Which dataset to evaluate from ToolQA. ToolQA contains 8 datasets, namely agenda, airbnb, coffee, dblp, flight, gsm8k, scirex, yelp. For example, the default is --dataset flight.',
  131. default='flight',
  132. )
  133. parser.add_argument(
  134. '--hardness',
  135. type=str,
  136. help='Which level of difficulty to evaluate from ToolQA. ToolQA contains 2 levels of hardness, namely easy and hard. For example, the default is --hardness easy.',
  137. default='easy',
  138. )
  139. parser.add_argument(
  140. '--wolfram_alpha_appid',
  141. type=str,
  142. help='wolfram alpha appid to use for wolfram alpha related tests',
  143. default='YOUR_WOLFRAMALPHA_APPID',
  144. )
  145. args, _ = parser.parse_known_args()
  146. llm_config = None
  147. if args.llm_config:
  148. llm_config = get_llm_config_arg(args.llm_config)
  149. if llm_config is None:
  150. raise ValueError(f'Could not find LLM config: --llm_config {args.llm_config}')
  151. dataset = ''
  152. hardness = ''
  153. dataset_choices = [
  154. 'agenda',
  155. 'airbnb',
  156. 'coffee',
  157. 'dblp',
  158. 'flight',
  159. 'gsm8k',
  160. 'scirex',
  161. 'yelp',
  162. 'genda',
  163. ]
  164. if args.dataset not in dataset_choices:
  165. raise ValueError(
  166. 'Please choose from agenda, airbnb, coffee, dblp, flight, gsm8k, scirex, yelp for dataset.'
  167. )
  168. if args.hardness not in ['easy', 'hard']:
  169. raise ValueError('Please choose from easy and hard for hardness.')
  170. toolqa_test = pd.DataFrame(get_data(dataset, hardness))
  171. toolqa_test.rename(columns={'qid': 'instance_id'}, inplace=True)
  172. metadata = make_metadata(
  173. llm_config,
  174. f'toolqa-{args.dataset}-{args.hardness}',
  175. args.agent_cls,
  176. args.eval_note,
  177. args.eval_output_dir,
  178. )
  179. output_file = os.path.join(metadata.eval_output_dir, 'output.jsonl')
  180. instances = prepare_dataset(toolqa_test, output_file, args.eval_n_limit)
  181. asyncio.run(
  182. run_evaluation(
  183. instances, metadata, output_file, args.eval_num_workers, process_instance
  184. )
  185. )