run_infer.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353
  1. import asyncio
  2. import json
  3. import logging
  4. import multiprocessing as mp
  5. import os
  6. import pathlib
  7. import subprocess
  8. import time
  9. from concurrent.futures import ProcessPoolExecutor
  10. from tqdm import tqdm
  11. from utils import download_data, download_tools, encode_question, eval_answer, get_data
  12. from opendevin.controller.state.state import State
  13. from opendevin.core.config import config, get_llm_config_arg, get_parser
  14. from opendevin.core.logger import get_console_handler
  15. from opendevin.core.logger import opendevin_logger as logger
  16. from opendevin.core.main import main
  17. from opendevin.events.action import MessageAction
  18. from opendevin.events.serialization.event import event_to_dict
  19. def cleanup():
  20. print('Cleaning up child processes...')
  21. for process in mp.active_children():
  22. print(f'Terminating child process: {process.name}')
  23. process.terminate()
  24. process.join()
  25. def codeact_user_response(state: State) -> str:
  26. msg = (
  27. 'Please continue working on the task on whatever approach you think is suitable.\n'
  28. 'When you think you finished the task, respond with `Finish[answer]` where you include your answer in `[]`\n'
  29. 'IMPORTANT: YOU SHOULD NEVER ASK FOR HUMAN HELP OR USE THE INTERNET TO SOLVE THIS TASK.\n'
  30. )
  31. if state.history:
  32. user_msgs = [
  33. action
  34. for action, _ in state.history
  35. if isinstance(action, MessageAction) and action.source == 'user'
  36. ]
  37. if len(user_msgs) >= 2:
  38. # let the agent know that it can give up when it has tried 3 times
  39. return (
  40. msg
  41. + 'If you want to give up, run: <execute_bash> exit </execute_bash>.\n'
  42. )
  43. return msg
  44. def monologue_user_response(state: State) -> str:
  45. raise NotImplementedError('MonologueAgent should never ask for user responses.')
  46. AGENT_CLS_TO_FAKE_USER_RESPONSE_FN = {
  47. 'CodeActAgent': codeact_user_response,
  48. 'MonologueAgent': monologue_user_response,
  49. }
  50. AGENT_CLS_TO_INST_SUFFIX = {
  51. 'CodeActAgent': 'When you think you have completed the request, please run the following command: <execute_bash> exit </execute_bash>.\n'
  52. }
  53. def process_instance(task, agent_class, metadata, reset_logger: bool = True):
  54. # create process-specific workspace dir
  55. # we will create a workspace directory for EACH process
  56. # so that different agent don't interfere with each other.
  57. workspace_mount_path = config.workspace_mount_path
  58. pathlib.Path(workspace_mount_path).mkdir(parents=True, exist_ok=True)
  59. # Setup the logger properly, so you can run multi-processing to parallelize the evaluation
  60. eval_output_dir = metadata['eval_output_dir']
  61. qid = task['qid']
  62. question = task['question']
  63. answer = task['answer']
  64. if reset_logger:
  65. # Set up logger
  66. log_file = os.path.join(eval_output_dir, 'logs', f'instance_{qid}.log')
  67. # Remove all existing handlers from logger
  68. for handler in logger.handlers[:]:
  69. logger.removeHandler(handler)
  70. # add back the console handler to print ONE line
  71. logger.addHandler(get_console_handler())
  72. logger.info(
  73. f'Starting evaluation for instance {qid}.\nHint: run "tail -f {log_file}" to see live logs in a separate shell'
  74. )
  75. # Remove all existing handlers from logger
  76. for handler in logger.handlers[:]:
  77. logger.removeHandler(handler)
  78. file_handler = logging.FileHandler(log_file)
  79. file_handler.setFormatter(
  80. logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')
  81. )
  82. logger.addHandler(file_handler)
  83. logger.info(f'Process-specific workspace mounted at {workspace_mount_path}')
  84. # Prepare instruction
  85. instruction = encode_question(question)
  86. instruction += 'IMPORTANT: You should ONLY interact with the environment provided to you AND NEVER ASK FOR HUMAN HELP.\n'
  87. # NOTE: You can actually set slightly different instruction for different agents
  88. instruction += AGENT_CLS_TO_INST_SUFFIX.get(agent_class, '')
  89. # logger.info(f'Instruction:\n{instruction}', extra={'msg_type': 'OBSERVATION'})
  90. # Here's how you can run the agent (similar to the `main` function) and get the final task state
  91. state: State = asyncio.run(
  92. main(
  93. instruction,
  94. fake_user_response_fn=AGENT_CLS_TO_FAKE_USER_RESPONSE_FN.get(agent_class),
  95. )
  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. model_answer_raw = ''
  103. for act, _ in reversed(state.history):
  104. if isinstance(act, MessageAction) and act.source == 'agent':
  105. model_answer_raw = act.content
  106. break
  107. # attempt to parse model_answer
  108. correct = eval_answer(str(model_answer_raw), str(answer))
  109. metrics = state.metrics.get() if state.metrics else None
  110. logger.info(f'Final message: {model_answer_raw} | Correctness: {correct}')
  111. # Save the output
  112. output = {
  113. 'qid': qid,
  114. 'text': model_answer_raw,
  115. 'correct': correct,
  116. 'answer_id': 'None',
  117. 'model_id': metadata['model_name'],
  118. 'metadata': metadata,
  119. 'history': [
  120. (event_to_dict(action), event_to_dict(obs)) for action, obs in state.history
  121. ],
  122. 'metrics': metrics,
  123. 'error': state.error if state and state.error else None,
  124. }
  125. return output
  126. if __name__ == '__main__':
  127. parser = get_parser()
  128. parser.add_argument(
  129. '--dataset',
  130. type=str,
  131. 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.',
  132. default='flight',
  133. )
  134. parser.add_argument(
  135. '--hardness',
  136. type=str,
  137. 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.',
  138. default='easy',
  139. )
  140. parser.add_argument(
  141. '--wolfram_alpha_appid',
  142. type=str,
  143. help='wolfram alpha appid to use for wolfram alpha related tests',
  144. default='YOUR_WOLFRAMALPHA_APPID',
  145. )
  146. args, _ = parser.parse_known_args()
  147. if args.directory:
  148. config.workspace_base = os.path.abspath(args.directory)
  149. print(f'Setting workspace base to {config.workspace_base}')
  150. # Check https://github.com/OpenDevin/OpenDevin/blob/main/evaluation/swe_bench/README.md#configure-opendevin-and-your-llm
  151. # for details of how to set `llm_config`
  152. if args.llm_config:
  153. specified_llm_config = get_llm_config_arg(args.llm_config)
  154. if specified_llm_config:
  155. config.llm = specified_llm_config
  156. logger.info(f'Config for evaluation: {config}')
  157. agent_class = args.agent_cls
  158. assert (
  159. agent_class in AGENT_CLS_TO_FAKE_USER_RESPONSE_FN
  160. ), f'Unsupported agent class: {agent_class}'
  161. model_name = config.llm.model.split('/')[-1]
  162. max_iterations = args.max_iterations
  163. eval_note = ''
  164. if args.eval_note is not None:
  165. eval_note += '_N_' + args.eval_note
  166. eval_output_dir = os.path.join(
  167. args.eval_output_dir,
  168. 'toolqa',
  169. agent_class,
  170. model_name + '_maxiter_' + str(max_iterations) + eval_note,
  171. )
  172. pathlib.Path(eval_output_dir).mkdir(parents=True, exist_ok=True)
  173. pathlib.Path(os.path.join(eval_output_dir, 'logs')).mkdir(
  174. parents=True, exist_ok=True
  175. )
  176. logger.info(f'Using evaluation output directory: {eval_output_dir}')
  177. dataset = ''
  178. hardness = ''
  179. dataset_choices = [
  180. 'agenda',
  181. 'airbnb',
  182. 'coffee',
  183. 'dblp',
  184. 'flight',
  185. 'gsm8k',
  186. 'scirex',
  187. 'yelp',
  188. 'genda',
  189. ]
  190. if args.dataset in dataset_choices:
  191. dataset = args.dataset
  192. else:
  193. raise ValueError(
  194. 'Please choose from agenda, airbnb, coffee, dblp, flight, gsm8k, scirex, yelp for dataset.'
  195. )
  196. if args.hardness == 'easy':
  197. hardness = 'easy'
  198. elif args.hardness == 'hard':
  199. hardness = 'hard'
  200. else:
  201. raise ValueError('Please choose from easy and hard for hardness.')
  202. logger.info(f'Evaluating ToolQA {dataset} {hardness} test')
  203. # workspace_mount_path = os.path.join(config.workspace_mount_path, '_eval_workspace')
  204. workspace_mount_path = config.workspace_mount_path
  205. pathlib.Path(workspace_mount_path).mkdir(parents=True, exist_ok=True)
  206. toolqa_test = get_data(dataset, hardness)
  207. toolqa_data_path = download_data(workspace_mount_path)
  208. toolqa_tool_path = download_tools(workspace_mount_path, args.wolfram_alpha_appid)
  209. # TEST METADATA
  210. metadata = {
  211. 'dataset': dataset,
  212. 'hardness': hardness,
  213. 'agent_class': agent_class,
  214. 'model_name': model_name,
  215. 'max_iterations': max_iterations,
  216. 'eval_output_dir': eval_output_dir,
  217. 'start_time': time.strftime('%Y-%m-%d %H:%M:%S'),
  218. # get the commit id of current repo for reproduciblity
  219. 'git_commit': subprocess.check_output(['git', 'rev-parse', 'HEAD'])
  220. .decode('utf-8')
  221. .strip(),
  222. }
  223. logger.info(f'Metadata: {metadata}')
  224. with open(
  225. os.path.join(eval_output_dir, f'metadata_{dataset}_{hardness}.json'), 'w'
  226. ) as f:
  227. json.dump(metadata, f)
  228. # LIMIT EVALUATION
  229. eval_n_limit = args.eval_n_limit
  230. if eval_n_limit:
  231. toolqa_test = toolqa_test[:eval_n_limit]
  232. logger.info(
  233. f'Limiting evaluation to a total of first {eval_n_limit} instances.'
  234. )
  235. output_file = os.path.join(
  236. eval_output_dir, f'output_{model_name}_{dataset}_{hardness}.jsonl'
  237. )
  238. logger.info(f'Writing evaluation output to {output_file}')
  239. finished_task_ids = set()
  240. if os.path.exists(output_file):
  241. with open(output_file, 'r') as f:
  242. for line in f:
  243. task = json.loads(line)
  244. finished_task_ids.add(task['qid'])
  245. logger.warning(
  246. f'Output file {output_file} already exists. Loaded {len(finished_task_ids)} finished instances.'
  247. )
  248. output_fp = open(output_file, 'a')
  249. logger.info(
  250. f'Evaluation started with Agent {agent_class}, model {model_name}, max iterations {max_iterations}.'
  251. )
  252. # =============================================
  253. # filter out finished instances
  254. new_toolqa_test = []
  255. for task in toolqa_test:
  256. qid = task['qid']
  257. if qid in finished_task_ids:
  258. logger.info(f'Skipping instance {qid} as it is already finished.')
  259. continue
  260. new_toolqa_test.append(task)
  261. finished_task_number = len(finished_task_ids)
  262. toolqa_test = new_toolqa_test
  263. logger.info(
  264. f'Finished instances: {finished_task_number}, Remaining instances: {len(toolqa_test)}'
  265. )
  266. # =============================================
  267. pbar = tqdm(total=len(toolqa_test))
  268. # This function tracks the progress AND write the output to a JSONL file
  269. def update_progress(future):
  270. pbar.update(1)
  271. output = future.result()
  272. pbar.set_description(f'Instance {output["qid"]}')
  273. pbar.set_postfix_str(f'Test Result: {output["correct"]}')
  274. logger.info(
  275. f'Finished evaluation for instance {output["qid"]}: {output["correct"]}'
  276. )
  277. output_fp.write(json.dumps(output) + '\n')
  278. output_fp.flush()
  279. finished_task_ids.add(output['qid'])
  280. # This sets the multi-processing
  281. num_workers = args.eval_num_workers
  282. logger.info(f'Using {num_workers} workers for evaluation.')
  283. try:
  284. with ProcessPoolExecutor(num_workers) as executor:
  285. futures = []
  286. # This is how we perform multi-processing
  287. for task in toolqa_test:
  288. try:
  289. future = executor.submit(
  290. process_instance,
  291. task,
  292. agent_class,
  293. metadata,
  294. reset_logger=bool(num_workers > 1),
  295. )
  296. future.add_done_callback(update_progress)
  297. futures.append(future)
  298. except Exception:
  299. continue
  300. # Wait for all futures to complete
  301. for future in futures:
  302. try:
  303. future.result()
  304. except Exception:
  305. continue
  306. except KeyboardInterrupt:
  307. logger.info('KeyboardInterrupt received. Cleaning up...')
  308. cleanup()
  309. output_fp.close()
  310. total_correct = 0
  311. output = []
  312. with open(output_file, 'r') as f:
  313. for line in f:
  314. data = json.loads(line)
  315. output.append(data)
  316. if data['qid'] in finished_task_ids:
  317. if str(data['correct']).lower() == 'true':
  318. total_correct += 1
  319. # sort all output by question_id
  320. output = sorted(output, key=lambda x: x['qid'])
  321. with open(output_file, 'w') as f:
  322. for dat in output:
  323. f.write(json.dumps(dat) + '\n')
  324. f.flush()
  325. logger.info(
  326. f'Evaluation finished for {dataset}-{hardness}. Total: {len(toolqa_test)+finished_task_number}; Correct: {total_correct}; Accuracy: {total_correct / (len(toolqa_test)+finished_task_number)}'
  327. )