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