run_infer.py 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206
  1. import asyncio
  2. import json
  3. import os
  4. import pandas as pd
  5. import requests
  6. from evaluation.gorilla.utils import encode_question, get_data_for_hub
  7. from evaluation.utils.shared import (
  8. EvalMetadata,
  9. EvalOutput,
  10. codeact_user_response,
  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. get_parser,
  22. )
  23. from openhands.core.logger import openhands_logger as logger
  24. from openhands.core.main import create_runtime, run_controller
  25. AGENT_CLS_TO_FAKE_USER_RESPONSE_FN = {
  26. 'CodeActAgent': codeact_user_response,
  27. }
  28. AGENT_CLS_TO_INST_SUFFIX = {
  29. 'CodeActAgent': 'When you think you have completed the request, please run the following command: <execute_bash> exit </execute_bash>.\n'
  30. }
  31. def get_config(
  32. metadata: EvalMetadata,
  33. ) -> AppConfig:
  34. config = AppConfig(
  35. default_agent=metadata.agent_class,
  36. run_as_openhands=False,
  37. runtime='eventstream',
  38. max_iterations=metadata.max_iterations,
  39. sandbox=SandboxConfig(
  40. base_container_image='python:3.11-bookworm',
  41. enable_auto_lint=True,
  42. use_host_network=False,
  43. ),
  44. # do not mount workspace
  45. workspace_base=None,
  46. workspace_mount_path=None,
  47. )
  48. config.set_llm_config(metadata.llm_config)
  49. return config
  50. def process_instance(
  51. instance: pd.Series,
  52. metadata: EvalMetadata,
  53. reset_logger: bool = True,
  54. ) -> EvalOutput:
  55. config = get_config(metadata)
  56. instance_id = instance['question_id']
  57. question = instance['question']
  58. # Setup the logger properly, so you can run multi-processing to parallelize the evaluation
  59. if reset_logger:
  60. log_dir = os.path.join(metadata.eval_output_dir, 'infer_logs')
  61. reset_logger_for_multiprocessing(logger, instance_id, log_dir)
  62. else:
  63. logger.info(f'Starting evaluation for instance {instance_id}.')
  64. # Prepare instruction
  65. instruction = encode_question(question, instance['hub'])
  66. instruction += 'IMPORTANT: You should ONLY interact with the environment provided to you AND NEVER ASK FOR HUMAN HELP.\n'
  67. # NOTE: You can actually set slightly different instruction for different agents
  68. instruction += AGENT_CLS_TO_INST_SUFFIX[metadata.agent_class]
  69. # logger.info(f'Instruction:\n{instruction}', extra={'msg_type': 'OBSERVATION'})
  70. # Here's how you can run the agent (similar to the `main` function) and get the final task state
  71. runtime = create_runtime(config, sid=instance_id)
  72. state: State | None = asyncio.run(
  73. run_controller(
  74. config=config,
  75. task_str=instruction,
  76. runtime=runtime,
  77. fake_user_response_fn=AGENT_CLS_TO_FAKE_USER_RESPONSE_FN.get(
  78. metadata.agent_class
  79. ),
  80. )
  81. )
  82. # ======= Attempt to evaluate the agent's edits =======
  83. # If you are working on simpler benchmark that only evaluates the final model output (e.g., in a MessageAction)
  84. # You can simply get the LAST `MessageAction` from the returned `state.history` and parse it for evaluation.
  85. if state is None:
  86. raise ValueError('State should not be None.')
  87. # retrieve the last message from the agent
  88. model_answer_raw = state.history.get_last_agent_message()
  89. # attempt to parse model_answer
  90. ast_eval_fn = instance['ast_eval']
  91. correct, hallucination = ast_eval_fn(instance_id, model_answer_raw)
  92. metrics = state.metrics.get() if state.metrics else None
  93. logger.info(
  94. f'Final message: {model_answer_raw} | Correctness: {correct} | Hallucination: {hallucination}'
  95. )
  96. # history is now available as a stream of events, rather than list of pairs of (Action, Observation)
  97. # for compatibility with the existing output format, we can remake the pairs here
  98. # remove when it becomes unnecessary
  99. histories = state.history.compatibility_for_eval_history_pairs()
  100. output = EvalOutput(
  101. instance_id=instance_id,
  102. metadata=metadata,
  103. history=histories,
  104. metrics=metrics,
  105. error=state.last_error if state and state.last_error else None,
  106. test_result={
  107. 'text': model_answer_raw,
  108. 'correct': correct,
  109. 'hallucination': hallucination,
  110. },
  111. )
  112. return output
  113. if __name__ == '__main__':
  114. parser = get_parser()
  115. parser.add_argument(
  116. '--hubs',
  117. type=str,
  118. help='Which hubs to evaluate from APIBench. APIBench contains 3 hubs, namely huggingface, torch, and tensorflow. You could choose one or more from hf, torch, or tf, separated by commas. For example, the default is --hub hf,torch,tf.',
  119. default='hf,torch,tf',
  120. )
  121. args, _ = parser.parse_known_args()
  122. llm_config = None
  123. if args.llm_config:
  124. llm_config = get_llm_config_arg(args.llm_config)
  125. if llm_config is None:
  126. raise ValueError(f'Could not find LLM config: --llm_config {args.llm_config}')
  127. hubs = args.hubs.split(',')
  128. if len(hubs) == 0:
  129. raise ValueError('Please choose at least one from hf, torch, and tf for hubs.')
  130. dfs = []
  131. for hub in hubs:
  132. logger.info(f'Evaluating APIBench {hub} test')
  133. df = get_data_for_hub(hub)
  134. dfs.append(df)
  135. dataset_df = pd.concat(dfs)
  136. dataset_df.rename(columns={'question_id': 'instance_id'}, inplace=True)
  137. metadata = make_metadata(
  138. llm_config=llm_config,
  139. dataset_name=f'gorilla-{hub}',
  140. agent_class=args.agent_cls,
  141. max_iterations=args.max_iterations,
  142. eval_note=args.eval_note,
  143. eval_output_dir=args.eval_output_dir,
  144. data_split=args.data_split,
  145. )
  146. output_file = os.path.join(metadata.eval_output_dir, 'output.jsonl')
  147. dataset = prepare_dataset(
  148. dataset_df, output_file=output_file, eval_n_limit=args.eval_n_limit
  149. )
  150. file_path = os.path.join(os.path.dirname(__file__), 'my-languages.so')
  151. # Check if the file exists
  152. if not os.path.exists(file_path):
  153. url = 'https://raw.githubusercontent.com/ShishirPatil/gorilla/main/eval/eval-scripts/codebleu/parser/my-languages.so'
  154. response = requests.get(url)
  155. with open(file_path, 'wb') as f:
  156. f.write(response.content)
  157. else:
  158. print('File already exists, skipping download.')
  159. run_evaluation(
  160. dataset=dataset,
  161. metadata=metadata,
  162. output_file=output_file,
  163. num_workers=args.eval_num_workers,
  164. process_instance_func=process_instance,
  165. )
  166. # Read the output file and calculate the accuracy
  167. total_correct = 0
  168. total_hallucination = 0
  169. output = []
  170. with open(output_file, 'r') as f:
  171. for line in f:
  172. data = json.loads(line)
  173. if data['test_result']['correct']:
  174. total_correct += 1
  175. if data['test_result']['hallucination']:
  176. total_hallucination += 1
  177. output.append(data)
  178. logger.info(
  179. f'Evaluation finished for {hub}. Total: {len(output)}; Correct: {total_correct}; Hallucination: {total_hallucination}. Accuracy: {total_correct / len(output)}'
  180. )