Skip to content

πŸ™Œ OpenHands: AI-Driven Development

evaluation: Reset configs in finally block (#2214)

Boxuan Li538d1d85a209
diff --git a/evaluation/gaia/run_infer.py b/evaluation/gaia/run_infer.py
index 516a99476d..a6ea07208b 100644
--- a/evaluation/gaia/run_infer.py
+++ b/evaluation/gaia/run_infer.py
@@ -77,124 +77,133 @@ def process_instance(instance, agent_class, metadata, reset_logger: bool = True)
# we will create a workspace directory for EACH process
# so that different agent don't interfere with each other.
old_workspace_mount_path = config.workspace_mount_path
- workspace_mount_path = os.path.join(config.workspace_mount_path, '_eval_workspace')
- workspace_mount_path = os.path.join(workspace_mount_path, str(os.getpid()))
- pathlib.Path(workspace_mount_path).mkdir(parents=True, exist_ok=True)
- config.workspace_mount_path = workspace_mount_path
-
- # Setup the logger properly, so you can run multi-processing to parallize the evaluation
- eval_output_dir = metadata['eval_output_dir']
- if reset_logger:
- # Set up logger
- log_file = os.path.join(
- eval_output_dir, 'logs', f'instance_{instance["task_id"]}.log'
+
+ try:
+ workspace_mount_path = os.path.join(
+ config.workspace_mount_path, '_eval_workspace'
)
- # 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}'
+ workspace_mount_path = os.path.join(workspace_mount_path, str(os.getpid()))
+ pathlib.Path(workspace_mount_path).mkdir(parents=True, exist_ok=True)
+ config.workspace_mount_path = workspace_mount_path
+
+ # Setup the logger properly, so you can run multi-processing to parallize the evaluation
+ eval_output_dir = metadata['eval_output_dir']
+ if reset_logger:
+ # Set up logger
+ log_file = os.path.join(
+ eval_output_dir, 'logs', f'instance_{instance["task_id"]}.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)
+
+ logger.info(f'Process-specific workspace mounted at {workspace_mount_path}')
+ if instance['file_name'] != '':
+ # if this question comes with a file, we need to save it to the workspace
+ src_file = os.path.join(
+ DATASET_CACHE_DIR, '2023', metadata['data_split'], instance['file_name']
+ )
+ extension_name = instance['file_name'].split('.')[-1]
+ dest_file = os.path.join(workspace_mount_path, f'file.{extension_name}')
+ shutil.copyfile(src_file, dest_file)
+ logger.info(f'File copied to {dest_file}')
+ else:
+ dest_file = None
+
+ # Prepare instruction
+ instruction = f"{instance['Question']}\n"
+ logger.info(f'Instruction: {instruction}')
+ if dest_file:
+ instruction += f"\n\nThe mentioned file is provided in the workspace at: {dest_file.split('/')[-1]}"
+
+ instruction += 'IMPORTANT: You should ONLY interact with the environment provided to you AND NEVER ASK FOR HUMAN HELP.\n'
+ instruction += 'Please encapsulate your final answer (answer ONLY) within <solution> and </solution>.\n'
+ instruction += (
+ 'For example: The answer to the question is <solution> 42 </solution>.\n'
)
- # 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')
+ # NOTE: You can actually set slightly different instruction for different agents
+ instruction += AGENT_CLS_TO_INST_SUFFIX.get(agent_class, '')
+ logger.info(f'Instruction:\n{instruction}', extra={'msg_type': 'OBSERVATION'})
+
+ # 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
+ ),
+ )
)
- logger.addHandler(file_handler)
+ # ======= Attempt to evaluate the agent's edits =======
+ # If you are working on 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.')
+
+ model_answer_raw = ''
+ for act, _ in reversed(state.history):
+ if isinstance(act, CmdRunAction) and act.source == 'agent':
+ model_answer_raw = act.thought
+ break
+ elif isinstance(act, MessageAction) and act.source == 'agent':
+ model_answer_raw = act.content
+ break
+
+ # attempt to parse model_answer
+ model_answer = re.findall(r'<solution>(.*?)</solution>', model_answer_raw)
+ if len(model_answer) == 0:
+ logger.warning(f'Failed to parse model answer: {model_answer_raw}')
+ model_answer = model_answer_raw
+ else:
+ model_answer = model_answer[0]
- logger.info(f'Process-specific workspace mounted at {workspace_mount_path}')
- if instance['file_name'] != '':
- # if this question comes with a file, we need to save it to the workspace
- src_file = os.path.join(
- DATASET_CACHE_DIR, '2023', metadata['data_split'], instance['file_name']
+ logger.info(
+ f'Final message: {model_answer} | Ground truth: {instance["Final answer"]}'
)
- extension_name = instance['file_name'].split('.')[-1]
- dest_file = os.path.join(workspace_mount_path, f'file.{extension_name}')
- shutil.copyfile(src_file, dest_file)
- logger.info(f'File copied to {dest_file}')
- else:
- dest_file = None
-
- # Prepare instruction
- instruction = f"{instance['Question']}\n"
- logger.info(f'Instruction: {instruction}')
- if dest_file:
- instruction += f"\n\nThe mentioned file is provided in the workspace at: {dest_file.split('/')[-1]}"
-
- instruction += 'IMPORTANT: You should ONLY interact with the environment provided to you AND NEVER ASK FOR HUMAN HELP.\n'
- instruction += 'Please encapsulate your final answer (answer ONLY) within <solution> and </solution>.\n'
- instruction += (
- 'For example: The answer to the question is <solution> 42 </solution>.\n'
- )
- # NOTE: You can actually set slightly different instruction for different agents
- instruction += AGENT_CLS_TO_INST_SUFFIX.get(agent_class, '')
- logger.info(f'Instruction:\n{instruction}', extra={'msg_type': 'OBSERVATION'})
-
- # 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),
+ score = question_scorer(
+ model_answer=model_answer, ground_truth=instance['Final answer']
)
- )
- # ======= Attempt to evaluate the agent's edits =======
- # If you are working on 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.')
-
- model_answer_raw = ''
- for act, _ in reversed(state.history):
- if isinstance(act, CmdRunAction) and act.source == 'agent':
- model_answer_raw = act.thought
- break
- elif isinstance(act, MessageAction) and act.source == 'agent':
- model_answer_raw = act.content
- break
-
- # attempt to parse model_answer
- model_answer = re.findall(r'<solution>(.*?)</solution>', model_answer_raw)
- if len(model_answer) == 0:
- logger.warning(f'Failed to parse model answer: {model_answer_raw}')
- model_answer = model_answer_raw
- else:
- model_answer = model_answer[0]
-
- logger.info(
- f'Final message: {model_answer} | Ground truth: {instance["Final answer"]}'
- )
- score = question_scorer(
- model_answer=model_answer, ground_truth=instance['Final answer']
- )
- test_result = {
- 'score': score,
- 'model_answer_raw': model_answer_raw,
- 'model_answer': model_answer,
- 'ground_truth': instance['Final answer'],
- }
- metrics = state.metrics.get() if state.metrics else None
-
- # Save the output
- output = {
- 'instance_id': instance['task_id'],
- 'instance': instance,
- 'instruction': instance['Question'],
- 'metadata': metadata,
- 'history': [
- (event_to_dict(action), event_to_dict(obs)) for action, obs in state.history
- ],
- 'metrics': metrics,
- 'error': state.error if state and state.error else None,
- 'test_result': test_result,
- }
-
- # Close the sandbox
- config.workspace_mount_path = old_workspace_mount_path
+ test_result = {
+ 'score': score,
+ 'model_answer_raw': model_answer_raw,
+ 'model_answer': model_answer,
+ 'ground_truth': instance['Final answer'],
+ }
+ metrics = state.metrics.get() if state.metrics else None
+
+ # Save the output
+ output = {
+ 'instance_id': instance['task_id'],
+ 'instance': instance,
+ 'instruction': instance['Question'],
+ 'metadata': metadata,
+ 'history': [
+ (event_to_dict(action), event_to_dict(obs))
+ for action, obs in state.history
+ ],
+ 'metrics': metrics,
+ 'error': state.error if state and state.error else None,
+ 'test_result': test_result,
+ }
+ except Exception:
+ logger.error('Process instance failed')
+ raise
+ finally:
+ config.workspace_mount_path = old_workspace_mount_path
return output
diff --git a/evaluation/humanevalfix/run_infer.py b/evaluation/humanevalfix/run_infer.py
index 2598ef6dd2..d0fb0cfe0b 100644
--- a/evaluation/humanevalfix/run_infer.py
+++ b/evaluation/humanevalfix/run_infer.py
@@ -140,104 +140,114 @@ def process_instance(
):
old_workspace_mount_path = config.workspace_mount_path
old_workspace_base = config.workspace_base
- workspace_mount_path = os.path.join(config.workspace_mount_path, '_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_base = workspace_mount_path
- config.workspace_mount_path = workspace_mount_path
-
- # Setup the logger properly, so you can run multi-processing to parallize 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')
+
+ try:
+ workspace_mount_path = os.path.join(
+ config.workspace_mount_path, '_eval_workspace'
)
- logger.addHandler(file_handler)
+ # 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_base = workspace_mount_path
+ config.workspace_mount_path = workspace_mount_path
+
+ # Setup the logger properly, so you can run multi-processing to parallize 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}')
+ if not skip_workspace_mount:
+ logger.info(f'Process-specific workspace mounted at {workspace_mount_path}')
- # Create file with HumanEvalFix problem
- # Prompt reference: https://github.com/bigcode-project/bigcode-evaluation-harness/blob/84b96da31b7f840b55c5733325346176140cdb6b/bigcode_eval/tasks/humanevalpack.py#L509
- problem_statement = (
- instance.declaration + instance.buggy_solution + '\n' + instance.test
- )
- path = os.path.join(
- workspace_mount_path, f'{instance.task_id.replace("/", "__")}.py'
- )
- with open(path, 'w') as f:
- f.write(problem_statement)
-
- # Prepare instruction
- instruction = (
- f'Please fix the function in {instance.task_id.replace("/", "__")}.py such that all test cases pass.\n'
- 'Environment has been set up for you to start working. You may assume all necessary tools are installed.\n\n'
- '# Problem Statement\n'
- f'{problem_statement}\n\n'
- )
- instruction += (
- 'IMPORTANT: You should ONLY interact with the environment provided to you AND NEVER ASK FOR HUMAN HELP.\n'
- 'You should NOT modify any existing test case files. If needed, you can add new test cases in a NEW file to reproduce the issue.\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),
+ # Create file with HumanEvalFix problem
+ # Prompt reference: https://github.com/bigcode-project/bigcode-evaluation-harness/blob/84b96da31b7f840b55c5733325346176140cdb6b/bigcode_eval/tasks/humanevalpack.py#L509
+ problem_statement = (
+ instance.declaration + instance.buggy_solution + '\n' + instance.test
+ )
+ path = os.path.join(
+ workspace_mount_path, f'{instance.task_id.replace("/", "__")}.py'
+ )
+ with open(path, 'w') as f:
+ f.write(problem_statement)
+
+ # Prepare instruction
+ instruction = (
+ f'Please fix the function in {instance.task_id.replace("/", "__")}.py such that all test cases pass.\n'
+ 'Environment has been set up for you to start working. You may assume all necessary tools are installed.\n\n'
+ '# Problem Statement\n'
+ f'{problem_statement}\n\n'
+ )
+ instruction += (
+ 'IMPORTANT: You should ONLY interact with the environment provided to you AND NEVER ASK FOR HUMAN HELP.\n'
+ 'You should NOT modify any existing test case files. If needed, you can add new test cases in a NEW file to reproduce the issue.\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.')
- metrics = state.metrics.get() if state.metrics else 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
- ],
- 'metrics': metrics,
- 'error': state.error if state and state.error else None,
- 'test_result': test_result,
- }
- config.workspace_mount_path = old_workspace_mount_path
- config.workspace_base = old_workspace_base
+ # ======= 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.')
+ metrics = state.metrics.get() if state.metrics else 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
+ ],
+ 'metrics': metrics,
+ 'error': state.error if state and state.error else None,
+ 'test_result': test_result,
+ }
+ except Exception:
+ logger.error('Process instance failed')
+ raise
+ finally:
+ config.workspace_mount_path = old_workspace_mount_path
+ config.workspace_base = old_workspace_base
return output
diff --git a/evaluation/logic_reasoning/run_infer.py b/evaluation/logic_reasoning/run_infer.py
index 2d8871481d..33b4bf91ce 100644
--- a/evaluation/logic_reasoning/run_infer.py
+++ b/evaluation/logic_reasoning/run_infer.py
@@ -138,126 +138,137 @@ def process_instance(
):
old_workspace_mount_path = config.workspace_mount_path
old_workspace_base = config.workspace_base
- workspace_mount_path = os.path.join(config.workspace_mount_path, '_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_base = workspace_mount_path
- config.workspace_mount_path = workspace_mount_path
-
- # Setup the logger properly, so you can run multi-processing to parallize the evaluation
- if reset_logger:
- # Set up logger
- log_file = os.path.join(
- eval_output_dir, 'logs', f'instance_{instance["id"]}.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["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')
+
+ try:
+ workspace_mount_path = os.path.join(
+ config.workspace_mount_path, '_eval_workspace'
)
- logger.addHandler(file_handler)
+ # 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_base = workspace_mount_path
+ config.workspace_mount_path = workspace_mount_path
+
+ # Setup the logger properly, so you can run multi-processing to parallize the evaluation
+ if reset_logger:
+ # Set up logger
+ log_file = os.path.join(
+ eval_output_dir, 'logs', f'instance_{instance["id"]}.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["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}')
+ if not skip_workspace_mount:
+ logger.info(f'Process-specific workspace mounted at {workspace_mount_path}')
- # sandbox = DockerSSHBox()
- logic_inference_path = os.path.join(workspace_mount_path, 'logic_inference.py')
- if not os.path.exists(logic_inference_path):
- shutil.copyfile(
- './evaluation/logic_reasoning/logic_inference.py', logic_inference_path
- )
- logger.info(f'logic_inference.py copied to {workspace_mount_path}')
+ # sandbox = DockerSSHBox()
+ logic_inference_path = os.path.join(workspace_mount_path, 'logic_inference.py')
+ if not os.path.exists(logic_inference_path):
+ shutil.copyfile(
+ './evaluation/logic_reasoning/logic_inference.py', logic_inference_path
+ )
+ logger.info(f'logic_inference.py copied to {workspace_mount_path}')
- cache_dir = os.path.join(workspace_mount_path, '.cache_program')
- if not os.path.exists(cache_dir):
- os.makedirs(cache_dir)
+ cache_dir = os.path.join(workspace_mount_path, '.cache_program')
+ if not os.path.exists(cache_dir):
+ os.makedirs(cache_dir)
- # Prepare instruction
+ # Prepare instruction
- with open('./evaluation/logic_reasoning/instruction.txt', 'r') as f:
- instruction = f.read()
+ with open('./evaluation/logic_reasoning/instruction.txt', 'r') as f:
+ instruction = f.read()
- instance_logic_programs = instance['raw_logic_programs'][0].strip()
- instruction = instruction.replace('[[dataset_name]]', dataset_name)
- instruction = instruction.replace('[[logic_programs]]', instance_logic_programs)
- instruction = instruction.replace(
- '[[logic_inference_path.py]]', logic_inference_path
- )
+ instance_logic_programs = instance['raw_logic_programs'][0].strip()
+ instruction = instruction.replace('[[dataset_name]]', dataset_name)
+ instruction = instruction.replace('[[logic_programs]]', instance_logic_programs)
+ instruction = instruction.replace(
+ '[[logic_inference_path.py]]', logic_inference_path
+ )
- # NOTE: You can actually set slightly different instruction for different agents
- instruction += AGENT_CLS_TO_INST_SUFFIX.get(agent_class, '')
+ # NOTE: You can actually set slightly different instruction for different agents
+ instruction += AGENT_CLS_TO_INST_SUFFIX.get(agent_class, '')
- sandbox = DockerSSHBox()
- exit_code, command_output = sandbox.execute('pip install scitools-pyke')
+ sandbox = DockerSSHBox()
+ exit_code, command_output = sandbox.execute('pip install scitools-pyke')
- # 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),
- sandbox=sandbox,
+ # 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
+ ),
+ sandbox=sandbox,
+ )
)
- )
- # ======= Attempt to evaluate the agent's edits =======
- # If you are working on 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.')
-
- final_message = ''
- messages = []
- for action, obs in reversed(state.history):
- # if isinstance(act, MessageAction):
- messages.append(obs.content)
- # print("obs.content:", obs.content)
- if str(obs.content) in ["'A'", "'B'", "'C'"]:
- final_message = obs.content
- break
-
- final_message = final_message.strip("'")
- logger.info(
- f'Predicted answer: {final_message}, Ground truth: {instance["answer"]}'
- )
+ # ======= Attempt to evaluate the agent's edits =======
+ # If you are working on 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.')
+
+ final_message = ''
+ messages = []
+ for action, obs in reversed(state.history):
+ # if isinstance(act, MessageAction):
+ messages.append(obs.content)
+ # print("obs.content:", obs.content)
+ if str(obs.content) in ["'A'", "'B'", "'C'"]:
+ final_message = obs.content
+ break
- test_result = get_test_result(
- model_answer=final_message, ground_truth=instance['answer']
- )
- metrics = state.metrics.get() if state.metrics else None
-
- # Save the output
- output = {
- 'id': instance['id'],
- 'instance': instance,
- 'instruction': instruction,
- # 'metadata': metadata,
- 'history': [
- (event_to_dict(action), event_to_dict(obs)) for action, obs in state.history
- ],
- 'metrics': metrics,
- 'final_message': final_message,
- 'messages': messages,
- 'error': state.error if state and state.error else None,
- 'test_result': test_result,
- }
- config.workspace_mount_path = old_workspace_mount_path
- config.workspace_base = old_workspace_base
+ final_message = final_message.strip("'")
+ logger.info(
+ f'Predicted answer: {final_message}, Ground truth: {instance["answer"]}'
+ )
+
+ test_result = get_test_result(
+ model_answer=final_message, ground_truth=instance['answer']
+ )
+ metrics = state.metrics.get() if state.metrics else None
+
+ # Save the output
+ output = {
+ 'id': instance['id'],
+ 'instance': instance,
+ 'instruction': instruction,
+ # 'metadata': metadata,
+ 'history': [
+ (event_to_dict(action), event_to_dict(obs))
+ for action, obs in state.history
+ ],
+ 'metrics': metrics,
+ 'final_message': final_message,
+ 'messages': messages,
+ 'error': state.error if state and state.error else None,
+ 'test_result': test_result,
+ }
+ except Exception:
+ logger.error('Process instance failed')
+ raise
+ finally:
+ config.workspace_mount_path = old_workspace_mount_path
+ config.workspace_base = old_workspace_base
# Close the sandbox
sandbox.close()
diff --git a/evaluation/swe_bench/swe_env_box.py b/evaluation/swe_bench/swe_env_box.py
index 3bf9619875..16ec63f2ca 100644
--- a/evaluation/swe_bench/swe_env_box.py
+++ b/evaluation/swe_bench/swe_env_box.py
@@ -83,45 +83,49 @@ class SWEBenchSSHBox(DockerSSHBox):
)
old_workspace_base = config.workspace_base
old_workspace_mount_path = config.workspace_mount_path
- config.workspace_base = workspace_mount_path
- config.workspace_mount_path = workspace_mount_path
- # linting python after editing helps LLM fix indentations
- config.enable_auto_lint = True
- # Need to run as root to use SWEBench container
- config.run_as_devin = False
- sandbox = cls(
- container_image=SWE_BENCH_CONTAINER_IMAGE,
- swe_instance_id=instance['instance_id'],
- swe_instance=instance,
- skip_workspace_mount=skip_workspace_mount,
- sandbox_plugins=sandbox_plugins,
- workspace_dir_name=workspace_dir_name,
- )
- logger.info(f"SSH box started for instance {instance['instance_id']}.")
-
- # cd to the repo
- exit_code, output = sandbox.execute(f'cd /workspace/{workspace_dir_name}')
- if exit_code != 0:
- logger.error(f'Failed to cd to the repo: {output}')
- sys.exit(1)
-
- # remove all future commits & remote following Devin
- # https://www.cognition-labs.com/post/swe-bench-technical-report
- exit_code, output = sandbox.execute('git reset --hard')
- if exit_code != 0:
- logger.error(f'Failed to reset the repo: {output}')
- sys.exit(1)
- exit_code, output = sandbox.execute(
- 'for remote_name in $(git remote); do git remote remove "${remote_name}"; done'
- )
- if exit_code != 0:
- logger.error(f'Failed to remove remote: {output}')
- sys.exit(1)
-
- # restore workspace_base and workspace_mount_path
- config.workspace_base = old_workspace_base
- config.workspace_mount_path = old_workspace_mount_path
+ try:
+ config.workspace_base = workspace_mount_path
+ config.workspace_mount_path = workspace_mount_path
+
+ # linting python after editing helps LLM fix indentations
+ config.enable_auto_lint = True
+ # Need to run as root to use SWEBench container
+ config.run_as_devin = False
+ sandbox = cls(
+ container_image=SWE_BENCH_CONTAINER_IMAGE,
+ swe_instance_id=instance['instance_id'],
+ swe_instance=instance,
+ skip_workspace_mount=skip_workspace_mount,
+ sandbox_plugins=sandbox_plugins,
+ workspace_dir_name=workspace_dir_name,
+ )
+ logger.info(f"SSH box started for instance {instance['instance_id']}.")
+
+ # cd to the repo
+ exit_code, output = sandbox.execute(f'cd /workspace/{workspace_dir_name}')
+ if exit_code != 0:
+ logger.error(f'Failed to cd to the repo: {output}')
+ sys.exit(1)
+
+ # remove all future commits & remote following Devin
+ # https://www.cognition-labs.com/post/swe-bench-technical-report
+ exit_code, output = sandbox.execute('git reset --hard')
+ if exit_code != 0:
+ logger.error(f'Failed to reset the repo: {output}')
+ sys.exit(1)
+ exit_code, output = sandbox.execute(
+ 'for remote_name in $(git remote); do git remote remove "${remote_name}"; done'
+ )
+ if exit_code != 0:
+ logger.error(f'Failed to remove remote: {output}')
+ sys.exit(1)
+ except Exception:
+ raise
+ finally:
+ # restore workspace_base and workspace_mount_path
+ config.workspace_base = old_workspace_base
+ config.workspace_mount_path = old_workspace_mount_path
return sandbox
def get_diff_patch(self):