π OpenHands: AI-Driven Development
Support BIRD benchmark (#2117)
Binyuan Hui46dcf4bb3efd
diff --git a/evaluation/bird/README.md b/evaluation/bird/README.mdnew file mode 100644index 0000000000..753dcc071f--- /dev/null+++ b/evaluation/bird/README.md@@ -0,0 +1,195 @@+# BIRD Evaluation with OpenDevin++Implements evaluation of agents on BIRD introduced in [Can LLM Already Serve as A Database Interface? A BIg Bench for Large-Scale Database Grounded Text-to-SQLs](https://arxiv.org/abs/2305.03111). Please see [here](https://bird-bench.github.io/) for the reference implementation used in the paper.++## Setup Environment++Please follow [this document](https://github.com/OpenDevin/OpenDevin/blob/main/Development.md) to setup local develop environment for OpenDevin.+++## Configure OpenDevin and your LLM++Create a `config.toml` file if it does not exist at the root of the workspace.++Add the following configurations:++```toml+[core]+max_iterations = 100+cache_dir = "/tmp/cache"+ssh_hostname = "localhost"+enable_auto_lint = true++# TODO: Change these to the model you want to evaluate+[eval_gpt4_1106_preview]+model = "gpt-4-1106-preview"+api_key = "XXX"+temperature = 0.0++[eval_some_openai_compatible_model]+model = "openai/MODEL_NAME"+base_url = "https://OPENAI_COMPATIBLE_URL/v1"+api_key = "XXX"+temperature = 0.0+```++## Run Inference on Bird++```bash+./evaluation/bird/scripts/run_infer.sh eval_gpt4_1106_preview+```++You can replace `eval_gpt4_1106_preview` with any model you set up in `config.toml`.+++## Examples++For each problem, OpenDevin is given a set number of iterations to fix the failing code. The history field shows each iteration's response to correct its code that fails any test case.+++```+{+ "task_id": "0",+ "instruction": "You are a SQL expert and need to complete the following text-to-SQL tasks.\n\nCREATE TABLE frpm\n(\n CDSCode TEXT not null\n primary key,\n `Academic Year` TEXT null,\n `County Code` TEXT null,\n `District Code` INTEGER null,\n `School Code` TEXT null,\n `County Name` TEXT null,\n `District Name` TEXT null,\n `School Name` TEXT null,\n `District Type` TEXT null,\n `School Type` TEXT null,\n `Educational Option Type` TEXT null,\n `NSLP Provision Status` TEXT null,\n `Charter School (Y/N)` INTEGER null,\n `Charter School Number` TEXT null,\n `Charter Funding Type` TEXT null,\n IRC INTEGER null,\n `Low Grade` TEXT null,\n `High Grade` TEXT null,\n `Enrollment (K-12)` REAL null,\n `Free Meal Count (K-12)` REAL null,\n `Percent (%) Eligible Free (K-12)` REAL null,\n `FRPM Count (K-12)` REAL null,\n `Percent (%) Eligible FRPM (K-12)` REAL null,\n `Enrollment (Ages 5-17)` REAL null,\n `Free Meal Count (Ages 5-17)` REAL null,\n `Percent (%) Eligible Free (Ages 5-17)` REAL null,\n `FRPM Count (Ages 5-17)` REAL null,\n `Percent (%) Eligible FRPM (Ages 5-17)` REAL null,\n `2013-14 CALPADS Fall 1 Certification Status` INTEGER null,\n foreign key (CDSCode) references schools (CDSCode)\n);\n\nCREATE TABLE satscores\n(\n cds TEXT not null\n primary key,\n rtype TEXT not null,\n sname TEXT null,\n dname TEXT null,\n cname TEXT null,\n enroll12 INTEGER not null,\n NumTstTakr INTEGER not null,\n AvgScrRead INTEGER null,\n AvgScrMath INTEGER null,\n AvgScrWrite INTEGER null,\n NumGE1500 INTEGER null,\n-- PctGE1500 double null,\n foreign key (cds) references schools (CDSCode)\n);\n\nCREATE TABLE schools\n(\n CDSCode TEXT not null\n primary key,\n NCESDist TEXT null,\n NCESSchool TEXT null,\n StatusType TEXT not null,\n County TEXT not null,\n District TEXT not null,\n School TEXT null,\n Street TEXT null,\n StreetAbr TEXT null,\n City TEXT null,\n Zip TEXT null,\n State TEXT null,\n MailStreet TEXT null,\n MailStrAbr TEXT null,\n MailCity TEXT null,\n MailZip TEXT null,\n MailState TEXT null,\n Phone TEXT null,\n Ext TEXT null,\n Website TEXT null,\n OpenDate DATE null,\n ClosedDate DATE null,\n Charter INTEGER null,\n CharterNum TEXT null,\n FundingType TEXT null,\n DOC TEXT not null,\n DOCType TEXT not null,\n SOC TEXT null,\n SOCType TEXT null,\n EdOpsCode TEXT null,\n EdOpsName TEXT null,\n EILCode TEXT null,\n EILName TEXT null,\n GSoffered TEXT null,\n GSserved TEXT null,\n Virtual TEXT null,\n Magnet INTEGER null,\n Latitude REAL null,\n Longitude REAL null,\n AdmFName1 TEXT null,\n AdmLName1 TEXT null,\n AdmEmail1 TEXT null,\n AdmFName2 TEXT null,\n AdmLName2 TEXT null,\n AdmEmail2 TEXT null,\n AdmFName3 TEXT null,\n AdmLName3 TEXT null,\n AdmEmail3 TEXT null,\n LastUpdate DATE not null\n);\n\n-- External Knowledge: Eligible free rate for K-12 = `Free Meal Count (K-12)` / `Enrollment (K-12)`\n\n-- Using valid SQLite and understanding External Knowledge, answer the following questions for the tables provided above.\n\n-- Using valid SQLite, answer the following questions for the tables provided above.\nQuestion: What is the highest eligible free rate for K-12 students in the schools in Alameda County?\n\n\nPlease write the SQL in one line without line breaks.And write a new python file named 0.py to call the SQL you wrote.You need to follow the code template below:\n\n\n import sqlite3\n def execute_sql(db_path, sql):\n with sqlite3.connect(db_path) as conn:\n cursor = conn.cursor()\n cursor.execute(sql)\n result = cursor.fetchall()\n return result\n\n if __name__ == '__main__':\n sql = \"\" # filling your SQL here\n db_path = \"california_schools/california_schools.sqlite\"\n print(db_path)\n result = execute_sql(db_path, sql)\n print(result)\n \n\nEnvironment has been set up for you to start working.You may assume all necessary tools are installed.\n\nIMPORTANT: You should ONLY interact with the environment provided to you AND NEVER ASK FOR HUMAN HELP.\nYou SHOULD INCLUDE PROPER INDENTATION in your edit commands.\nWhen you think you have fixed the issue through code changes, please run the following command: <execute_bash> exit </execute_bash>.\n",+ "metadata": {+ "agent_class": "CodeActAgent",+ "model_name": "gpt-4-1106-preview",+ "max_iterations": 5,+ "eval_output_dir": "evaluation/evaluation_outputs/outputs/bird/CodeActAgent/gpt-4-1106-preview_maxiter_5_N_v1.5",+ "start_time": "2024-05-29 02:00:22",+ "git_commit": "ae105c2fafc64ad3eeb7a8bea09119fcb5865bc4"+ },+ "history": [+ [+ {+ "id": 0,+ "timestamp": "2024-05-29T02:00:46.498136",+ "source": "user",+ "message": "You are a SQL expert and need to complete the following text-to-SQL tasks.\n\nCREATE TABLE frpm\n(\n CDSCode TEXT not null\n primary key,\n `Academic Year` TEXT null,\n `County Code` TEXT null,\n `District Code` INTEGER null,\n `School Code` TEXT null,\n `County Name` TEXT null,\n `District Name` TEXT null,\n `School Name` TEXT null,\n `District Type` TEXT null,\n `School Type` TEXT null,\n `Educational Option Type` TEXT null,\n `NSLP Provision Status` TEXT null,\n `Charter School (Y/N)` INTEGER null,\n `Charter School Number` TEXT null,\n `Charter Funding Type` TEXT null,\n IRC INTEGER null,\n `Low Grade` TEXT null,\n `High Grade` TEXT null,\n `Enrollment (K-12)` REAL null,\n `Free Meal Count (K-12)` REAL null,\n `Percent (%) Eligible Free (K-12)` REAL null,\n `FRPM Count (K-12)` REAL null,\n `Percent (%) Eligible FRPM (K-12)` REAL null,\n `Enrollment (Ages 5-17)` REAL null,\n `Free Meal Count (Ages 5-17)` REAL null,\n `Percent (%) Eligible Free (Ages 5-17)` REAL null,\n `FRPM Count (Ages 5-17)` REAL null,\n `Percent (%) Eligible FRPM (Ages 5-17)` REAL null,\n `2013-14 CALPADS Fall 1 Certification Status` INTEGER null,\n foreign key (CDSCode) references schools (CDSCode)\n);\n\nCREATE TABLE satscores\n(\n cds TEXT not null\n primary key,\n rtype TEXT not null,\n sname TEXT null,\n dname TEXT null,\n cname TEXT null,\n enroll12 INTEGER not null,\n NumTstTakr INTEGER not null,\n AvgScrRead INTEGER null,\n AvgScrMath INTEGER null,\n AvgScrWrite INTEGER null,\n NumGE1500 INTEGER null,\n-- PctGE1500 double null,\n foreign key (cds) references schools (CDSCode)\n);\n\nCREATE TABLE schools\n(\n CDSCode TEXT not null\n primary key,\n NCESDist TEXT null,\n NCESSchool TEXT null,\n StatusType TEXT not null,\n County TEXT not null,\n District TEXT not null,\n School TEXT null,\n Street TEXT null,\n StreetAbr TEXT null,\n City TEXT null,\n Zip TEXT null,\n State TEXT null,\n MailStreet TEXT null,\n MailStrAbr TEXT null,\n MailCity TEXT null,\n MailZip TEXT null,\n MailState TEXT null,\n Phone TEXT null,\n Ext TEXT null,\n Website TEXT null,\n OpenDate DATE null,\n ClosedDate DATE null,\n Charter INTEGER null,\n CharterNum TEXT null,\n FundingType TEXT null,\n DOC TEXT not null,\n DOCType TEXT not null,\n SOC TEXT null,\n SOCType TEXT null,\n EdOpsCode TEXT null,\n EdOpsName TEXT null,\n EILCode TEXT null,\n EILName TEXT null,\n GSoffered TEXT null,\n GSserved TEXT null,\n Virtual TEXT null,\n Magnet INTEGER null,\n Latitude REAL null,\n Longitude REAL null,\n AdmFName1 TEXT null,\n AdmLName1 TEXT null,\n AdmEmail1 TEXT null,\n AdmFName2 TEXT null,\n AdmLName2 TEXT null,\n AdmEmail2 TEXT null,\n AdmFName3 TEXT null,\n AdmLName3 TEXT null,\n AdmEmail3 TEXT null,\n LastUpdate DATE not null\n);\n\n-- External Knowledge: Eligible free rate for K-12 = `Free Meal Count (K-12)` / `Enrollment (K-12)`\n\n-- Using valid SQLite and understanding External Knowledge, answer the following questions for the tables provided above.\n\n-- Using valid SQLite, answer the following questions for the tables provided above.\nQuestion: What is the highest eligible free rate for K-12 students in the schools in Alameda County?\n\n\nPlease write the SQL in one line without line breaks.And write a new python file named 0.py to call the SQL you wrote.You need to follow the code template below:\n\n\n import sqlite3\n def execute_sql(db_path, sql):\n with sqlite3.connect(db_path) as conn:\n cursor = conn.cursor()\n cursor.execute(sql)\n result = cursor.fetchall()\n return result\n\n if __name__ == '__main__':\n sql = \"\" # filling your SQL here\n db_path = \"california_schools/california_schools.sqlite\"\n print(db_path)\n result = execute_sql(db_path, sql)\n print(result)\n \n\nEnvironment has been set up for you to start working.You may assume all necessary tools are installed.\n\nIMPORTANT: You should ONLY interact with the environment provided to you AND NEVER ASK FOR HUMAN HELP.\nYou SHOULD INCLUDE PROPER INDENTATION in your edit commands.\nWhen you think you have fixed the issue through code changes, please run the following command: <execute_bash> exit </execute_bash>.\n",+ "action": "message",+ "args": {+ "content": "You are a SQL expert and need to complete the following text-to-SQL tasks.\n\nCREATE TABLE frpm\n(\n CDSCode TEXT not null\n primary key,\n `Academic Year` TEXT null,\n `County Code` TEXT null,\n `District Code` INTEGER null,\n `School Code` TEXT null,\n `County Name` TEXT null,\n `District Name` TEXT null,\n `School Name` TEXT null,\n `District Type` TEXT null,\n `School Type` TEXT null,\n `Educational Option Type` TEXT null,\n `NSLP Provision Status` TEXT null,\n `Charter School (Y/N)` INTEGER null,\n `Charter School Number` TEXT null,\n `Charter Funding Type` TEXT null,\n IRC INTEGER null,\n `Low Grade` TEXT null,\n `High Grade` TEXT null,\n `Enrollment (K-12)` REAL null,\n `Free Meal Count (K-12)` REAL null,\n `Percent (%) Eligible Free (K-12)` REAL null,\n `FRPM Count (K-12)` REAL null,\n `Percent (%) Eligible FRPM (K-12)` REAL null,\n `Enrollment (Ages 5-17)` REAL null,\n `Free Meal Count (Ages 5-17)` REAL null,\n `Percent (%) Eligible Free (Ages 5-17)` REAL null,\n `FRPM Count (Ages 5-17)` REAL null,\n `Percent (%) Eligible FRPM (Ages 5-17)` REAL null,\n `2013-14 CALPADS Fall 1 Certification Status` INTEGER null,\n foreign key (CDSCode) references schools (CDSCode)\n);\n\nCREATE TABLE satscores\n(\n cds TEXT not null\n primary key,\n rtype TEXT not null,\n sname TEXT null,\n dname TEXT null,\n cname TEXT null,\n enroll12 INTEGER not null,\n NumTstTakr INTEGER not null,\n AvgScrRead INTEGER null,\n AvgScrMath INTEGER null,\n AvgScrWrite INTEGER null,\n NumGE1500 INTEGER null,\n-- PctGE1500 double null,\n foreign key (cds) references schools (CDSCode)\n);\n\nCREATE TABLE schools\n(\n CDSCode TEXT not null\n primary key,\n NCESDist TEXT null,\n NCESSchool TEXT null,\n StatusType TEXT not null,\n County TEXT not null,\n District TEXT not null,\n School TEXT null,\n Street TEXT null,\n StreetAbr TEXT null,\n City TEXT null,\n Zip TEXT null,\n State TEXT null,\n MailStreet TEXT null,\n MailStrAbr TEXT null,\n MailCity TEXT null,\n MailZip TEXT null,\n MailState TEXT null,\n Phone TEXT null,\n Ext TEXT null,\n Website TEXT null,\n OpenDate DATE null,\n ClosedDate DATE null,\n Charter INTEGER null,\n CharterNum TEXT null,\n FundingType TEXT null,\n DOC TEXT not null,\n DOCType TEXT not null,\n SOC TEXT null,\n SOCType TEXT null,\n EdOpsCode TEXT null,\n EdOpsName TEXT null,\n EILCode TEXT null,\n EILName TEXT null,\n GSoffered TEXT null,\n GSserved TEXT null,\n Virtual TEXT null,\n Magnet INTEGER null,\n Latitude REAL null,\n Longitude REAL null,\n AdmFName1 TEXT null,\n AdmLName1 TEXT null,\n AdmEmail1 TEXT null,\n AdmFName2 TEXT null,\n AdmLName2 TEXT null,\n AdmEmail2 TEXT null,\n AdmFName3 TEXT null,\n AdmLName3 TEXT null,\n AdmEmail3 TEXT null,\n LastUpdate DATE not null\n);\n\n-- External Knowledge: Eligible free rate for K-12 = `Free Meal Count (K-12)` / `Enrollment (K-12)`\n\n-- Using valid SQLite and understanding External Knowledge, answer the following questions for the tables provided above.\n\n-- Using valid SQLite, answer the following questions for the tables provided above.\nQuestion: What is the highest eligible free rate for K-12 students in the schools in Alameda County?\n\n\nPlease write the SQL in one line without line breaks.And write a new python file named 0.py to call the SQL you wrote.You need to follow the code template below:\n\n\n import sqlite3\n def execute_sql(db_path, sql):\n with sqlite3.connect(db_path) as conn:\n cursor = conn.cursor()\n cursor.execute(sql)\n result = cursor.fetchall()\n return result\n\n if __name__ == '__main__':\n sql = \"\" # filling your SQL here\n db_path = \"california_schools/california_schools.sqlite\"\n print(db_path)\n result = execute_sql(db_path, sql)\n print(result)\n \n\nEnvironment has been set up for you to start working.You may assume all necessary tools are installed.\n\nIMPORTANT: You should ONLY interact with the environment provided to you AND NEVER ASK FOR HUMAN HELP.\nYou SHOULD INCLUDE PROPER INDENTATION in your edit commands.\nWhen you think you have fixed the issue through code changes, please run the following command: <execute_bash> exit </execute_bash>.\n",+ "wait_for_response": false+ }+ },+ {+ "message": "No observation",+ "observation": "null",+ "content": "",+ "extras": {}+ }+ ],+ [+ {+ "id": 5,+ "timestamp": "2024-05-29T02:00:49.776373",+ "source": "agent",+ "message": "Running Python code interactively: create_file('0.py')",+ "action": "run_ipython",+ "args": {+ "code": "create_file('0.py')",+ "thought": "Let's start by creating the Python file `0.py` with the provided template. Then, I will fill in the SQL query to find the highest eligible free rate for K-12 students in the schools in Alameda County.",+ "kernel_init_code": "from agentskills import *"+ }+ },+ {+ "id": 6,+ "timestamp": "2024-05-29T02:00:50.218391",+ "source": "agent",+ "message": "Code executed in IPython cell.",+ "cause": 5,+ "observation": "run_ipython",+ "content": "[File: /workspace/0.py (1 lines total)]\r\n1|\r\n[File 0.py created.]\r\n",+ "extras": {+ "code": "create_file('0.py')"+ }+ }+ ],+ [+ {+ "id": 7,+ "timestamp": "2024-05-29T02:01:02.238250",+ "source": "agent",+ "message": "Running Python code interactively: EDITED_CODE = \"\"\"import sqlite3\n\ndef execute_sql(db_path, sql):\n with sqlite3.connect(db_path) as conn:\n cursor = conn.cursor()\n cursor.execute(sql)\n result = cursor.fetchall()\n return result\n\nif __name__ == '__main__':\n sql = \"SELECT MAX(\\`Free Meal Count (K-12)\\` / \\`Enrollment (K-12)\\`) AS highest_eligible_free_rate FROM frpm JOIN schools ON frpm.CDSCode = schools.CDSCode WHERE \\`County Name\\` = 'Alameda'\"\n db_path = \"california_schools/california_schools.sqlite\"\n print(db_path)\n result = execute_sql(db_path, sql)\n print(result)\n\"\"\"\nedit_file(start=1, end=1, content=EDITED_CODE)",+ "action": "run_ipython",+ "args": {+ "code": "EDITED_CODE = \"\"\"import sqlite3\n\ndef execute_sql(db_path, sql):\n with sqlite3.connect(db_path) as conn:\n cursor = conn.cursor()\n cursor.execute(sql)\n result = cursor.fetchall()\n return result\n\nif __name__ == '__main__':\n sql = \"SELECT MAX(\\`Free Meal Count (K-12)\\` / \\`Enrollment (K-12)\\`) AS highest_eligible_free_rate FROM frpm JOIN schools ON frpm.CDSCode = schools.CDSCode WHERE \\`County Name\\` = 'Alameda'\"\n db_path = \"california_schools/california_schools.sqlite\"\n print(db_path)\n result = execute_sql(db_path, sql)\n print(result)\n\"\"\"\nedit_file(start=1, end=1, content=EDITED_CODE)",+ "thought": "Now I will write the Python code with the SQL query to find the highest eligible free rate for K-12 students in Alameda County and save it to the file `0.py`.",+ "kernel_init_code": "from agentskills import *"+ }+ },+ {+ "id": 8,+ "timestamp": "2024-05-29T02:01:02.775798",+ "source": "agent",+ "message": "Code executed in IPython cell.",+ "cause": 7,+ "observation": "run_ipython",+ "content": "[File: /workspace/0.py (16 lines total after edit)]\r\n1|import sqlite3\r\n2|\r\n3|def execute_sql(db_path, sql):\r\n4| with sqlite3.connect(db_path) as conn:\r\n5| cursor = conn.cursor()\r\n6| cursor.execute(sql)\r\n7| result = cursor.fetchall()\r\n8| return result\r\n9|\r\n10|if __name__ == '__main__':\r\n11| sql = \"SELECT MAX(`Free Meal Count (K-12)` / `Enrollment (K-12)`) AS highest_eligible_free_rate FROM frpm JOIN schools ON frpm.CDSCode = schools.CDSCode WHERE `County Name` = 'Alameda'\"\r\n12| db_path = \"california_schools/california_schools.sqlite\"\r\n13| print(db_path)\r\n14| result = execute_sql(db_path, sql)\r\n15| print(result)\r\n16|\r\n[File updated. Please review the changes and make sure they are correct (correct indentation, no duplicate lines, etc). Edit the file again if necessary.]\r\n",+ "extras": {+ "code": "EDITED_CODE = \"\"\"import sqlite3\n\ndef execute_sql(db_path, sql):\n with sqlite3.connect(db_path) as conn:\n cursor = conn.cursor()\n cursor.execute(sql)\n result = cursor.fetchall()\n return result\n\nif __name__ == '__main__':\n sql = \"SELECT MAX(\\`Free Meal Count (K-12)\\` / \\`Enrollment (K-12)\\`) AS highest_eligible_free_rate FROM frpm JOIN schools ON frpm.CDSCode = schools.CDSCode WHERE \\`County Name\\` = 'Alameda'\"\n db_path = \"california_schools/california_schools.sqlite\"\n print(db_path)\n result = execute_sql(db_path, sql)\n print(result)\n\"\"\"\nedit_file(start=1, end=1, content=EDITED_CODE)"+ }+ }+ ],+ [+ {+ "id": 9,+ "timestamp": "2024-05-29T02:01:13.053834",+ "source": "agent",+ "message": "Running command: python3 0.py",+ "action": "run",+ "args": {+ "command": "python3 0.py",+ "background": false,+ "thought": "The Python code with the SQL query has been written to the file `0.py`. Now, let's run the Python script to execute the SQL query and get the result."+ }+ },+ {+ "id": 10,+ "timestamp": "2024-05-29T02:01:13.222204",+ "source": "agent",+ "message": "Command `python3 0.py` executed with exit code 0.",+ "cause": 9,+ "observation": "run",+ "content": "california_schools/california_schools.sqlite\r\n[(1.0,)]",+ "extras": {+ "command_id": -1,+ "command": "python3 0.py",+ "exit_code": 0+ }+ }+ ],+ [+ {+ "id": 11,+ "timestamp": "2024-05-29T02:01:18.663380",+ "source": "agent",+ "message": "All done! What's next on the agenda?",+ "action": "finish",+ "args": {+ "outputs": {},+ "thought": ""+ }+ },+ {+ "message": "No observation",+ "observation": "null",+ "content": "",+ "extras": {}+ }+ ]+ ],+ "error": null,+ "test_result": {+ "result": {+ "passed": 1,+ "status": "success"+ },+ "metadata": {+ "timeout": 10,+ "gen_sql": "SELECT MAX(`Free Meal Count (K-12)` / `Enrollment (K-12)`) AS highest_eligible_free_rate FROM frpm JOIN schools ON frpm.CDSCode = schools.CDSCode WHERE `County Name` = 'Alameda'",+ "gold_sql": "SELECT `Free Meal Count (K-12)` / `Enrollment (K-12)` FROM frpm WHERE `County Name` = 'Alameda' ORDER BY (CAST(`Free Meal Count (K-12)` AS REAL) / `Enrollment (K-12)`) DESC LIMIT 1"+ }+ }+}+```diff --git a/evaluation/bird/__init__.py b/evaluation/bird/__init__.pynew file mode 100644index 0000000000..e69de29bb2diff --git a/evaluation/bird/run_infer.py b/evaluation/bird/run_infer.pynew file mode 100644index 0000000000..44cbd18226--- /dev/null+++ b/evaluation/bird/run_infer.py@@ -0,0 +1,515 @@+import asyncio+import json+import logging+import multiprocessing as mp+import os+import pathlib+import re+import shutil+import sqlite3+import subprocess+import time+from concurrent.futures import ProcessPoolExecutor++import pandas as pd+from datasets import load_dataset+from func_timeout import FunctionTimedOut, func_timeout+from tqdm import tqdm++from opendevin.controller.state.state import State+from opendevin.core.config import args, config, get_llm_config_arg+from opendevin.core.logger import get_console_handler+from opendevin.core.logger import opendevin_logger as logger+from opendevin.core.main import main+from opendevin.events.action import MessageAction+from opendevin.events.serialization.event import event_to_dict+++def cleanup():+ logger.info('Cleaning up child processes...')+ for process in mp.active_children():+ logger.info(f'Terminating child process: {process.name}')+ process.terminate()+ process.join()+++def codeact_user_response(state: State) -> str:+ msg = (+ 'Please continue working on the task on whatever approach you think is suitable.\n'+ 'If you think you have completed the SQL, please run the following command: <execute_bash> exit </execute_bash>.\n'+ 'IMPORTANT: YOU SHOULD NEVER ASK FOR HUMAN HELP OR USE THE INTERNET TO SOLVE THIS TASK.\n'+ )+ if state.history:+ user_msgs = [+ action+ for action, _ in state.history+ if isinstance(action, MessageAction) and action.source == 'user'+ ]+ if len(user_msgs) >= 2:+ # let the agent know that it can give up when it has tried 3 times+ return (+ msg+ + 'If you want to give up, run: <execute_bash> exit </execute_bash>.\n'+ )+ return msg+++def monologue_user_response(state: State) -> str:+ raise NotImplementedError('MonologueAgent should never ask for user responses.')+++AGENT_CLS_TO_FAKE_USER_RESPONSE_FN = {+ 'CodeActAgent': codeact_user_response,+ 'MonologueAgent': monologue_user_response,+}++AGENT_CLS_TO_INST_SUFFIX = {+ 'CodeActAgent': 'When you think you have fixed the issue through code changes, please run the following command: <execute_bash> exit </execute_bash>.\n'+}+++def execute_sql(db_path, gen_sql, gold_sql):+ """+ Execute the generated SQL and the ground truth SQL and compare the results.+ """+ with sqlite3.connect(db_path) as conn:+ cursor = conn.cursor()+ cursor.execute(gen_sql)+ predicted_res = cursor.fetchall()+ cursor.execute(gold_sql)+ ground_truth_res = cursor.fetchall()+ res = 0+ if set(predicted_res) == set(ground_truth_res):+ res = 1+ return res+++def get_test_result(instance, path, timeout=30):+ test_result = {'result': {}, 'metadata': {}}++ # Read the generated python file+ with open(path, 'r') as f:+ gen_file = f.read()++ # Extract the SQL from the python file+ gen_sql = ''+ pattern = r'sql\s*=\s*"([^"]+)"'+ match = re.search(pattern, gen_file)+ if match:+ gen_sql = match.group(1)+ else:+ print('No match found.')++ gold_sql = instance.SQL+ # Execute the SQL+ try:+ res = func_timeout(+ timeout, execute_sql, args=(instance.db_path, gen_sql, gold_sql)+ )+ status = 'success'+ except FunctionTimedOut:+ res = 0+ status = 'timeout'+ except Exception as e:+ res = 0+ status = 'error'+ logger.error(f'Error: {e}')++ # Save the test result+ test_result['result'] = {'passed': res, 'status': status}+ test_result['metadata'] = {+ 'timeout': timeout,+ 'gen_sql': gen_sql,+ 'gold_sql': gold_sql,+ }+ return test_result+++def process_instance(+ instance, agent_class, metadata, skip_workspace_mount, reset_logger: bool = True+):+ workspace_mount_path = os.path.join(+ config.workspace_mount_path, 'bird_eval_workspace'+ )+ # create process-specific workspace dir+ # if `not skip_workspace_mount` - we will create a workspace directory for EACH process+ # so that different agent don't interfere with each other.+ if not skip_workspace_mount:+ workspace_mount_path = os.path.join(workspace_mount_path, str(os.getpid()))+ pathlib.Path(workspace_mount_path).mkdir(parents=True, exist_ok=True)++ # reset workspace to config+ config.workspace_mount_path = workspace_mount_path++ # Copy the database to the workspace+ db_root = os.path.join(+ config.workspace_base, 'evaluation_bird/dev/dev_databases', instance.db_id+ )+ target_path = os.path.join(workspace_mount_path, f'{instance.db_id}')+ if not os.path.exists(target_path):+ logger.info(f'Copying database from {db_root} to {target_path}...')+ shutil.copytree(db_root, target_path)++ # Set up the database path+ database_path = os.path.join(instance.db_id, f'{instance.db_id}.sqlite')++ # Set up the logger properly, so you can run multi-processing to parallelize the evaluation+ if reset_logger:+ # Set up logger+ log_file = os.path.join(+ eval_output_dir,+ 'logs',+ f'instance_{instance.task_id.replace("/", "__")}.log',+ )+ # Remove all existing handlers from logger+ for handler in logger.handlers[:]:+ logger.removeHandler(handler)+ # add back the console handler to print ONE line+ logger.addHandler(get_console_handler())+ logger.info(+ f'Starting evaluation for instance {instance.task_id}.\nLOG: tail -f {log_file}'+ )+ # Remove all existing handlers from logger+ for handler in logger.handlers[:]:+ logger.removeHandler(handler)+ file_handler = logging.FileHandler(log_file)+ file_handler.setFormatter(+ logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')+ )+ logger.addHandler(file_handler)++ if not skip_workspace_mount:+ logger.info(f'Process-specific workspace mounted at {workspace_mount_path}')++ # Create file with BIRD instance+ statements = f"""+ import sqlite3+ def execute_sql(db_path, sql):+ with sqlite3.connect(db_path) as conn:+ cursor = conn.cursor()+ cursor.execute(sql)+ result = cursor.fetchall()+ return result++ if __name__ == '__main__':+ sql = "" # fill in your SQL here+ db_path = "{database_path}"+ print(db_path)+ result = execute_sql(db_path, sql)+ print(result)+ """+ path = os.path.join(+ config.workspace_mount_path, f'{instance.task_id.replace("/", "__")}.py'+ )+ instruction = (+ f'You are a SQL expert and need to complete the following text-to-SQL tasks.'+ f'\n\n{instance.instruction}\n\n'+ 'Please write the SQL in one line without line breaks.'+ f'And write a new python file named {instance.task_id.replace("/", "__")}.py to call the SQL you wrote.'+ 'You need to follow the code template below:'+ f'\n\n{statements}\n\n'+ 'Environment has been set up for you to start working.'+ 'You may assume all necessary tools are installed.\n\n'+ )+ instruction += (+ 'IMPORTANT: You should ONLY interact with the environment provided to you AND NEVER ASK FOR HUMAN HELP.\n'+ 'You SHOULD INCLUDE PROPER INDENTATION in your edit commands.\n'+ )+ # NOTE: You can actually set slightly different instruction for different agents+ instruction += AGENT_CLS_TO_INST_SUFFIX.get(agent_class, '')+ # Here's how you can run the agent (similar to the `main` function) and get the final task state+ state: State = asyncio.run(+ main(+ instruction,+ fake_user_response_fn=AGENT_CLS_TO_FAKE_USER_RESPONSE_FN.get(agent_class),+ )+ )++ # ======= Attempt to evaluate the agent's edits =======+ test_result = get_test_result(instance, path)++ # If you are working on some simpler benchmark that only evaluates the final model output (e.g., in a MessageAction)+ # You can simply get the LAST `MessageAction` from the returned `state.history` and parse it for evaluation.+ if state is None:+ raise ValueError('State should not be None.')++ # Save the output+ output = {+ 'task_id': instance.task_id,+ 'instruction': instruction,+ 'metadata': metadata,+ 'history': [+ (event_to_dict(action), event_to_dict(obs)) for action, obs in state.history+ ],+ 'error': state.error if state and state.error else None,+ 'test_result': test_result,+ }+ return output+++def load_bird():+ """+ Main function to handle the flow of downloading, processing, and loading the bird dataset.+ """+ raw_dataset_path = download_bird()+ bird_dataset = process_bird(raw_dataset_path)+ return bird_dataset+++def download_bird():+ """+ Downloads and extracts the bird dataset from a specified URL into a local directory.+ """+ dataset_path = os.path.join(config.workspace_base, 'evaluation_bird')+ devset_path = os.path.join(dataset_path, 'dev')+ if not os.path.exists(dataset_path):+ logger.info(+ f'{dataset_path} folder does not exist, starting download and extraction...'+ )+ os.makedirs(dataset_path, exist_ok=True)+ download_url = 'https://bird-bench.oss-cn-beijing.aliyuncs.com/dev.zip'+ download_path = os.path.join(dataset_path, 'dev.zip')+ logger.info('Start Downloading...')+ subprocess.run(['wget', download_url, '-O', download_path])+ logger.info('Download completed.')+ logger.info('Start Extracting...')+ subprocess.run(['unzip', download_path, '-d', dataset_path])+ # extract databases+ devset_path = os.path.join(dataset_path, 'dev')+ database_path = os.path.join(devset_path, 'dev_databases.zip')+ subprocess.run(['unzip', database_path, '-d', devset_path])+ logger.info('Extraction completed.')+ else:+ logger.info(f'{dataset_path} folder already exists.')+ return devset_path+++def process_bird(dataset_path):+ """+ Processes the raw bird dataset into a structured format and saves it as JSON.+ """+ processed_path = os.path.join(dataset_path, 'processed_dev.json')+ if not os.path.exists(processed_path):+ logger.info(f'{processed_path} folder does not exist, starting processing...')+ raw_data_path = os.path.join(dataset_path, 'dev.json')+ database_path = os.path.join(dataset_path, 'dev_databases')+ processed_data = []+ with pathlib.Path(raw_data_path).open('r') as f:+ data = json.load(f)+ for e in tqdm(data):+ item = {+ 'task_id': f'{len(processed_data)}',+ 'db_path': os.path.join(+ database_path, e['db_id'], f"{e['db_id']}.sqlite"+ ),+ 'db_id': e['db_id'],+ 'instruction': create_prompt(e, database_path),+ 'SQL': e['SQL'],+ }+ processed_data.append(item)++ with pathlib.Path(processed_path).open('w') as f:+ json.dump(processed_data, f, indent=2)+ logger.info(f'Processed data saved to {processed_path}')+ else:+ logger.info(f'{processed_path} folder already exists.')+ bird_dataset = load_dataset('json', data_files={'test': processed_path})+ return bird_dataset+++def extract_create_table_prompt(db_path, limit_value=0):+ """+ Generates a SQL prompt with CREATE TABLE statements and sample data from the database.+ """+ table_query = "SELECT * FROM sqlite_master WHERE type='table';"+ tables = sqlite3.connect(db_path).cursor().execute(table_query).fetchall()+ prompt = ''+ for table in tables:+ table_name = table[1]+ create_table_statement = table[-1]++ table_info_query = f'PRAGMA table_info(`{table_name}`);'+ top_k_row_query = f'SELECT * FROM {table_name} LIMIT {limit_value};'+ try:+ headers = [+ x[1]+ for x in sqlite3.connect(db_path)+ .cursor()+ .execute(table_info_query)+ .fetchall()+ ]+ except Exception:+ logger.error(f'Error Connection: {table_info_query}, {top_k_row_query}')+ exit(0)++ prompt += create_table_statement + ';\n'+ if limit_value > 0:+ top_k_rows = (+ sqlite3.connect(db_path).cursor().execute(top_k_row_query).fetchall()+ )+ prompt += (+ f"/*\n3 example rows:\n{top_k_row_query}\n{' '.join(headers)}\n"+ )+ for row in top_k_rows:+ row = [str(x) for x in row]+ row = [x if x is not None else '' for x in row]+ prompt += ' '.join(row) + '\n'+ prompt += '*/\n'+ prompt += '\n'+ return prompt+++def create_prompt(e, database_path):+ """+ Create a prompt for the given example+ """+ db_id = e['db_id']+ db_path = pathlib.Path(database_path) / db_id / f'{db_id}.sqlite'++ # Extract the CREATE TABLE statements and sample data from the database+ prompt = extract_create_table_prompt(db_path)+ prompt += f"-- External Knowledge: {e['evidence']}\n\n"+ prompt += '-- Using valid SQLite and understanding External Knowledge, answer the following questions for the tables provided above.\n\n'+ prompt += '-- Using valid SQLite, answer the following questions for the tables provided above.\n'+ prompt += f"Question: {e['question']}\n"++ return prompt+++if __name__ == '__main__':+ # NOTE: It is preferable to load datasets from huggingface datasets and perform post-processing+ # so we don't need to manage file uploading to OpenDevin's repo+ # Due to the large size of the BIRD database, it cannot be hosted on huggingface datasets, so it needs to be downloaded+ bird_dataset = load_bird()+ bird_tests = bird_dataset['test'].to_pandas()++ # Check https://github.com/OpenDevin/OpenDevin/blob/main/evaluation/humanevalfix/README.md#configure-opendevin-and-your-llm+ # for details of how to set `llm_config`+ if args.llm_config:+ specified_llm_config = get_llm_config_arg(args.llm_config)+ if specified_llm_config:+ config.llm = specified_llm_config+ logger.info(f'Config for evaluation: {config}')++ # TEST METADATA+ agent_class = args.agent_cls+ assert (+ agent_class in AGENT_CLS_TO_FAKE_USER_RESPONSE_FN+ ), f'Unsupported agent class: {agent_class}'+ model_name = config.llm.model.split('/')[-1]+ max_iterations = args.max_iterations+ eval_note = ''+ if args.eval_note is not None:+ eval_note += '_N_' + args.eval_note+ eval_output_dir = os.path.join(+ args.eval_output_dir,+ 'bird',+ agent_class,+ model_name + '_maxiter_' + str(max_iterations) + eval_note,+ )++ pathlib.Path(eval_output_dir).mkdir(parents=True, exist_ok=True)+ pathlib.Path(os.path.join(eval_output_dir, 'logs')).mkdir(+ parents=True, exist_ok=True+ )+ logger.info(f'Using evaluation output directory: {eval_output_dir}')++ metadata = {+ 'agent_class': agent_class,+ 'model_name': model_name,+ 'max_iterations': max_iterations,+ 'eval_output_dir': eval_output_dir,+ 'start_time': time.strftime('%Y-%m-%d %H:%M:%S'),+ # get the commit id of current repo for reproduciblity+ 'git_commit': subprocess.check_output(['git', 'rev-parse', 'HEAD'])+ .decode('utf-8')+ .strip(),+ }+ logger.info(f'Metadata: {metadata}')+ with open(os.path.join(eval_output_dir, 'metadata.json'), 'w') as f:+ json.dump(metadata, f)++ # LIMIT EVALUATION+ eval_n_limit = args.eval_n_limit+ if eval_n_limit:+ bird_tests = bird_tests.head(eval_n_limit)+ logger.info(f'Limiting evaluation to first {eval_n_limit} instances.')++ # OUTPUT FILE+ output_file = os.path.join(eval_output_dir, 'output.jsonl')+ logger.info(f'Writing evaluation output to {output_file}')+ finished_instance_ids = set()+ if os.path.exists(output_file):+ with open(output_file, 'r') as f:+ for line in f:+ data = json.loads(line)+ finished_instance_ids.add(data['task_id'])+ logger.warning(+ f'Output file {output_file} already exists. Loaded {len(finished_instance_ids)} finished instances.'+ )+ output_fp = open(output_file, 'a')++ logger.info(+ f'Evaluation started with Agent {agent_class}, model {model_name}, max iterations {max_iterations}.'+ )++ # =============================================+ # filter out finished instances+ new_bird_tests = []+ for idx, instance in bird_tests.iterrows():+ if instance.task_id in finished_instance_ids:+ logger.info(+ f'Skipping instance {instance.task_id} as it is already finished.'+ )+ continue+ new_bird_tests.append(instance)++ bird_tests = pd.DataFrame(new_bird_tests)+ logger.info(+ f'Finished instances: {len(finished_instance_ids)}, Remaining instances: {len(bird_tests)}'+ )+ # =============================================++ pbar = tqdm(total=len(bird_tests))++ # This function tracks the progress AND write the output to a JSONL file+ def update_progress(future):+ pbar.update(1)+ output = future.result()+ pbar.set_description(f'Instance {output["task_id"]}')+ pbar.set_postfix_str(f'Test Result: {output["test_result"]["result"]}')+ logger.info(+ f'Finished evaluation for instance {output["task_id"]}: {output["test_result"]["result"]}'+ )+ output_fp.write(json.dumps(output) + '\n')+ output_fp.flush()++ # This sets the multi-processing+ num_workers = args.eval_num_workers+ logger.info(f'Using {num_workers} workers for evaluation.')++ try:+ with ProcessPoolExecutor(num_workers) as executor:+ futures = []+ # This is how we perform multi-processing+ for row_idx, instance in bird_tests.iterrows():+ future = executor.submit(+ process_instance,+ instance,+ agent_class,+ metadata,+ skip_workspace_mount=False,+ reset_logger=bool(num_workers > 1),+ )+ future.add_done_callback(update_progress)+ futures.append(future)++ # Wait for all futures to complete+ for future in futures:+ future.result()+ except KeyboardInterrupt:+ print('KeyboardInterrupt received. Cleaning up...')+ cleanup()++ output_fp.close()+ logger.info('Evaluation finished.')diff --git a/evaluation/bird/scripts/run_infer.sh b/evaluation/bird/scripts/run_infer.shnew file mode 100755index 0000000000..751cd64c59--- /dev/null+++ b/evaluation/bird/scripts/run_infer.sh@@ -0,0 +1,33 @@+#!/bin/bash+MODEL_CONFIG=$1+AGENT=$2+EVAL_LIMIT=$3++if [ -z "$AGENT" ]; then+ echo "Agent not specified, use default CodeActAgent"+ AGENT="CodeActAgent"+fi++# IMPORTANT: Because Agent's prompt changes fairly often in the rapidly evolving codebase of OpenDevin+# We need to track the version of Agent in the evaluation to make sure results are comparable+AGENT_VERSION=v$(poetry run python -c "import agenthub; from opendevin.controller.agent import Agent; print(Agent.get_cls('$AGENT').VERSION)")++echo "AGENT: $AGENT"+echo "AGENT_VERSION: $AGENT_VERSION"+echo "MODEL_CONFIG: $MODEL_CONFIG"++COMMAND="poetry run python evaluation/bird/run_infer.py \+ --agent-cls $AGENT \+ --llm-config $MODEL_CONFIG \+ --max-iterations 5 \+ --max-chars 10000000 \+ --eval-num-workers 1 \+ --eval-note $AGENT_VERSION" \++if [ -n "$EVAL_LIMIT" ]; then+ echo "EVAL_LIMIT: $EVAL_LIMIT"+ COMMAND="$COMMAND --eval-n-limit $EVAL_LIMIT"+fi++# Run the command+eval $COMMANDdiff --git a/opendevin/runtime/server/runtime.py b/opendevin/runtime/server/runtime.pyindex 44bd03cb14..d38e79451a 100644--- a/opendevin/runtime/server/runtime.py+++ b/opendevin/runtime/server/runtime.py@@ -48,6 +48,7 @@ class ServerRuntime(Runtime):)async def run_ipython(self, action: IPythonRunCellAction) -> Observation:+ action.code = action.code.replace('`', r'\`')obs = self._run_command(("cat > /tmp/opendevin_jupyter_temp.py <<'EOL'\n" f'{action.code}\n' 'EOL'),background=False,