run_infer.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399
  1. import asyncio
  2. import json
  3. import logging
  4. import os
  5. import pathlib
  6. import re
  7. import shutil
  8. import sqlite3
  9. import subprocess
  10. import pandas as pd
  11. from datasets import load_dataset
  12. from func_timeout import FunctionTimedOut, func_timeout
  13. from tqdm import tqdm
  14. from evaluation.utils.shared import (
  15. EvalMetadata,
  16. make_metadata,
  17. prepare_dataset,
  18. run_evaluation,
  19. )
  20. from opendevin.controller.agent import Agent
  21. from opendevin.controller.state.state import State
  22. from opendevin.core.config import get_llm_config_arg, load_app_config, parse_arguments
  23. from opendevin.core.logger import get_console_handler
  24. from opendevin.core.logger import opendevin_logger as logger
  25. from opendevin.core.main import run_agent_controller
  26. from opendevin.events.action import MessageAction
  27. from opendevin.llm.llm import LLM
  28. config = load_app_config()
  29. def codeact_user_response(state: State) -> str:
  30. msg = (
  31. 'Please continue working on the task on whatever approach you think is suitable.\n'
  32. 'If you think you have completed the SQL, please run the following command: <execute_bash> exit </execute_bash>.\n'
  33. 'IMPORTANT: YOU SHOULD NEVER ASK FOR HUMAN HELP OR USE THE INTERNET TO SOLVE THIS TASK.\n'
  34. )
  35. if state.history:
  36. # check if the agent has tried to talk to the user 3 times, if so, let the agent know it can give up
  37. user_msgs = [
  38. event
  39. for event in state.history.get_events()
  40. if isinstance(event, MessageAction) and event.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. AGENT_CLS_TO_FAKE_USER_RESPONSE_FN = {
  50. 'CodeActAgent': codeact_user_response,
  51. }
  52. AGENT_CLS_TO_INST_SUFFIX = {
  53. 'CodeActAgent': 'When you think you have fixed the issue through code changes, please run the following command: <execute_bash> exit </execute_bash>.\n'
  54. }
  55. def execute_sql(db_path, gen_sql, gold_sql):
  56. """Execute the generated SQL and the ground truth SQL and compare the results."""
  57. with sqlite3.connect(db_path) as conn:
  58. cursor = conn.cursor()
  59. cursor.execute(gen_sql)
  60. predicted_res = cursor.fetchall()
  61. cursor.execute(gold_sql)
  62. ground_truth_res = cursor.fetchall()
  63. res = 0
  64. if set(predicted_res) == set(ground_truth_res):
  65. res = 1
  66. return res
  67. def get_test_result(instance, path, timeout=30):
  68. test_result = {'result': {}, 'metadata': {}}
  69. # Read the generated python file
  70. with open(path, 'r') as f:
  71. gen_file = f.read()
  72. # Extract the SQL from the python file
  73. gen_sql = ''
  74. pattern = r'sql\s*=\s*"([^"]+)"'
  75. match = re.search(pattern, gen_file)
  76. if match:
  77. gen_sql = match.group(1)
  78. else:
  79. print('No match found.')
  80. gold_sql = instance.SQL
  81. # Execute the SQL
  82. try:
  83. res = func_timeout(
  84. timeout, execute_sql, args=(instance.db_path, gen_sql, gold_sql)
  85. )
  86. status = 'success'
  87. except FunctionTimedOut:
  88. res = 0
  89. status = 'timeout'
  90. except Exception as e:
  91. res = 0
  92. status = 'error'
  93. logger.error(f'Error: {e}')
  94. # Save the test result
  95. test_result['result'] = {'passed': res, 'status': status}
  96. test_result['metadata'] = {
  97. 'timeout': timeout,
  98. 'gen_sql': gen_sql,
  99. 'gold_sql': gold_sql,
  100. }
  101. return test_result
  102. def process_instance(
  103. instance: pd.Series,
  104. metadata: EvalMetadata,
  105. reset_logger: bool = True,
  106. ):
  107. # Create the agent
  108. agent = Agent.get_cls(metadata.agent_class)(llm=LLM(config=metadata.llm_config))
  109. workspace_mount_path = os.path.join(
  110. config.workspace_mount_path, 'bird_eval_workspace'
  111. )
  112. workspace_mount_path = os.path.join(workspace_mount_path, str(os.getpid()))
  113. pathlib.Path(workspace_mount_path).mkdir(parents=True, exist_ok=True)
  114. # reset workspace to config
  115. config.workspace_mount_path = workspace_mount_path
  116. # Copy the database to the workspace
  117. db_root = os.path.join(
  118. config.workspace_base, 'evaluation_bird/dev/dev_databases', instance.db_id
  119. )
  120. target_path = os.path.join(workspace_mount_path, f'{instance.db_id}')
  121. if not os.path.exists(target_path):
  122. logger.info(f'Copying database from {db_root} to {target_path}...')
  123. shutil.copytree(db_root, target_path)
  124. # Set up the database path
  125. database_path = os.path.join(instance.db_id, f'{instance.db_id}.sqlite')
  126. # use session id for concurrent evaluation
  127. sid = instance.task_id.replace('/', '__')
  128. # Set up the logger properly, so you can run multi-processing to parallelize the evaluation
  129. if reset_logger:
  130. # Set up logger
  131. log_file = os.path.join(
  132. metadata.eval_output_dir,
  133. 'logs',
  134. f'instance_{sid}.log',
  135. )
  136. # Remove all existing handlers from logger
  137. for handler in logger.handlers[:]:
  138. logger.removeHandler(handler)
  139. # add back the console handler to print ONE line
  140. logger.addHandler(get_console_handler())
  141. logger.info(
  142. f'Starting evaluation for instance {instance.task_id}.\nLOG: tail -f {log_file}'
  143. )
  144. # Remove all existing handlers from logger
  145. for handler in logger.handlers[:]:
  146. logger.removeHandler(handler)
  147. file_handler = logging.FileHandler(log_file)
  148. file_handler.setFormatter(
  149. logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')
  150. )
  151. logger.addHandler(file_handler)
  152. logger.info(f'Process-specific workspace mounted at {workspace_mount_path}')
  153. # Create file with BIRD instance
  154. statements = f"""
  155. import sqlite3
  156. def execute_sql(db_path, sql):
  157. with sqlite3.connect(db_path) as conn:
  158. cursor = conn.cursor()
  159. cursor.execute(sql)
  160. result = cursor.fetchall()
  161. return result
  162. if __name__ == '__main__':
  163. sql = "" # fill in your SQL here
  164. db_path = "{database_path}"
  165. print(db_path)
  166. result = execute_sql(db_path, sql)
  167. print(result)
  168. """
  169. path = os.path.join(config.workspace_mount_path, f'{sid}.py')
  170. instruction = (
  171. f'You are a SQL expert and need to complete the following text-to-SQL tasks.'
  172. f'\n\n{instance.instruction}\n\n'
  173. 'Please write the SQL in one line without line breaks.'
  174. f'And write a new python file named {sid}.py to call the SQL you wrote.'
  175. 'You need to follow the code template below:'
  176. f'\n\n{statements}\n\n'
  177. 'Environment has been set up for you to start working.'
  178. 'You may assume all necessary tools are installed.\n\n'
  179. )
  180. instruction += (
  181. 'IMPORTANT: You should ONLY interact with the environment provided to you AND NEVER ASK FOR HUMAN HELP.\n'
  182. 'You SHOULD INCLUDE PROPER INDENTATION in your edit commands.\n'
  183. )
  184. # NOTE: You can actually set slightly different instruction for different agents
  185. instruction += AGENT_CLS_TO_INST_SUFFIX[agent.__class__.__name__]
  186. # Here's how you can run the agent (similar to the `main` function) and get the final task state
  187. state: State | None = asyncio.run(
  188. run_agent_controller(
  189. agent,
  190. instruction,
  191. max_iterations=metadata.max_iterations,
  192. max_budget_per_task=config.max_budget_per_task,
  193. fake_user_response_fn=AGENT_CLS_TO_FAKE_USER_RESPONSE_FN[
  194. agent.__class__.__name__
  195. ],
  196. sid=sid,
  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. # history is now available as a stream of events, rather than list of pairs of (Action, Observation)
  207. # for compatibility with the existing output format, we can remake the pairs here
  208. # remove when it becomes unnecessary
  209. histories = state.history.compatibility_for_eval_history_pairs()
  210. # Save the output
  211. output = {
  212. 'task_id': instance.task_id,
  213. 'instruction': instruction,
  214. 'metadata': metadata.model_dump(),
  215. 'history': histories,
  216. 'metrics': metrics,
  217. 'error': state.last_error if state and state.last_error else None,
  218. 'test_result': test_result,
  219. }
  220. return output
  221. def load_bird():
  222. """Main function to handle the flow of downloading, processing, and loading the bird dataset."""
  223. raw_dataset_path = download_bird()
  224. bird_dataset = process_bird(raw_dataset_path)
  225. return bird_dataset
  226. def download_bird():
  227. """Downloads and extracts the bird dataset from a specified URL into a local directory."""
  228. dataset_path = os.path.join(config.workspace_base, 'evaluation_bird')
  229. devset_path = os.path.join(dataset_path, 'dev')
  230. if not os.path.exists(dataset_path):
  231. logger.info(
  232. f'{dataset_path} folder does not exist, starting download and extraction...'
  233. )
  234. os.makedirs(dataset_path, exist_ok=True)
  235. download_url = 'https://bird-bench.oss-cn-beijing.aliyuncs.com/dev.zip'
  236. download_path = os.path.join(dataset_path, 'dev.zip')
  237. logger.info('Start Downloading...')
  238. subprocess.run(['wget', download_url, '-O', download_path])
  239. logger.info('Download completed.')
  240. logger.info('Start Extracting...')
  241. subprocess.run(['unzip', download_path, '-d', dataset_path])
  242. # extract databases
  243. devset_path = os.path.join(dataset_path, 'dev')
  244. database_path = os.path.join(devset_path, 'dev_databases.zip')
  245. subprocess.run(['unzip', database_path, '-d', devset_path])
  246. logger.info('Extraction completed.')
  247. else:
  248. logger.info(f'{dataset_path} folder already exists.')
  249. return devset_path
  250. def process_bird(dataset_path):
  251. """Processes the raw bird dataset into a structured format and saves it as JSON."""
  252. processed_path = os.path.join(dataset_path, 'processed_dev.json')
  253. if not os.path.exists(processed_path):
  254. logger.info(f'{processed_path} folder does not exist, starting processing...')
  255. raw_data_path = os.path.join(dataset_path, 'dev.json')
  256. database_path = os.path.join(dataset_path, 'dev_databases')
  257. processed_data = []
  258. with pathlib.Path(raw_data_path).open('r') as f:
  259. data = json.load(f)
  260. for e in tqdm(data):
  261. item = {
  262. 'task_id': f'{len(processed_data)}',
  263. 'db_path': os.path.join(
  264. database_path, e['db_id'], f"{e['db_id']}.sqlite"
  265. ),
  266. 'db_id': e['db_id'],
  267. 'instruction': create_prompt(e, database_path),
  268. 'SQL': e['SQL'],
  269. }
  270. processed_data.append(item)
  271. with pathlib.Path(processed_path).open('w') as f:
  272. json.dump(processed_data, f, indent=2)
  273. logger.info(f'Processed data saved to {processed_path}')
  274. else:
  275. logger.info(f'{processed_path} folder already exists.')
  276. bird_dataset = load_dataset('json', data_files={'test': processed_path})
  277. return bird_dataset
  278. def extract_create_table_prompt(db_path, limit_value=0):
  279. """Generates a SQL prompt with CREATE TABLE statements and sample data from the database."""
  280. table_query = "SELECT * FROM sqlite_master WHERE type='table';"
  281. tables = sqlite3.connect(db_path).cursor().execute(table_query).fetchall()
  282. prompt = ''
  283. for table in tables:
  284. table_name = table[1]
  285. create_table_statement = table[-1]
  286. table_info_query = f'PRAGMA table_info(`{table_name}`);'
  287. top_k_row_query = f'SELECT * FROM {table_name} LIMIT {limit_value};'
  288. try:
  289. headers = [
  290. x[1]
  291. for x in sqlite3.connect(db_path)
  292. .cursor()
  293. .execute(table_info_query)
  294. .fetchall()
  295. ]
  296. except Exception:
  297. logger.error(f'Error Connection: {table_info_query}, {top_k_row_query}')
  298. exit(0)
  299. prompt += create_table_statement + ';\n'
  300. if limit_value > 0:
  301. top_k_rows = (
  302. sqlite3.connect(db_path).cursor().execute(top_k_row_query).fetchall()
  303. )
  304. prompt += (
  305. f"/*\n3 example rows:\n{top_k_row_query}\n{' '.join(headers)}\n"
  306. )
  307. for row in top_k_rows:
  308. row = [str(x) for x in row]
  309. row = [x if x is not None else '' for x in row]
  310. prompt += ' '.join(row) + '\n'
  311. prompt += '*/\n'
  312. prompt += '\n'
  313. return prompt
  314. def create_prompt(e, database_path):
  315. """Create a prompt for the given example"""
  316. db_id = e['db_id']
  317. db_path = pathlib.Path(database_path) / db_id / f'{db_id}.sqlite'
  318. # Extract the CREATE TABLE statements and sample data from the database
  319. prompt = extract_create_table_prompt(db_path)
  320. prompt += f"-- External Knowledge: {e['evidence']}\n\n"
  321. prompt += '-- Using valid SQLite and understanding External Knowledge, answer the following questions for the tables provided above.\n\n'
  322. prompt += '-- Using valid SQLite, answer the following questions for the tables provided above.\n'
  323. prompt += f"Question: {e['question']}\n"
  324. return prompt
  325. if __name__ == '__main__':
  326. id_column = 'task_id'
  327. args = parse_arguments()
  328. bird_dataset = load_bird()
  329. dataset = bird_dataset['test'].to_pandas()
  330. llm_config = get_llm_config_arg(args.llm_config) if args.llm_config else config.llm
  331. logger.info(f'Config for evaluation: {config}')
  332. metadata = make_metadata(
  333. llm_config,
  334. args.dataset_name,
  335. args.agent_cls,
  336. args.max_iterations,
  337. args.eval_note,
  338. args.eval_output_dir,
  339. )
  340. output_file = os.path.join(metadata.eval_output_dir, 'output.jsonl')
  341. instances = prepare_dataset(dataset, output_file, args.eval_n_limit, id_column)
  342. run_evaluation(
  343. instances,
  344. metadata,
  345. output_file,
  346. args.eval_num_workers,
  347. process_instance,
  348. id_column,
  349. )