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, MessageAction
  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.12-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. 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 = 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 = runtime.run_action(action)
  66. assert obs.exit_code == 0
  67. runtime.add_env_vars({'WOLFRAM_ALPHA_APPID': args.wolfram_alpha_appid})
  68. logger.info(f"{'-' * 50} END Runtime Initialization Fn {'-' * 50}")
  69. def process_instance(instance: Any, metadata: EvalMetadata, reset_logger: bool = True):
  70. config = get_config(metadata)
  71. qid = instance.qid
  72. question = instance.question
  73. answer = instance.answer
  74. # Setup the logger properly, so you can run multi-processing to parallelize the evaluation
  75. if reset_logger:
  76. log_dir = os.path.join(metadata.eval_output_dir, 'infer_logs')
  77. reset_logger_for_multiprocessing(logger, qid, log_dir)
  78. else:
  79. logger.info(f'Starting evaluation for instance {qid}.')
  80. # Prepare instruction
  81. instruction = encode_question(question)
  82. instruction += 'IMPORTANT: You should ONLY interact with the environment provided to you AND NEVER ASK FOR HUMAN HELP.\n'
  83. # NOTE: You can actually set slightly different instruction for different agents
  84. instruction += AGENT_CLS_TO_INST_SUFFIX[metadata.agent_class]
  85. logger.info(f'Instruction:\n{instruction}', extra={'msg_type': 'OBSERVATION'})
  86. runtime = create_runtime(config)
  87. initialize_runtime(runtime)
  88. # Here's how you can run the agent (similar to the `main` function) and get the final task state
  89. state: State | None = asyncio.run(
  90. run_controller(
  91. config=config,
  92. initial_user_action=MessageAction(content=instruction),
  93. runtime=runtime,
  94. fake_user_response_fn=AGENT_CLS_TO_FAKE_USER_RESPONSE_FN[
  95. metadata.agent_class
  96. ],
  97. )
  98. )
  99. # ======= Attempt to evaluate the agent's edits =======
  100. # If you are working on simpler benchmark that only evaluates the final model output (e.g., in a MessageAction)
  101. # You can simply get the LAST `MessageAction` from the returned `state.history` and parse it for evaluation.
  102. if state is None:
  103. raise ValueError('State should not be None.')
  104. # retrieve the last message from the agent
  105. model_answer_raw = state.history.get_last_agent_message()
  106. # attempt to parse model_answer
  107. correct = eval_answer(str(model_answer_raw), str(answer))
  108. logger.info(f'Final message: {model_answer_raw} | Correctness: {correct}')
  109. metrics = state.metrics.get() if state.metrics else None
  110. # history is now available as a stream of events, rather than list of pairs of (Action, Observation)
  111. # for compatibility with the existing output format, we can remake the pairs here
  112. # remove when it becomes unnecessary
  113. histories = state.history.compatibility_for_eval_history_pairs()
  114. # Save the output
  115. output = EvalOutput(
  116. instance_id=qid,
  117. test_result={
  118. 'model_answer_raw': model_answer_raw,
  119. 'correct': correct,
  120. },
  121. metadata=metadata,
  122. history=histories,
  123. metrics=metrics,
  124. error=state.last_error if state and state.last_error else None,
  125. )
  126. return output
  127. if __name__ == '__main__':
  128. parser = get_parser()
  129. parser.add_argument(
  130. '--dataset',
  131. type=str,
  132. 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.',
  133. default='flight',
  134. )
  135. parser.add_argument(
  136. '--hardness',
  137. type=str,
  138. 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.',
  139. default='easy',
  140. )
  141. parser.add_argument(
  142. '--wolfram_alpha_appid',
  143. type=str,
  144. help='wolfram alpha appid to use for wolfram alpha related tests',
  145. default='YOUR_WOLFRAMALPHA_APPID',
  146. )
  147. args, _ = parser.parse_known_args()
  148. llm_config = None
  149. if args.llm_config:
  150. llm_config = get_llm_config_arg(args.llm_config)
  151. if llm_config is None:
  152. raise ValueError(f'Could not find LLM config: --llm_config {args.llm_config}')
  153. dataset = ''
  154. hardness = ''
  155. dataset_choices = [
  156. 'agenda',
  157. 'airbnb',
  158. 'coffee',
  159. 'dblp',
  160. 'flight',
  161. 'gsm8k',
  162. 'scirex',
  163. 'yelp',
  164. 'genda',
  165. ]
  166. if args.dataset not in dataset_choices:
  167. raise ValueError(
  168. 'Please choose from agenda, airbnb, coffee, dblp, flight, gsm8k, scirex, yelp for dataset.'
  169. )
  170. if args.hardness not in ['easy', 'hard']:
  171. raise ValueError('Please choose from easy and hard for hardness.')
  172. toolqa_test = pd.DataFrame(get_data(dataset, hardness))
  173. toolqa_test.rename(columns={'qid': 'instance_id'}, inplace=True)
  174. metadata = make_metadata(
  175. llm_config,
  176. f'toolqa-{args.dataset}-{args.hardness}',
  177. args.agent_cls,
  178. args.eval_note,
  179. args.eval_output_dir,
  180. )
  181. output_file = os.path.join(metadata.eval_output_dir, 'output.jsonl')
  182. instances = prepare_dataset(toolqa_test, output_file, args.eval_n_limit)
  183. run_evaluation(
  184. instances, metadata, output_file, args.eval_num_workers, process_instance
  185. )