run_infer.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517
  1. import asyncio
  2. import json
  3. import logging
  4. import multiprocessing as mp
  5. import os
  6. import pathlib
  7. import re
  8. import shutil
  9. import sqlite3
  10. import subprocess
  11. import time
  12. from concurrent.futures import ProcessPoolExecutor
  13. import pandas as pd
  14. from datasets import load_dataset
  15. from func_timeout import FunctionTimedOut, func_timeout
  16. from tqdm import tqdm
  17. from opendevin.controller.state.state import State
  18. from opendevin.core.config import args, config, get_llm_config_arg
  19. from opendevin.core.logger import get_console_handler
  20. from opendevin.core.logger import opendevin_logger as logger
  21. from opendevin.core.main import main
  22. from opendevin.events.action import MessageAction
  23. from opendevin.events.serialization.event import event_to_dict
  24. def cleanup():
  25. logger.info('Cleaning up child processes...')
  26. for process in mp.active_children():
  27. logger.info(f'Terminating child process: {process.name}')
  28. process.terminate()
  29. process.join()
  30. def codeact_user_response(state: State) -> str:
  31. msg = (
  32. 'Please continue working on the task on whatever approach you think is suitable.\n'
  33. 'If you think you have completed the SQL, please run the following command: <execute_bash> exit </execute_bash>.\n'
  34. 'IMPORTANT: YOU SHOULD NEVER ASK FOR HUMAN HELP OR USE THE INTERNET TO SOLVE THIS TASK.\n'
  35. )
  36. if state.history:
  37. user_msgs = [
  38. action
  39. for action, _ in state.history
  40. if isinstance(action, MessageAction) and action.source == 'user'
  41. ]
  42. if len(user_msgs) >= 2:
  43. # let the agent know that it can give up when it has tried 3 times
  44. return (
  45. msg
  46. + 'If you want to give up, run: <execute_bash> exit </execute_bash>.\n'
  47. )
  48. return msg
  49. def monologue_user_response(state: State) -> str:
  50. raise NotImplementedError('MonologueAgent should never ask for user responses.')
  51. AGENT_CLS_TO_FAKE_USER_RESPONSE_FN = {
  52. 'CodeActAgent': codeact_user_response,
  53. 'MonologueAgent': monologue_user_response,
  54. }
  55. AGENT_CLS_TO_INST_SUFFIX = {
  56. 'CodeActAgent': 'When you think you have fixed the issue through code changes, please run the following command: <execute_bash> exit </execute_bash>.\n'
  57. }
  58. def execute_sql(db_path, gen_sql, gold_sql):
  59. """
  60. Execute the generated SQL and the ground truth SQL and compare the results.
  61. """
  62. with sqlite3.connect(db_path) as conn:
  63. cursor = conn.cursor()
  64. cursor.execute(gen_sql)
  65. predicted_res = cursor.fetchall()
  66. cursor.execute(gold_sql)
  67. ground_truth_res = cursor.fetchall()
  68. res = 0
  69. if set(predicted_res) == set(ground_truth_res):
  70. res = 1
  71. return res
  72. def get_test_result(instance, path, timeout=30):
  73. test_result = {'result': {}, 'metadata': {}}
  74. # Read the generated python file
  75. with open(path, 'r') as f:
  76. gen_file = f.read()
  77. # Extract the SQL from the python file
  78. gen_sql = ''
  79. pattern = r'sql\s*=\s*"([^"]+)"'
  80. match = re.search(pattern, gen_file)
  81. if match:
  82. gen_sql = match.group(1)
  83. else:
  84. print('No match found.')
  85. gold_sql = instance.SQL
  86. # Execute the SQL
  87. try:
  88. res = func_timeout(
  89. timeout, execute_sql, args=(instance.db_path, gen_sql, gold_sql)
  90. )
  91. status = 'success'
  92. except FunctionTimedOut:
  93. res = 0
  94. status = 'timeout'
  95. except Exception as e:
  96. res = 0
  97. status = 'error'
  98. logger.error(f'Error: {e}')
  99. # Save the test result
  100. test_result['result'] = {'passed': res, 'status': status}
  101. test_result['metadata'] = {
  102. 'timeout': timeout,
  103. 'gen_sql': gen_sql,
  104. 'gold_sql': gold_sql,
  105. }
  106. return test_result
  107. def process_instance(
  108. instance, agent_class, metadata, skip_workspace_mount, reset_logger: bool = True
  109. ):
  110. workspace_mount_path = os.path.join(
  111. config.workspace_mount_path, 'bird_eval_workspace'
  112. )
  113. # create process-specific workspace dir
  114. # if `not skip_workspace_mount` - we will create a workspace directory for EACH process
  115. # so that different agent don't interfere with each other.
  116. if not skip_workspace_mount:
  117. workspace_mount_path = os.path.join(workspace_mount_path, str(os.getpid()))
  118. pathlib.Path(workspace_mount_path).mkdir(parents=True, exist_ok=True)
  119. # reset workspace to config
  120. config.workspace_mount_path = workspace_mount_path
  121. # Copy the database to the workspace
  122. db_root = os.path.join(
  123. config.workspace_base, 'evaluation_bird/dev/dev_databases', instance.db_id
  124. )
  125. target_path = os.path.join(workspace_mount_path, f'{instance.db_id}')
  126. if not os.path.exists(target_path):
  127. logger.info(f'Copying database from {db_root} to {target_path}...')
  128. shutil.copytree(db_root, target_path)
  129. # Set up the database path
  130. database_path = os.path.join(instance.db_id, f'{instance.db_id}.sqlite')
  131. # Set up the logger properly, so you can run multi-processing to parallelize the evaluation
  132. if reset_logger:
  133. # Set up logger
  134. log_file = os.path.join(
  135. eval_output_dir,
  136. 'logs',
  137. f'instance_{instance.task_id.replace("/", "__")}.log',
  138. )
  139. # Remove all existing handlers from logger
  140. for handler in logger.handlers[:]:
  141. logger.removeHandler(handler)
  142. # add back the console handler to print ONE line
  143. logger.addHandler(get_console_handler())
  144. logger.info(
  145. f'Starting evaluation for instance {instance.task_id}.\nLOG: tail -f {log_file}'
  146. )
  147. # Remove all existing handlers from logger
  148. for handler in logger.handlers[:]:
  149. logger.removeHandler(handler)
  150. file_handler = logging.FileHandler(log_file)
  151. file_handler.setFormatter(
  152. logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')
  153. )
  154. logger.addHandler(file_handler)
  155. if not skip_workspace_mount:
  156. logger.info(f'Process-specific workspace mounted at {workspace_mount_path}')
  157. # Create file with BIRD instance
  158. statements = f"""
  159. import sqlite3
  160. def execute_sql(db_path, sql):
  161. with sqlite3.connect(db_path) as conn:
  162. cursor = conn.cursor()
  163. cursor.execute(sql)
  164. result = cursor.fetchall()
  165. return result
  166. if __name__ == '__main__':
  167. sql = "" # fill in your SQL here
  168. db_path = "{database_path}"
  169. print(db_path)
  170. result = execute_sql(db_path, sql)
  171. print(result)
  172. """
  173. path = os.path.join(
  174. config.workspace_mount_path, f'{instance.task_id.replace("/", "__")}.py'
  175. )
  176. instruction = (
  177. f'You are a SQL expert and need to complete the following text-to-SQL tasks.'
  178. f'\n\n{instance.instruction}\n\n'
  179. 'Please write the SQL in one line without line breaks.'
  180. f'And write a new python file named {instance.task_id.replace("/", "__")}.py to call the SQL you wrote.'
  181. 'You need to follow the code template below:'
  182. f'\n\n{statements}\n\n'
  183. 'Environment has been set up for you to start working.'
  184. 'You may assume all necessary tools are installed.\n\n'
  185. )
  186. instruction += (
  187. 'IMPORTANT: You should ONLY interact with the environment provided to you AND NEVER ASK FOR HUMAN HELP.\n'
  188. 'You SHOULD INCLUDE PROPER INDENTATION in your edit commands.\n'
  189. )
  190. # NOTE: You can actually set slightly different instruction for different agents
  191. instruction += AGENT_CLS_TO_INST_SUFFIX.get(agent_class, '')
  192. # Here's how you can run the agent (similar to the `main` function) and get the final task state
  193. state: State = asyncio.run(
  194. main(
  195. instruction,
  196. fake_user_response_fn=AGENT_CLS_TO_FAKE_USER_RESPONSE_FN.get(agent_class),
  197. )
  198. )
  199. # ======= Attempt to evaluate the agent's edits =======
  200. test_result = get_test_result(instance, path)
  201. # If you are working on some simpler benchmark that only evaluates the final model output (e.g., in a MessageAction)
  202. # You can simply get the LAST `MessageAction` from the returned `state.history` and parse it for evaluation.
  203. if state is None:
  204. raise ValueError('State should not be None.')
  205. metrics = state.metrics.get() if state.metrics else None
  206. # Save the output
  207. output = {
  208. 'task_id': instance.task_id,
  209. 'instruction': instruction,
  210. 'metadata': metadata,
  211. 'history': [
  212. (event_to_dict(action), event_to_dict(obs)) for action, obs in state.history
  213. ],
  214. 'metrics': metrics,
  215. 'error': state.error if state and state.error else None,
  216. 'test_result': test_result,
  217. }
  218. return output
  219. def load_bird():
  220. """
  221. Main function to handle the flow of downloading, processing, and loading the bird dataset.
  222. """
  223. raw_dataset_path = download_bird()
  224. bird_dataset = process_bird(raw_dataset_path)
  225. return bird_dataset
  226. def download_bird():
  227. """
  228. Downloads and extracts the bird dataset from a specified URL into a local directory.
  229. """
  230. dataset_path = os.path.join(config.workspace_base, 'evaluation_bird')
  231. devset_path = os.path.join(dataset_path, 'dev')
  232. if not os.path.exists(dataset_path):
  233. logger.info(
  234. f'{dataset_path} folder does not exist, starting download and extraction...'
  235. )
  236. os.makedirs(dataset_path, exist_ok=True)
  237. download_url = 'https://bird-bench.oss-cn-beijing.aliyuncs.com/dev.zip'
  238. download_path = os.path.join(dataset_path, 'dev.zip')
  239. logger.info('Start Downloading...')
  240. subprocess.run(['wget', download_url, '-O', download_path])
  241. logger.info('Download completed.')
  242. logger.info('Start Extracting...')
  243. subprocess.run(['unzip', download_path, '-d', dataset_path])
  244. # extract databases
  245. devset_path = os.path.join(dataset_path, 'dev')
  246. database_path = os.path.join(devset_path, 'dev_databases.zip')
  247. subprocess.run(['unzip', database_path, '-d', devset_path])
  248. logger.info('Extraction completed.')
  249. else:
  250. logger.info(f'{dataset_path} folder already exists.')
  251. return devset_path
  252. def process_bird(dataset_path):
  253. """
  254. Processes the raw bird dataset into a structured format and saves it as JSON.
  255. """
  256. processed_path = os.path.join(dataset_path, 'processed_dev.json')
  257. if not os.path.exists(processed_path):
  258. logger.info(f'{processed_path} folder does not exist, starting processing...')
  259. raw_data_path = os.path.join(dataset_path, 'dev.json')
  260. database_path = os.path.join(dataset_path, 'dev_databases')
  261. processed_data = []
  262. with pathlib.Path(raw_data_path).open('r') as f:
  263. data = json.load(f)
  264. for e in tqdm(data):
  265. item = {
  266. 'task_id': f'{len(processed_data)}',
  267. 'db_path': os.path.join(
  268. database_path, e['db_id'], f"{e['db_id']}.sqlite"
  269. ),
  270. 'db_id': e['db_id'],
  271. 'instruction': create_prompt(e, database_path),
  272. 'SQL': e['SQL'],
  273. }
  274. processed_data.append(item)
  275. with pathlib.Path(processed_path).open('w') as f:
  276. json.dump(processed_data, f, indent=2)
  277. logger.info(f'Processed data saved to {processed_path}')
  278. else:
  279. logger.info(f'{processed_path} folder already exists.')
  280. bird_dataset = load_dataset('json', data_files={'test': processed_path})
  281. return bird_dataset
  282. def extract_create_table_prompt(db_path, limit_value=0):
  283. """
  284. Generates a SQL prompt with CREATE TABLE statements and sample data from the database.
  285. """
  286. table_query = "SELECT * FROM sqlite_master WHERE type='table';"
  287. tables = sqlite3.connect(db_path).cursor().execute(table_query).fetchall()
  288. prompt = ''
  289. for table in tables:
  290. table_name = table[1]
  291. create_table_statement = table[-1]
  292. table_info_query = f'PRAGMA table_info(`{table_name}`);'
  293. top_k_row_query = f'SELECT * FROM {table_name} LIMIT {limit_value};'
  294. try:
  295. headers = [
  296. x[1]
  297. for x in sqlite3.connect(db_path)
  298. .cursor()
  299. .execute(table_info_query)
  300. .fetchall()
  301. ]
  302. except Exception:
  303. logger.error(f'Error Connection: {table_info_query}, {top_k_row_query}')
  304. exit(0)
  305. prompt += create_table_statement + ';\n'
  306. if limit_value > 0:
  307. top_k_rows = (
  308. sqlite3.connect(db_path).cursor().execute(top_k_row_query).fetchall()
  309. )
  310. prompt += (
  311. f"/*\n3 example rows:\n{top_k_row_query}\n{' '.join(headers)}\n"
  312. )
  313. for row in top_k_rows:
  314. row = [str(x) for x in row]
  315. row = [x if x is not None else '' for x in row]
  316. prompt += ' '.join(row) + '\n'
  317. prompt += '*/\n'
  318. prompt += '\n'
  319. return prompt
  320. def create_prompt(e, database_path):
  321. """
  322. Create a prompt for the given example
  323. """
  324. db_id = e['db_id']
  325. db_path = pathlib.Path(database_path) / db_id / f'{db_id}.sqlite'
  326. # Extract the CREATE TABLE statements and sample data from the database
  327. prompt = extract_create_table_prompt(db_path)
  328. prompt += f"-- External Knowledge: {e['evidence']}\n\n"
  329. prompt += '-- Using valid SQLite and understanding External Knowledge, answer the following questions for the tables provided above.\n\n'
  330. prompt += '-- Using valid SQLite, answer the following questions for the tables provided above.\n'
  331. prompt += f"Question: {e['question']}\n"
  332. return prompt
  333. if __name__ == '__main__':
  334. # NOTE: It is preferable to load datasets from huggingface datasets and perform post-processing
  335. # so we don't need to manage file uploading to OpenDevin's repo
  336. # Due to the large size of the BIRD database, it cannot be hosted on huggingface datasets, so it needs to be downloaded
  337. bird_dataset = load_bird()
  338. bird_tests = bird_dataset['test'].to_pandas()
  339. # Check https://github.com/OpenDevin/OpenDevin/blob/main/evaluation/humanevalfix/README.md#configure-opendevin-and-your-llm
  340. # for details of how to set `llm_config`
  341. if args.llm_config:
  342. specified_llm_config = get_llm_config_arg(args.llm_config)
  343. if specified_llm_config:
  344. config.llm = specified_llm_config
  345. logger.info(f'Config for evaluation: {config}')
  346. # TEST METADATA
  347. agent_class = args.agent_cls
  348. assert (
  349. agent_class in AGENT_CLS_TO_FAKE_USER_RESPONSE_FN
  350. ), f'Unsupported agent class: {agent_class}'
  351. model_name = config.llm.model.split('/')[-1]
  352. max_iterations = args.max_iterations
  353. eval_note = ''
  354. if args.eval_note is not None:
  355. eval_note += '_N_' + args.eval_note
  356. eval_output_dir = os.path.join(
  357. args.eval_output_dir,
  358. 'bird',
  359. agent_class,
  360. model_name + '_maxiter_' + str(max_iterations) + eval_note,
  361. )
  362. pathlib.Path(eval_output_dir).mkdir(parents=True, exist_ok=True)
  363. pathlib.Path(os.path.join(eval_output_dir, 'logs')).mkdir(
  364. parents=True, exist_ok=True
  365. )
  366. logger.info(f'Using evaluation output directory: {eval_output_dir}')
  367. metadata = {
  368. 'agent_class': agent_class,
  369. 'model_name': model_name,
  370. 'max_iterations': max_iterations,
  371. 'eval_output_dir': eval_output_dir,
  372. 'start_time': time.strftime('%Y-%m-%d %H:%M:%S'),
  373. # get the commit id of current repo for reproducibility
  374. 'git_commit': subprocess.check_output(['git', 'rev-parse', 'HEAD'])
  375. .decode('utf-8')
  376. .strip(),
  377. }
  378. logger.info(f'Metadata: {metadata}')
  379. with open(os.path.join(eval_output_dir, 'metadata.json'), 'w') as f:
  380. json.dump(metadata, f)
  381. # LIMIT EVALUATION
  382. eval_n_limit = args.eval_n_limit
  383. if eval_n_limit:
  384. bird_tests = bird_tests.head(eval_n_limit)
  385. logger.info(f'Limiting evaluation to first {eval_n_limit} instances.')
  386. # OUTPUT FILE
  387. output_file = os.path.join(eval_output_dir, 'output.jsonl')
  388. logger.info(f'Writing evaluation output to {output_file}')
  389. finished_instance_ids = set()
  390. if os.path.exists(output_file):
  391. with open(output_file, 'r') as f:
  392. for line in f:
  393. data = json.loads(line)
  394. finished_instance_ids.add(data['task_id'])
  395. logger.warning(
  396. f'Output file {output_file} already exists. Loaded {len(finished_instance_ids)} finished instances.'
  397. )
  398. output_fp = open(output_file, 'a')
  399. logger.info(
  400. f'Evaluation started with Agent {agent_class}, model {model_name}, max iterations {max_iterations}.'
  401. )
  402. # =============================================
  403. # filter out finished instances
  404. new_bird_tests = []
  405. for idx, instance in bird_tests.iterrows():
  406. if instance.task_id in finished_instance_ids:
  407. logger.info(
  408. f'Skipping instance {instance.task_id} as it is already finished.'
  409. )
  410. continue
  411. new_bird_tests.append(instance)
  412. bird_tests = pd.DataFrame(new_bird_tests)
  413. logger.info(
  414. f'Finished instances: {len(finished_instance_ids)}, Remaining instances: {len(bird_tests)}'
  415. )
  416. # =============================================
  417. pbar = tqdm(total=len(bird_tests))
  418. # This function tracks the progress AND write the output to a JSONL file
  419. def update_progress(future):
  420. pbar.update(1)
  421. output = future.result()
  422. pbar.set_description(f'Instance {output["task_id"]}')
  423. pbar.set_postfix_str(f'Test Result: {output["test_result"]["result"]}')
  424. logger.info(
  425. f'Finished evaluation for instance {output["task_id"]}: {output["test_result"]["result"]}'
  426. )
  427. output_fp.write(json.dumps(output) + '\n')
  428. output_fp.flush()
  429. # This sets the multi-processing
  430. num_workers = args.eval_num_workers
  431. logger.info(f'Using {num_workers} workers for evaluation.')
  432. try:
  433. with ProcessPoolExecutor(num_workers) as executor:
  434. futures = []
  435. # This is how we perform multi-processing
  436. for row_idx, instance in bird_tests.iterrows():
  437. future = executor.submit(
  438. process_instance,
  439. instance,
  440. agent_class,
  441. metadata,
  442. skip_workspace_mount=False,
  443. reset_logger=bool(num_workers > 1),
  444. )
  445. future.add_done_callback(update_progress)
  446. futures.append(future)
  447. # Wait for all futures to complete
  448. for future in futures:
  449. future.result()
  450. except KeyboardInterrupt:
  451. print('KeyboardInterrupt received. Cleaning up...')
  452. cleanup()
  453. output_fp.close()
  454. logger.info('Evaluation finished.')