run_infer.py 15 KB

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