π OpenHands: AI-Driven Development
[Feat] Aider Benchmark (#3507)
Raj Maheshwari80f88e14cd7c
diff --git a/evaluation/aider_bench/README.md b/evaluation/aider_bench/README.mdnew file mode 100644index 0000000000..6947133603--- /dev/null+++ b/evaluation/aider_bench/README.md@@ -0,0 +1,67 @@+# AiderBench Evaluation++This folder contains evaluation harness for evaluating agents on the+[Aider Editing Benchmark](https://github.com/paul-gauthier/aider/blob/main/benchmark/README.md).+This will allow us to develop better editing approach without running the full+SWE-bench. The benchmark uses the+[RajMaheshwari/Exercism-Python](https://huggingface.co/datasets/RajMaheshwari/Exercism-Python)+Hugging Face dataset based on the+[Exercism python coding exercises](https://github.com/exercism/python).++## Setup Environment and LLM Configuration++Please follow instruction [here](../README.md#setup) to setup your local+development environment and LLM.++## Start the evaluation++```bash+./evaluation/agent_bench/scripts/run_infer.sh [model_config] [git-version] [agent] [eval_limit]+```++- `model_config`, e.g. `eval_gpt4_1106_preview`, is the config group name for+ your LLM settings, as defined in your `config.toml`.+- `git-version`, e.g. `HEAD`, is the git commit hash of the OpenHands version+ you would like to evaluate. It could also be a release tag like `0.6.2`.+- `agent`, e.g. `CodeActAgent`, is the name of the agent for benchmarks,+ defaulting to `CodeActAgent`.+- `eval_limit`, e.g. `10`, limits the evaluation to the first `eval_limit`+ instances. By default, the script evaluates the entire Exercism test set+ (133 issues). Note: in order to use `eval_limit`, you must also set `agent`.++Following is the basic command to start the evaluation.++You can update the arguments in the script+`evaluation/agent_bench/scripts/run_infer.sh`, such as `--max-iterations`,+`--eval-num-workers` and so on.++- `--agent-cls`, the agent to use. For example, `CodeActAgent`.+- `--llm-config`: the LLM configuration to use. For example,+ `eval_gpt4_1106_preview`.+- `--max-iterations`: the number of iterations to run the evaluation. For+ example, `30`.+- `--eval-num-workers`: the number of workers to use for evaluation. For+ example, `5`.+- `--eval-n-limit`: the number of examples to evaluate. For example, `100`.++```bash+./evaluation/aider_bench/scripts/run_infer.sh eval_gpt35_turbo HEAD CodeActAgent 1+```++## Summarize Results++```bash+poetry run python ./evaluation/agent_bench/scripts/summarise_results.py [path_to_output_jsonl_file]+```++This will list the instances that passed and the instances that failed. For each+instance, the corresponding set of test cases (which can vary for each instance)+are run on the file edited by the agent. We consider an instance to be passed+only if ALL test cases are passed. Sometimes even a single failed test case will+cause the entire instance to be marked as filed.++You can inspect the test_results field in the output json file to know the exact+outcome of the tests. If there are no syntax or indentation errors, you can+expect to see something like "..F...EF..", where "." means the test case+passed, "E" means there was an error while executing the test case and "F"+means some assertion failed and returned output was not as expected.diff --git a/evaluation/aider_bench/create_dataset.py b/evaluation/aider_bench/create_dataset.pynew file mode 100644index 0000000000..ba76f92cbd--- /dev/null+++ b/evaluation/aider_bench/create_dataset.py@@ -0,0 +1,47 @@+# This file was used to create the hugging face dataset from the exercism/python+# github repo.+# Refer to: https://github.com/exercism/python/tree/main/exercises/practice++import os+from pathlib import Path++from datasets import Dataset++tests = sorted(os.listdir('practice/'))+dataset = {+ 'instance_id': [],+ 'instance_name': [],+ 'instruction': [],+ 'signature': [],+ 'test': [],+}++for i, test in enumerate(tests):+ testdir = Path(f'practice/{test}/')++ dataset['instance_id'].append(i)+ dataset['instance_name'].append(testdir.name.replace('-', '_'))++ # if len(glob.glob(f'practice/{testdir.name}/*.py')) != 2:+ # print(testdir.name)++ instructions = ''+ introduction = testdir / '.docs/introduction.md'+ if introduction.exists():+ instructions += introduction.read_text()+ instructions += (testdir / '.docs/instructions.md').read_text()+ instructions_append = testdir / '.docs/instructions.append.md'+ if instructions_append.exists():+ instructions += instructions_append.read_text()++ dataset['instruction'].append(instructions)++ signature_file = testdir / (testdir.name + '.py').replace('-', '_')+ dataset['signature'].append(signature_file.read_text())++ test_file = testdir / (testdir.name + '_test.py').replace('-', '_')+ dataset['test'].append(test_file.read_text())++ds = Dataset.from_dict(dataset)++ds.push_to_hub('RajMaheshwari/Exercism-Python')diff --git a/evaluation/aider_bench/helper.py b/evaluation/aider_bench/helper.pynew file mode 100644index 0000000000..2c65362f5c--- /dev/null+++ b/evaluation/aider_bench/helper.py@@ -0,0 +1,22 @@+from evaluation.utils.shared import codeact_user_response++INSTRUCTIONS_ADDENDUM = """+####++Use the above instructions to modify the supplied files: {signature_file}+Don't change the names of existing functions or classes, as they may be referenced from other code like unit tests, etc.++Only use standard python libraries, don't suggest installing any packages.+"""+++FAKE_RESPONSES = {+ 'CodeActAgent': codeact_user_response,+}++INST_SUFFIXES: dict[str, str] = {+ 'CodeActAgent': (+ 'REMEMBER: All edits must be made directly in the files. Do NOT send'+ ' the edited file as output to the user.\n'+ )+}diff --git a/evaluation/aider_bench/run_infer.py b/evaluation/aider_bench/run_infer.pynew file mode 100644index 0000000000..d9cefc38c5--- /dev/null+++ b/evaluation/aider_bench/run_infer.py@@ -0,0 +1,254 @@+import asyncio+import os+import tempfile+from typing import Any++import pandas as pd+from datasets import load_dataset++from evaluation.aider_bench.helper import (+ FAKE_RESPONSES,+ INST_SUFFIXES,+ INSTRUCTIONS_ADDENDUM,+)+from evaluation.utils.shared import (+ EvalMetadata,+ EvalOutput,+ make_metadata,+ prepare_dataset,+ reset_logger_for_multiprocessing,+ run_evaluation,+)+from openhands.controller.state.state import State+from openhands.core.config import (+ AppConfig,+ SandboxConfig,+ get_llm_config_arg,+ parse_arguments,+)+from openhands.core.logger import openhands_logger as logger+from openhands.core.main import create_runtime, run_controller+from openhands.events.action import CmdRunAction+from openhands.events.observation import CmdOutputObservation+from openhands.runtime.runtime import Runtime+++def get_config(+ metadata: EvalMetadata,+) -> AppConfig:+ config = AppConfig(+ default_agent=metadata.agent_class,+ run_as_openhands=False,+ runtime='eventstream',+ max_iterations=metadata.max_iterations,+ sandbox=SandboxConfig(+ container_image='python:3.11-bookworm',+ enable_auto_lint=True,+ use_host_network=False,+ timeout=100,+ ),+ # do not mount workspace+ workspace_base=None,+ workspace_mount_path=None,+ )+ config.set_llm_config(metadata.llm_config)+ return config+++async def initialize_runtime(+ runtime: Runtime,+ instance: pd.Series,+):+ """Initialize the runtime for the agent.++ This function is called before the runtime is used to run the agent.+ """+ logger.info(f"{'-' * 50} BEGIN Runtime Initialization Fn {'-' * 50}")+ obs: CmdOutputObservation++ # Set instance id+ action = CmdRunAction(command='mkdir -p /workspace')+ logger.info(action, extra={'msg_type': 'ACTION'})+ obs = await runtime.run_action(action)+ assert obs.exit_code == 0++ action = CmdRunAction(command='cd /workspace')+ logger.info(action, extra={'msg_type': 'ACTION'})+ obs = await runtime.run_action(action)+ assert obs.exit_code == 0++ with tempfile.TemporaryDirectory() as tmpdir:+ file_path = os.path.join(tmpdir, f'{instance.instance_name}.py')+ with open(file_path, 'w') as f:+ f.write(instance.signature)+ await runtime.copy_to(+ file_path,+ '/workspace',+ )+ logger.info(f"{'-' * 50} END Runtime Initialization Fn {'-' * 50}")+++async def complete_runtime(+ runtime: Runtime,+ instance: pd.Series,+) -> dict[str, Any]:+ """Complete the runtime for the agent.++ This function is called before the runtime is used to run the agent.+ If you need to do something in the sandbox to get the correctness metric after+ the agent has run, modify this function.+ """+ logger.info(f"{'-' * 50} BEGIN Runtime Completion Fn {'-' * 50}")+ obs: CmdOutputObservation++ script_name = f'{instance.instance_name}_test.py'+ with tempfile.TemporaryDirectory() as tmpdir:+ file_path = os.path.join(tmpdir, script_name)+ with open(file_path, 'w') as f:+ f.write(instance.test)+ await runtime.copy_to(+ file_path,+ '/workspace',+ )+ logger.info(f'Running test file: {script_name}')++ action = CmdRunAction(+ command=f'python -m unittest {script_name}',+ keep_prompt=False,+ )+ logger.info(action, extra={'msg_type': 'ACTION'})+ obs = await runtime.run_action(action)+ logger.info(obs, extra={'msg_type': 'OBSERVATION'})++ logger.info(f"{'-' * 50} END Runtime Completion Fn {'-' * 50}")++ return {+ 'test_output': obs.content,+ 'exit_code': obs.exit_code,+ }+++async def process_instance(+ instance: pd.Series,+ metadata: EvalMetadata,+ reset_logger: bool = True,+) -> EvalOutput:+ config = get_config(metadata)++ # Setup the logger properly, so you can run multi-processing to parallelize the evaluation+ if reset_logger:+ log_dir = os.path.join(metadata.eval_output_dir, 'infer_logs')+ reset_logger_for_multiprocessing(logger, str(instance.instance_id), log_dir)+ else:+ logger.info(f'Starting evaluation for instance {str(instance.instance_id)}.')++ # =============================================+ # build instruction+ # =============================================++ # Prepare instruction+ logger.info(instance)+ instruction = instance.instruction+ instruction += INSTRUCTIONS_ADDENDUM.format(+ signature_file=f'{instance.instance_name}.py',+ )+ instruction += (+ 'IMPORTANT: You should ONLY interact with the environment provided '+ 'to you AND NEVER ASK FOR HUMAN HELP.\n'+ )+ # NOTE: You can actually set slightly different instruction for different agents+ instruction += INST_SUFFIXES[metadata.agent_class]++ # =============================================+ # create sandbox and run the agent+ # =============================================++ runtime: Runtime = await create_runtime(config, sid=str(instance.instance_id))++ await initialize_runtime(runtime, instance=instance)++ # Here's how you can run the agent (similar to the `main` function) and get the final task state+ state: State | None = await run_controller(+ config=config,+ task_str=instruction,+ runtime=runtime,+ fake_user_response_fn=FAKE_RESPONSES[metadata.agent_class],+ )+ if state is None:+ raise ValueError('State should not be None.')++ # # =============================================+ # # result evaluation+ # # =============================================++ return_val = await complete_runtime(runtime, instance)+ exit_code = return_val['exit_code']+ test_output = return_val['test_output']++ errors = []+ test_cases = None+ if test_output.find('SyntaxError') != -1:+ errors += 'SyntaxError'+ elif test_output.find('IndentationError') != -1:+ errors += 'IndentationError'+ else:+ test_cases = test_output[: test_output.find('\r')]++ test_result = {+ 'exit_code': exit_code,+ 'test_cases': test_cases,+ 'errors': errors,+ }++ # history is now available as a stream of events, rather than list of pairs of (Action, Observation)+ # for compatibility with the existing output format, we can remake the pairs here+ # remove when it becomes unnecessary+ histories = state.history.compatibility_for_eval_history_pairs()+ metrics = state.metrics.get() if state.metrics else None++ # Save the output+ output = EvalOutput(+ instance_id=str(instance.instance_id),+ instance=instance.to_dict(),+ instruction=instruction,+ metadata=metadata,+ history=histories,+ metrics=metrics,+ error=state.last_error if state and state.last_error else None,+ test_result=test_result,+ )+ return output+++if __name__ == '__main__':+ args = parse_arguments()+ dataset = load_dataset('RajMaheshwari/Exercism-Python')+ aider_bench_tests = dataset['train'].to_pandas()++ llm_config = None+ if args.llm_config:+ llm_config = get_llm_config_arg(args.llm_config)++ if llm_config is None:+ raise ValueError(f'Could not find LLM config: --llm_config {args.llm_config}')++ metadata = make_metadata(+ llm_config,+ 'AiderBench',+ args.agent_cls,+ args.max_iterations,+ args.eval_note,+ args.eval_output_dir,+ )+ output_file = os.path.join(metadata.eval_output_dir, 'output.jsonl')+ instances = prepare_dataset(aider_bench_tests, output_file, args.eval_n_limit)++ asyncio.run(+ run_evaluation(+ instances,+ metadata,+ output_file,+ args.eval_num_workers,+ process_instance,+ )+ )diff --git a/evaluation/aider_bench/scripts/run_infer.sh b/evaluation/aider_bench/scripts/run_infer.shnew file mode 100755index 0000000000..b43607b3c7--- /dev/null+++ b/evaluation/aider_bench/scripts/run_infer.sh@@ -0,0 +1,43 @@+#!/bin/bash+set -eo pipefail++source "evaluation/utils/version_control.sh"++MODEL_CONFIG=$1+COMMIT_HASH=$2+AGENT=$3+EVAL_LIMIT=$4+NUM_WORKERS=$5++if [ -z "$NUM_WORKERS" ]; then+ NUM_WORKERS=1+ echo "Number of workers not specified, use default $NUM_WORKERS"+fi+checkout_eval_branch++if [ -z "$AGENT" ]; then+ echo "Agent not specified, use default CodeActAgent"+ AGENT="CodeActAgent"+fi++get_agent_version++echo "AGENT: $AGENT"+echo "AGENT_VERSION: $AGENT_VERSION"+echo "MODEL_CONFIG: $MODEL_CONFIG"++COMMAND="export PYTHONPATH=evaluation/aider_bench:\$PYTHONPATH && poetry run python evaluation/aider_bench/run_infer.py \+ --agent-cls $AGENT \+ --llm-config $MODEL_CONFIG \+ --max-iterations 30 \+ --max-chars 10000000 \+ --eval-num-workers $NUM_WORKERS \+ --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/evaluation/aider_bench/scripts/summarize_results.py b/evaluation/aider_bench/scripts/summarize_results.pynew file mode 100644index 0000000000..2df0b35919--- /dev/null+++ b/evaluation/aider_bench/scripts/summarize_results.py@@ -0,0 +1,37 @@+import json+import sys+++def extract_test_results(res_file_path: str) -> tuple[list[str], list[str]]:+ passed = []+ failed = []+ with open(res_file_path, 'r') as file:+ for line in file:+ data = json.loads(line.strip())+ instance_id = data['instance_id']+ resolved = False+ if 'test_result' in data and 'exit_code' in data['test_result']:+ resolved = data['test_result']['exit_code'] == 0+ if resolved:+ passed.append(instance_id)+ else:+ failed.append(instance_id)+ return passed, failed+++if __name__ == '__main__':+ if len(sys.argv) != 2:+ print(+ 'Usage: poetry run python summarise_results.py <path_to_output_jsonl_file>'+ )+ sys.exit(1)+ json_file_path = sys.argv[1]+ passed_tests, failed_tests = extract_test_results(json_file_path)+ succ_rate = len(passed_tests) / (len(passed_tests) + len(failed_tests))+ print(+ f'\nPassed {len(passed_tests)} tests, failed {len(failed_tests)} tests, resolve rate = {succ_rate}'+ )+ print('PASSED TESTS:')+ print(passed_tests)+ print('FAILED TESTS:')+ print(failed_tests)