run_infer.py 17 KB

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