run_infer.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472
  1. import asyncio
  2. import json
  3. import os
  4. import pathlib
  5. import re
  6. import sqlite3
  7. import subprocess
  8. import zipfile
  9. from typing import Any
  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. EvalOutput,
  17. make_metadata,
  18. prepare_dataset,
  19. reset_logger_for_multiprocessing,
  20. run_evaluation,
  21. )
  22. from openhands.controller.state.state import State
  23. from openhands.core.config import (
  24. AppConfig,
  25. SandboxConfig,
  26. get_llm_config_arg,
  27. parse_arguments,
  28. )
  29. from openhands.core.logger import openhands_logger as logger
  30. from openhands.core.main import create_runtime, run_controller
  31. from openhands.events.action import CmdRunAction, MessageAction
  32. from openhands.events.observation import CmdOutputObservation
  33. from openhands.runtime.runtime import Runtime
  34. def codeact_user_response(state: State) -> str:
  35. msg = (
  36. 'Please continue working on the task on whatever approach you think is suitable.\n'
  37. 'If you think you have completed the SQL, please run the following command: <execute_bash> exit </execute_bash>.\n'
  38. 'IMPORTANT: YOU SHOULD NEVER ASK FOR HUMAN HELP OR USE THE INTERNET TO SOLVE THIS TASK.\n'
  39. )
  40. if state.history:
  41. # check if the agent has tried to talk to the user 3 times, if so, let the agent know it can give up
  42. user_msgs = [
  43. event
  44. for event in state.history.get_events()
  45. if isinstance(event, MessageAction) and event.source == 'user'
  46. ]
  47. if len(user_msgs) > 2:
  48. # let the agent know that it can give up when it has tried 3 times
  49. return (
  50. msg
  51. + 'If you want to give up, run: <execute_bash> exit </execute_bash>.\n'
  52. )
  53. return msg
  54. AGENT_CLS_TO_FAKE_USER_RESPONSE_FN = {
  55. 'CodeActAgent': codeact_user_response,
  56. }
  57. AGENT_CLS_TO_INST_SUFFIX = {
  58. 'CodeActAgent': 'When you think you have fixed the issue through code changes, please run the following command: <execute_bash> exit </execute_bash>.\n'
  59. }
  60. def get_config(
  61. metadata: EvalMetadata,
  62. ) -> AppConfig:
  63. config = AppConfig(
  64. default_agent=metadata.agent_class,
  65. run_as_openhands=False,
  66. runtime='eventstream',
  67. max_iterations=metadata.max_iterations,
  68. sandbox=SandboxConfig(
  69. base_container_image='python:3.11-bookworm',
  70. enable_auto_lint=True,
  71. use_host_network=False,
  72. ),
  73. # do not mount workspace
  74. workspace_base=None,
  75. workspace_mount_path=None,
  76. )
  77. config.set_llm_config(metadata.llm_config)
  78. return config
  79. def execute_sql(db_path, gen_sql, gold_sql):
  80. """Execute the generated SQL and the ground truth SQL and compare the results."""
  81. with sqlite3.connect(db_path) as conn:
  82. cursor = conn.cursor()
  83. cursor.execute(gen_sql)
  84. predicted_res = cursor.fetchall()
  85. cursor.execute(gold_sql)
  86. ground_truth_res = cursor.fetchall()
  87. res = 0
  88. if set(predicted_res) == set(ground_truth_res):
  89. res = 1
  90. return res
  91. LOCAL_DATASET_PATH = os.path.join(os.path.dirname(__file__), 'data')
  92. def load_bird():
  93. """Main function to handle the flow of downloading, processing, and loading the bird dataset."""
  94. def _download_bird():
  95. """Downloads and extracts the bird dataset from a specified URL into a local directory."""
  96. devset_path = os.path.join(LOCAL_DATASET_PATH, 'dev')
  97. if not os.path.exists(devset_path):
  98. logger.info(
  99. f'{LOCAL_DATASET_PATH} folder does not exist, starting download and extraction...'
  100. )
  101. os.makedirs(LOCAL_DATASET_PATH, exist_ok=True)
  102. download_url = 'https://bird-bench.oss-cn-beijing.aliyuncs.com/dev.zip'
  103. download_path = os.path.join(LOCAL_DATASET_PATH, 'dev.zip')
  104. if not os.path.exists(download_path):
  105. logger.info('Start Downloading...')
  106. subprocess.run(['wget', download_url, '-O', download_path])
  107. logger.info('Download completed.')
  108. devset_path = os.path.join(LOCAL_DATASET_PATH, 'dev')
  109. if not os.path.exists(devset_path):
  110. logger.info('Start Extracting...')
  111. os.makedirs(devset_path, exist_ok=True)
  112. with zipfile.ZipFile(download_path, 'r') as zip_ref:
  113. zip_ref.extractall(devset_path)
  114. # move everything in 'dev_20240627' to the root folder
  115. for file in os.listdir(os.path.join(devset_path, 'dev_20240627')):
  116. os.rename(
  117. os.path.join(devset_path, 'dev_20240627', file),
  118. os.path.join(devset_path, file),
  119. )
  120. os.rmdir(os.path.join(devset_path, 'dev_20240627'))
  121. logger.info('Extraction completed.')
  122. # extract databases
  123. database_path = os.path.join(devset_path, 'dev_databases.zip')
  124. assert os.path.exists(database_path)
  125. logger.info('Start Extracting...')
  126. with zipfile.ZipFile(database_path, 'r') as zip_ref:
  127. zip_ref.extractall(devset_path)
  128. logger.info('Extraction completed.')
  129. else:
  130. logger.info(f'{LOCAL_DATASET_PATH} folder already exists.')
  131. return devset_path
  132. def _extract_create_table_prompt(db_path, limit_value=0):
  133. """Generates a SQL prompt with CREATE TABLE statements and sample data from the database."""
  134. table_query = "SELECT * FROM sqlite_master WHERE type='table';"
  135. tables = sqlite3.connect(db_path).cursor().execute(table_query).fetchall()
  136. prompt = ''
  137. for table in tables:
  138. table_name = table[1]
  139. create_table_statement = table[-1]
  140. table_info_query = f'PRAGMA table_info(`{table_name}`);'
  141. top_k_row_query = f'SELECT * FROM {table_name} LIMIT {limit_value};'
  142. try:
  143. headers = [
  144. x[1]
  145. for x in sqlite3.connect(db_path)
  146. .cursor()
  147. .execute(table_info_query)
  148. .fetchall()
  149. ]
  150. except Exception:
  151. logger.error(f'Error Connection: {table_info_query}, {top_k_row_query}')
  152. exit(0)
  153. prompt += create_table_statement + ';\n'
  154. if limit_value > 0:
  155. top_k_rows = (
  156. sqlite3.connect(db_path)
  157. .cursor()
  158. .execute(top_k_row_query)
  159. .fetchall()
  160. )
  161. prompt += (
  162. f"/*\n3 example rows:\n{top_k_row_query}\n{' '.join(headers)}\n"
  163. )
  164. for row in top_k_rows:
  165. row = [str(x) for x in row]
  166. row = [x if x is not None else '' for x in row]
  167. prompt += ' '.join(row) + '\n'
  168. prompt += '*/\n'
  169. prompt += '\n'
  170. return prompt
  171. def _create_prompt(e, database_path):
  172. """Create a prompt for the given example"""
  173. db_id = e['db_id']
  174. db_path = pathlib.Path(database_path) / db_id / f'{db_id}.sqlite'
  175. # Extract the CREATE TABLE statements and sample data from the database
  176. prompt = _extract_create_table_prompt(db_path)
  177. prompt += f"-- External Knowledge: {e['evidence']}\n\n"
  178. prompt += '-- Using valid SQLite and understanding External Knowledge, answer the following questions for the tables provided above.\n\n'
  179. prompt += '-- Using valid SQLite, answer the following questions for the tables provided above.\n'
  180. prompt += f"Question: {e['question']}\n"
  181. return prompt
  182. def _process_bird(dataset_path):
  183. """Processes the raw bird dataset into a structured format and saves it as JSON."""
  184. processed_path = os.path.join(LOCAL_DATASET_PATH, 'dev', 'processed_dev.json')
  185. if not os.path.exists(processed_path):
  186. logger.info(
  187. f'{processed_path} folder does not exist, starting processing...'
  188. )
  189. raw_data_path = os.path.join(LOCAL_DATASET_PATH, 'dev', 'dev.json')
  190. database_path = os.path.join(LOCAL_DATASET_PATH, 'dev', 'dev_databases')
  191. processed_data = []
  192. with pathlib.Path(raw_data_path).open('r') as f:
  193. data = json.load(f)
  194. for e in tqdm(data):
  195. item = {
  196. 'instance_id': f'{len(processed_data)}',
  197. 'db_path': os.path.join(
  198. database_path, e['db_id'], f"{e['db_id']}.sqlite"
  199. ),
  200. 'db_id': e['db_id'],
  201. 'instruction': _create_prompt(e, database_path),
  202. 'SQL': e['SQL'],
  203. }
  204. processed_data.append(item)
  205. with pathlib.Path(processed_path).open('w') as f:
  206. json.dump(processed_data, f, indent=2)
  207. logger.info(f'Processed data saved to {processed_path}')
  208. else:
  209. logger.info(f'{processed_path} folder already exists.')
  210. bird_dataset = load_dataset('json', data_files={'test': processed_path})
  211. return bird_dataset
  212. raw_dataset_path = _download_bird()
  213. bird_dataset = _process_bird(raw_dataset_path)
  214. return bird_dataset
  215. def initialize_runtime(
  216. runtime: Runtime,
  217. instance: pd.Series, # this argument is not required
  218. ):
  219. """Initialize the runtime for the agent.
  220. This function is called before the runtime is used to run the agent.
  221. """
  222. logger.info(f"{'-' * 50} BEGIN Runtime Initialization Fn {'-' * 50}")
  223. obs: CmdOutputObservation
  224. # Copy the database to the workspace
  225. db_file = os.path.join(
  226. LOCAL_DATASET_PATH,
  227. 'dev',
  228. 'dev_databases',
  229. instance.db_id,
  230. f'{instance.db_id}.sqlite',
  231. )
  232. runtime.copy_to(db_file, '/workspace')
  233. # Check the database is copied
  234. action = CmdRunAction(
  235. command='cd /workspace && ls -l',
  236. keep_prompt=False,
  237. )
  238. obs = runtime.run_action(action)
  239. logger.info(obs, extra={'msg_type': 'OBSERVATION'})
  240. assert obs.exit_code == 0
  241. assert f'{instance.db_id}.sqlite' in obs.content
  242. logger.info(f"{'-' * 50} END Runtime Initialization Fn {'-' * 50}")
  243. def complete_runtime(
  244. runtime: Runtime,
  245. instance: pd.Series, # this argument is not required, but it is used to get the workspace_dir_name
  246. ) -> dict[str, Any]:
  247. """Complete the runtime for the agent.
  248. This function is called before the runtime is used to run the agent.
  249. If you need to do something in the sandbox to get the correctness metric after
  250. the agent has run, modify this function.
  251. """
  252. logger.info(f"{'-' * 50} BEGIN Runtime Completion Fn {'-' * 50}")
  253. obs: CmdOutputObservation
  254. timeout = 30
  255. test_result = {'result': {}, 'metadata': {}}
  256. # Read the generated python file
  257. instance_id = instance.instance_id.replace('/', '__')
  258. path = os.path.join('/workspace', f'{instance_id}.py')
  259. action = CmdRunAction(
  260. command=f'cat {path}',
  261. keep_prompt=False,
  262. )
  263. obs = runtime.run_action(action)
  264. logger.info(obs, extra={'msg_type': 'OBSERVATION'})
  265. if obs.exit_code != 0:
  266. test_result['result'] = {'passed': 0, 'status': 'error'}
  267. return test_result
  268. gen_file = obs.content.strip().replace('\r\n', '\n')
  269. # Extract the SQL from the python file
  270. gen_sql = ''
  271. pattern = r'sql\s*=\s*"([^"]+)"'
  272. match = re.search(pattern, gen_file)
  273. if match:
  274. gen_sql = match.group(1)
  275. else:
  276. print('No match found.')
  277. gold_sql = instance.SQL
  278. # Execute the SQL
  279. try:
  280. res = func_timeout(
  281. timeout,
  282. execute_sql,
  283. args=(
  284. instance.db_path,
  285. gen_sql,
  286. gold_sql,
  287. ),
  288. )
  289. status = 'success'
  290. except FunctionTimedOut:
  291. res = 0
  292. status = 'timeout'
  293. except Exception as e:
  294. res = 0
  295. status = 'error'
  296. logger.error(f'Error: {e}')
  297. # Save the test result
  298. test_result['result'] = {'passed': res, 'status': status}
  299. test_result['metadata'] = {
  300. 'timeout': timeout,
  301. 'gen_sql': gen_sql,
  302. 'gold_sql': gold_sql,
  303. }
  304. logger.info(f"{'-' * 50} END Runtime Completion Fn {'-' * 50}")
  305. return test_result
  306. def process_instance(
  307. instance: pd.Series,
  308. metadata: EvalMetadata,
  309. reset_logger: bool = True,
  310. ) -> EvalOutput:
  311. config = get_config(metadata)
  312. # use session id for concurrent evaluation
  313. instance_id = instance.instance_id.replace('/', '__')
  314. # Set up the logger properly, so you can run multi-processing to parallelize the evaluation
  315. if reset_logger:
  316. log_dir = os.path.join(metadata.eval_output_dir, 'infer_logs')
  317. reset_logger_for_multiprocessing(logger, instance_id, log_dir)
  318. else:
  319. logger.info(f'Starting evaluation for instance {instance_id}.')
  320. # Create file with BIRD instance
  321. database_path = os.path.join('/workspace', f'{instance.db_id}.sqlite')
  322. statements = f"""
  323. import sqlite3
  324. def execute_sql(db_path, sql):
  325. with sqlite3.connect(db_path) as conn:
  326. cursor = conn.cursor()
  327. cursor.execute(sql)
  328. result = cursor.fetchall()
  329. return result
  330. if __name__ == '__main__':
  331. sql = "" # fill in your SQL here
  332. db_path = "{database_path}"
  333. print(db_path)
  334. result = execute_sql(db_path, sql)
  335. print(result)
  336. """
  337. instruction = (
  338. f'You are a SQL expert and need to complete the following text-to-SQL tasks.'
  339. f'\n\n{instance.instruction}\n\n'
  340. 'Please write the SQL in one line without line breaks.'
  341. f'And write a new python file named {instance_id}.py to call the SQL you wrote.'
  342. 'You need to follow the code template below:'
  343. f'\n\n{statements}\n\n'
  344. 'Environment has been set up for you to start working.'
  345. 'You may assume all necessary tools are installed.\n\n'
  346. )
  347. instruction += (
  348. 'IMPORTANT: You should ONLY interact with the environment provided to you AND NEVER ASK FOR HUMAN HELP.\n'
  349. 'You SHOULD INCLUDE PROPER INDENTATION in your edit commands.\n'
  350. )
  351. # NOTE: You can actually set slightly different instruction for different agents
  352. instruction += AGENT_CLS_TO_INST_SUFFIX[metadata.agent_class]
  353. runtime = create_runtime(config, sid=instance_id)
  354. initialize_runtime(runtime, instance)
  355. # Here's how you can run the agent (similar to the `main` function) and get the final task state
  356. state: State | None = asyncio.run(
  357. run_controller(
  358. config=config,
  359. task_str=instruction,
  360. fake_user_response_fn=AGENT_CLS_TO_FAKE_USER_RESPONSE_FN[
  361. metadata.agent_class
  362. ],
  363. runtime=runtime,
  364. )
  365. )
  366. # ======= Attempt to evaluate the agent's edits =======
  367. test_result = complete_runtime(runtime, instance)
  368. # If you are working on some simpler benchmark that only evaluates the final model output (e.g., in a MessageAction)
  369. # You can simply get the LAST `MessageAction` from the returned `state.history` and parse it for evaluation.
  370. if state is None:
  371. raise ValueError('State should not be None.')
  372. metrics = state.metrics.get() if state.metrics else None
  373. # history is now available as a stream of events, rather than list of pairs of (Action, Observation)
  374. # for compatibility with the existing output format, we can remake the pairs here
  375. # remove when it becomes unnecessary
  376. histories = state.history.compatibility_for_eval_history_pairs()
  377. # Save the output
  378. output = EvalOutput(
  379. instance_id=instance.instance_id,
  380. instruction=instruction,
  381. metadata=metadata,
  382. history=histories,
  383. metrics=metrics,
  384. error=state.last_error if state and state.last_error else None,
  385. test_result=test_result,
  386. )
  387. return output
  388. if __name__ == '__main__':
  389. args = parse_arguments()
  390. bird_dataset = load_bird()
  391. dataset = bird_dataset['test'].to_pandas()
  392. dataset.rename(columns={'task_id': 'instance_id'}, inplace=True)
  393. llm_config = None
  394. if args.llm_config:
  395. llm_config = get_llm_config_arg(args.llm_config)
  396. if llm_config is None:
  397. raise ValueError(f'Could not find LLM config: --llm_config {args.llm_config}')
  398. metadata = make_metadata(
  399. llm_config,
  400. 'BIRD',
  401. args.agent_cls,
  402. args.max_iterations,
  403. args.eval_note,
  404. args.eval_output_dir,
  405. )
  406. output_file = os.path.join(metadata.eval_output_dir, 'output.jsonl')
  407. instances = prepare_dataset(dataset, output_file, args.eval_n_limit)
  408. run_evaluation(
  409. instances, metadata, output_file, args.eval_num_workers, process_instance
  410. )