run_infer.py 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193
  1. import asyncio
  2. import logging
  3. import os
  4. import pathlib
  5. from typing import Any
  6. import pandas as pd
  7. from evaluation.utils.shared import (
  8. EvalMetadata,
  9. codeact_user_response,
  10. make_metadata,
  11. prepare_dataset,
  12. run_evaluation,
  13. )
  14. from opendevin.controller.agent import Agent
  15. from opendevin.controller.state.state import State
  16. from opendevin.core.config import config, get_llm_config_arg, get_parser
  17. from opendevin.core.logger import get_console_handler
  18. from opendevin.core.logger import opendevin_logger as logger
  19. from opendevin.core.main import run_agent_controller
  20. from opendevin.llm.llm import LLM
  21. from .utils import download_data, download_tools, encode_question, eval_answer, get_data
  22. AGENT_CLS_TO_FAKE_USER_RESPONSE_FN = {
  23. 'CodeActAgent': codeact_user_response,
  24. }
  25. AGENT_CLS_TO_INST_SUFFIX = {
  26. 'CodeActAgent': 'When you think you have completed the request, please run the following command: <execute_bash> exit </execute_bash>.\n'
  27. }
  28. def process_instance(instance: Any, metadata: EvalMetadata, reset_logger: bool = True):
  29. agent = Agent.get_cls(metadata.agent_class)(llm=LLM(config=metadata.llm_config))
  30. # create process-specific workspace dir
  31. # we will create a workspace directory for EACH process
  32. # so that different agent don't interfere with each other.
  33. workspace_mount_path = config.workspace_mount_path
  34. pathlib.Path(workspace_mount_path).mkdir(parents=True, exist_ok=True)
  35. # Setup the logger properly, so you can run multi-processing to parallelize the evaluation
  36. eval_output_dir = metadata.eval_output_dir
  37. qid = instance.qid
  38. question = instance.question
  39. answer = instance.answer
  40. if reset_logger:
  41. # Set up logger
  42. log_file = os.path.join(eval_output_dir, 'logs', f'instance_{qid}.log')
  43. # Remove all existing handlers from logger
  44. for handler in logger.handlers[:]:
  45. logger.removeHandler(handler)
  46. # add back the console handler to print ONE line
  47. logger.addHandler(get_console_handler())
  48. logger.info(
  49. f'Starting evaluation for instance {qid}.\nHint: run "tail -f {log_file}" to see live logs in a separate shell'
  50. )
  51. # Remove all existing handlers from logger
  52. for handler in logger.handlers[:]:
  53. logger.removeHandler(handler)
  54. file_handler = logging.FileHandler(log_file)
  55. file_handler.setFormatter(
  56. logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')
  57. )
  58. logger.addHandler(file_handler)
  59. logger.info(f'Process-specific workspace mounted at {workspace_mount_path}')
  60. # Prepare instruction
  61. instruction = encode_question(question)
  62. instruction += 'IMPORTANT: You should ONLY interact with the environment provided to you AND NEVER ASK FOR HUMAN HELP.\n'
  63. # NOTE: You can actually set slightly different instruction for different agents
  64. instruction += AGENT_CLS_TO_INST_SUFFIX[agent.__class__.__name__]
  65. # logger.info(f'Instruction:\n{instruction}', extra={'msg_type': 'OBSERVATION'})
  66. # Here's how you can run the agent (similar to the `main` function) and get the final task state
  67. state: State | None = asyncio.run(
  68. run_agent_controller(
  69. agent,
  70. instruction,
  71. max_iterations=metadata.max_iterations,
  72. max_budget_per_task=config.max_budget_per_task,
  73. fake_user_response_fn=AGENT_CLS_TO_FAKE_USER_RESPONSE_FN[
  74. agent.__class__.__name__
  75. ],
  76. sid=qid,
  77. )
  78. )
  79. # ======= Attempt to evaluate the agent's edits =======
  80. # If you are working on simpler benchmark that only evaluates the final model output (e.g., in a MessageAction)
  81. # You can simply get the LAST `MessageAction` from the returned `state.history` and parse it for evaluation.
  82. if state is None:
  83. raise ValueError('State should not be None.')
  84. # retrieve the last message from the agent
  85. model_answer_raw = state.history.get_last_agent_message()
  86. # attempt to parse model_answer
  87. correct = eval_answer(str(model_answer_raw), str(answer))
  88. logger.info(f'Final message: {model_answer_raw} | Correctness: {correct}')
  89. metrics = state.metrics.get() if state.metrics else None
  90. # history is now available as a stream of events, rather than list of pairs of (Action, Observation)
  91. # for compatibility with the existing output format, we can remake the pairs here
  92. # remove when it becomes unnecessary
  93. histories = state.history.compatibility_for_eval_history_pairs()
  94. # Save the output
  95. output = {
  96. 'qid': qid,
  97. 'text': model_answer_raw,
  98. 'correct': correct,
  99. 'answer_id': 'None',
  100. 'model_id': metadata.model_name,
  101. 'metadata': metadata,
  102. 'history': histories,
  103. 'metrics': metrics,
  104. 'error': state.last_error if state and state.last_error else None,
  105. }
  106. return output
  107. if __name__ == '__main__':
  108. parser = get_parser()
  109. parser.add_argument(
  110. '--dataset',
  111. type=str,
  112. 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.',
  113. default='flight',
  114. )
  115. parser.add_argument(
  116. '--hardness',
  117. type=str,
  118. 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.',
  119. default='easy',
  120. )
  121. parser.add_argument(
  122. '--wolfram_alpha_appid',
  123. type=str,
  124. help='wolfram alpha appid to use for wolfram alpha related tests',
  125. default='YOUR_WOLFRAMALPHA_APPID',
  126. )
  127. args, _ = parser.parse_known_args()
  128. llm_config = get_llm_config_arg(args.llm_config) if args.llm_config else config.llm
  129. logger.info(f'Config for evaluation: {config}')
  130. dataset = ''
  131. hardness = ''
  132. dataset_choices = [
  133. 'agenda',
  134. 'airbnb',
  135. 'coffee',
  136. 'dblp',
  137. 'flight',
  138. 'gsm8k',
  139. 'scirex',
  140. 'yelp',
  141. 'genda',
  142. ]
  143. if args.dataset not in dataset_choices:
  144. raise ValueError(
  145. 'Please choose from agenda, airbnb, coffee, dblp, flight, gsm8k, scirex, yelp for dataset.'
  146. )
  147. if args.hardness not in ['easy', 'hard']:
  148. raise ValueError('Please choose from easy and hard for hardness.')
  149. # workspace_mount_path = os.path.join(config.workspace_mount_path, '_eval_workspace')
  150. workspace_mount_path = config.workspace_mount_path
  151. pathlib.Path(workspace_mount_path).mkdir(parents=True, exist_ok=True)
  152. toolqa_test = pd.DataFrame(get_data(dataset, hardness))
  153. toolqa_data_path = download_data(workspace_mount_path)
  154. toolqa_tool_path = download_tools(workspace_mount_path, args.wolfram_alpha_appid)
  155. id_column = 'qid'
  156. metadata = make_metadata(
  157. llm_config,
  158. f'toolqa-{args.dataset}-{args.hardness}',
  159. args.agent_cls,
  160. args.eval_note,
  161. args.eval_output_dir,
  162. )
  163. output_file = os.path.join(metadata.eval_output_dir, 'output.jsonl')
  164. instances = prepare_dataset(toolqa_test, output_file, args.eval_n_limit, id_column)
  165. run_evaluation(
  166. instances,
  167. metadata,
  168. output_file,
  169. args.eval_num_workers,
  170. process_instance,
  171. id_column,
  172. )