| 1 | """ |
| 2 | An agent, which is only responsible for the write_patch tool call. |
| 3 | """ |
| 4 | |
| 5 | import json |
| 6 | import shutil |
| 7 | from collections.abc import Callable, Iterable |
| 8 | from copy import deepcopy |
| 9 | from os.path import join as pjoin |
| 10 | from pathlib import Path |
| 11 | |
| 12 | from loguru import logger |
| 13 | |
| 14 | from app import globals |
| 15 | from app.api import agent_common |
| 16 | from app.api.python import validation |
| 17 | from app.data_structures import MessageThread, MethodId |
| 18 | from app.log import print_acr, print_patch_generation |
| 19 | from app.model import common |
| 20 | from app.post_process import ( |
| 21 | ExtractStatus, |
| 22 | extract_diff_one_instance, |
| 23 | record_extract_status, |
| 24 | ) |
| 25 | from app.task import SweTask, Task |
| 26 | |
| 27 | SYSTEM_PROMPT = """You are a software developer maintaining a large project. |
| 28 | You are working on an issue submitted to your project. |
| 29 | The issue contains a description marked between <issue> and </issue>. |
| 30 | You ultimate goal is to write a patch that resolves this issue. |
| 31 | """ |
| 32 | |
| 33 | |
| 34 | USER_PROMPT_INIT = """Write a patch for the issue, based on the retrieved context.\n\nYou can import necessary libraries.\n\n |
| 35 | Return the patch in the format below.\n\nWithin `<file></file>`, replace `...` with actual file path.\n\nWithin `<original></original>`, replace `...` with the original code snippet from the program.\n\nWithin `<patched></patched>`, replace `...` with the fixed version of the original code. When adding orignal code and updated code, pay attention to indentation, as the code is in Python. |
| 36 | You can write multiple modifications if needed. |
| 37 | |
| 38 | ``` |
| 39 | # modification 1 |
| 40 | <file>...</file> |
| 41 | <original>...</original> |
| 42 | <patched>...</patched> |
| 43 | |
| 44 | # modification 2 |
| 45 | <file>...</file> |
| 46 | <original>...</original> |
| 47 | <patched>...</patched> |
| 48 | |
| 49 | # modification 3 |
| 50 | ... |
| 51 | ``` |
| 52 | """ |
| 53 | |
| 54 | |
| 55 | def run_with_retries( |
| 56 | message_thread: MessageThread, |
| 57 | output_dir: str, |
| 58 | task: Task, |
| 59 | retries=3, |
| 60 | print_callback: Callable[[dict], None] | None = None, |
| 61 | ) -> tuple[str, float, int, int]: |
| 62 | """ |
| 63 | Since the agent may not always write an applicable patch, we allow for retries. |
| 64 | This is a wrapper around the actual run. |
| 65 | """ |
| 66 | # (1) replace system prompt |
| 67 | messages = deepcopy(message_thread.messages) |
| 68 | new_thread: MessageThread = MessageThread(messages=messages) |
| 69 | new_thread = agent_common.replace_system_prompt(new_thread, SYSTEM_PROMPT) |
| 70 | |
| 71 | # (2) add the initial user prompt |
| 72 | new_thread.add_user(USER_PROMPT_INIT) |
| 73 | print_acr(USER_PROMPT_INIT, "patch generation", print_callback=print_callback) |
| 74 | |
| 75 | can_stop = False |
| 76 | result_msg = "" |
| 77 | |
| 78 | for i in range(1, retries + 2): |
| 79 | if i > 1: |
| 80 | debug_file = pjoin(output_dir, f"debug_agent_write_patch_{i - 1}.json") |
| 81 | with open(debug_file, "w") as f: |
| 82 | json.dump(new_thread.to_msg(), f, indent=4) |
| 83 | |
| 84 | if can_stop or i > retries: |
| 85 | break |
| 86 | |
| 87 | logger.info(f"Trying to write a patch. Try {i} of {retries}.") |
| 88 | |
| 89 | raw_patch_file = pjoin(output_dir, f"agent_patch_raw_{i}") |
| 90 | |
| 91 | # actually calling model |
| 92 | res_text, *_ = common.SELECTED_MODEL.call(new_thread.to_msg()) |
| 93 | |
| 94 | new_thread.add_model(res_text, []) # no tools |
| 95 | |
| 96 | logger.info(f"Raw patch produced in try {i}. Writing patch into file.") |
| 97 | |
| 98 | with open(raw_patch_file, "w") as f: |
| 99 | f.write(res_text) |
| 100 | |
| 101 | print_patch_generation( |
| 102 | res_text, f"try {i} / {retries}", print_callback=print_callback |
| 103 | ) |
| 104 | |
| 105 | # Attemp to extract a real patch from the raw patch |
| 106 | diff_file = pjoin(output_dir, f"extracted_patch_{i}.diff") |
| 107 | extract_status, extract_msg = extract_diff_one_instance( |
| 108 | raw_patch_file, diff_file |
| 109 | ) |
| 110 | |
| 111 | # record the extract status. This is for classifying the task at the end of workflow |
| 112 | record_extract_status(output_dir, extract_status) |
| 113 | |
| 114 | if extract_status == ExtractStatus.APPLICABLE_PATCH: |
| 115 | patch_content = Path(diff_file).read_text() |
| 116 | print_acr( |
| 117 | f"```diff\n{patch_content}\n```", |
| 118 | "extracted patch", |
| 119 | print_callback=print_callback, |
| 120 | ) |
| 121 | |
| 122 | # patch generated is applicable and all edits are ok, so we can think about validation |
| 123 | if globals.enable_validation: |
| 124 | # if we have a patch extracted, apply it and validate |
| 125 | |
| 126 | patch_is_correct, err_message, log_file = task.validate(diff_file) |
| 127 | shutil.move(log_file, pjoin(output_dir, f"run_test_suite_{i}.log")) |
| 128 | |
| 129 | if patch_is_correct: |
| 130 | result_msg = ( |
| 131 | "Written a patch that resolves the issue. Congratulations!" |
| 132 | ) |
| 133 | new_thread.add_user(result_msg) # just for logging |
| 134 | print_acr( |
| 135 | result_msg, |
| 136 | f"patch generation try {i} / {retries}", |
| 137 | print_callback=print_callback, |
| 138 | ) |
| 139 | can_stop = True |
| 140 | # the following two branches cannot be swapped, because |
| 141 | # --enable-perfect-angelic is meant to override --enable-angelic |
| 142 | elif globals.enable_perfect_angelic: |
| 143 | if not isinstance(task, SweTask): |
| 144 | raise NotImplementedError( |
| 145 | f"Angelic debugging not implemented for {type(task).__name__}" |
| 146 | ) |
| 147 | |
| 148 | msg = ( |
| 149 | f"Written an applicable patch, but it did not resolve the issue. Error message: {err_message}.", |
| 150 | ) |
| 151 | |
| 152 | incorrect_locations = validation.perfect_angelic_debug( |
| 153 | task.task_id, diff_file, task.project_path |
| 154 | ) |
| 155 | angelic_msg = angelic_debugging_message(incorrect_locations[0]) |
| 156 | |
| 157 | result_msg = f"{msg}\n{angelic_msg}" |
| 158 | new_thread.add_user(result_msg) |
| 159 | print_acr( |
| 160 | result_msg, |
| 161 | f"patch generation try {i} / {retries}", |
| 162 | print_callback=print_callback, |
| 163 | ) |
| 164 | continue |
| 165 | elif globals.enable_angelic: |
| 166 | raise NotImplementedError( |
| 167 | "Angelic debugging has not been integrated" |
| 168 | ) |
| 169 | else: |
| 170 | result_msg = f"Written an applicable patch, but it did not resolve the issue. {err_message} " |
| 171 | result_msg += " Please try again." |
| 172 | new_thread.add_user(result_msg) |
| 173 | print_acr( |
| 174 | result_msg, |
| 175 | f"patch generation try {i} / {retries}", |
| 176 | print_callback=print_callback, |
| 177 | ) |
| 178 | continue |
| 179 | elif globals.enable_perfect_angelic: |
| 180 | if not isinstance(task, SweTask): |
| 181 | raise NotImplementedError( |
| 182 | f"Angelic debugging not implemented for {type(task).__name__}" |
| 183 | ) |
| 184 | |
| 185 | incorrect_locations = validation.perfect_angelic_debug( |
| 186 | task.task_id, diff_file, task.project_path |
| 187 | ) |
| 188 | |
| 189 | msg = "Extracted a patch." |
| 190 | if angelic_msg := angelic_debugging_message(incorrect_locations[0]): |
| 191 | result_msg = f"{msg}\n{angelic_msg}" |
| 192 | else: |
| 193 | result_msg = msg |
| 194 | |
| 195 | new_thread.add_user(result_msg) |
| 196 | print_acr( |
| 197 | result_msg, |
| 198 | f"patch generation try {i} / {retries}", |
| 199 | print_callback=print_callback, |
| 200 | ) |
| 201 | continue |
| 202 | elif globals.enable_angelic: |
| 203 | raise NotImplementedError("Angelic debugging has not been integrated") |
| 204 | else: |
| 205 | result_msg = "Extracted a patch. Since validation is disabled, you should validation the patch later on. Ending the workflow." |
| 206 | new_thread.add_user(result_msg) # just for logging |
| 207 | print_acr( |
| 208 | result_msg, |
| 209 | f"patch generation try {i} / {retries}", |
| 210 | print_callback=print_callback, |
| 211 | ) |
| 212 | can_stop = True |
| 213 | |
| 214 | else: |
| 215 | # we dont have a valid patch |
| 216 | new_prompt = ( |
| 217 | "Your edit could not be applied to the program. " |
| 218 | + extract_msg |
| 219 | + " Please try again." |
| 220 | ) |
| 221 | new_thread.add_user(new_prompt) |
| 222 | print_acr( |
| 223 | new_prompt, |
| 224 | f"patch generation try {i} / {retries}", |
| 225 | print_callback=print_callback, |
| 226 | ) |
| 227 | result_msg = "Failed to write a valid patch." |
| 228 | |
| 229 | return result_msg |
| 230 | |
| 231 | |
| 232 | def angelic_debugging_message( |
| 233 | incorrect_locations: Iterable[tuple[str, MethodId]], |
| 234 | ) -> str: |
| 235 | msg = [] |
| 236 | |
| 237 | if incorrect_locations: |
| 238 | msg.append("The following methods should not have been changed:") |
| 239 | msg.extend( |
| 240 | f" {filename}: {method_id!s}" |
| 241 | for filename, method_id in incorrect_locations |
| 242 | ) |
| 243 | |
| 244 | return "\n".join(msg) |