| 1 | import inspect |
| 2 | import json |
| 3 | import re |
| 4 | from collections.abc import Callable |
| 5 | from os.path import join as pjoin |
| 6 | from pathlib import Path |
| 7 | |
| 8 | from loguru import logger |
| 9 | from termcolor import colored |
| 10 | |
| 11 | from app import globals |
| 12 | from app.api.manage import ProjectApiManager |
| 13 | from app.data_structures import FunctionCallIntent, MessageThread |
| 14 | from app.log import ( |
| 15 | log_and_cprint, |
| 16 | log_and_print, |
| 17 | print_acr, |
| 18 | print_banner, |
| 19 | print_issue, |
| 20 | print_retrieval, |
| 21 | ) |
| 22 | from app.model import common, ollama |
| 23 | from app.search.search_manage import SearchManager |
| 24 | from app.utils import parse_function_invocation |
| 25 | |
| 26 | # FIXME: the system prompt should be different for stratified/state machine. |
| 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 | Your task is to invoke a few search API calls to gather buggy information, then write patches to solve the issues. |
| 31 | """ |
| 32 | |
| 33 | |
| 34 | def prepare_issue_prompt(problem_stmt: str) -> str: |
| 35 | """ |
| 36 | Given the raw problem statement, sanitize it and prepare the issue prompt. |
| 37 | Args: |
| 38 | problem_stmt (str): The raw problem statement. |
| 39 | Assumption: the problem statement is the content of a markdown file. |
| 40 | Returns: |
| 41 | str: The issue prompt. |
| 42 | """ |
| 43 | # remove markdown comments |
| 44 | problem_wo_comments = re.sub(r"<!--.*?-->", "", problem_stmt, flags=re.DOTALL) |
| 45 | content_lines = problem_wo_comments.split("\n") |
| 46 | # remove spaces and empty lines |
| 47 | content_lines = [x.strip() for x in content_lines] |
| 48 | content_lines = [x for x in content_lines if x != ""] |
| 49 | problem_stripped = "\n".join(content_lines) |
| 50 | # add tags |
| 51 | result = "<issue>" + problem_stripped + "\n</issue>" |
| 52 | return result |
| 53 | |
| 54 | |
| 55 | def add_step_trigger(orig_prompt: str, is_first: bool = False) -> str: |
| 56 | """ |
| 57 | Given the original prompt, add the trigger question for the next step. |
| 58 | Args: |
| 59 | orig_prompt (str): The original prompt. |
| 60 | is_first (bool): Whether the trigger is for the first step. |
| 61 | Returns: |
| 62 | str: The prompt with trigger question. |
| 63 | """ |
| 64 | if is_first: |
| 65 | trigger = "What is the first step?" |
| 66 | else: |
| 67 | trigger = "What's the next step to complete the task? Be reminded that you are solving the initial issue." |
| 68 | return orig_prompt + "\n" + trigger |
| 69 | |
| 70 | |
| 71 | def start_conversation_round_stratified( |
| 72 | output_dir: str, |
| 73 | msg_thread: MessageThread, |
| 74 | api_manager: ProjectApiManager, |
| 75 | start_round_no: int = 0, |
| 76 | print_callback: Callable[[dict], None] | None = None, |
| 77 | ) -> bool: |
| 78 | """ |
| 79 | This version uses json data to process API calls, instead of using the OpenAI function calling. |
| 80 | Advantage is that multiple API calls can be made in a single round. |
| 81 | """ |
| 82 | prompt = ( |
| 83 | "Based on the files, classes, methods, and code statements from the issue related to the bug, you can use the following search APIs to get more context of the project." |
| 84 | "\n- search_class(class_name: str): Search for a class in the codebase" |
| 85 | "\n- search_method_in_file(method_name: str, file_path: str): Search for a method in a given file" |
| 86 | "\n- search_method_in_class(method_name: str, class_name: str): Search for a method in a given class" |
| 87 | "\n- search_method(method_name: str): Search for a method in the entire codebase" |
| 88 | "\n- search_code(code_str: str): Search for a code snippet in the entire codebase" |
| 89 | "\n- search_code_in_file(code_str: str, file_path: str): Search for a code snippet in a given file file" |
| 90 | "\n\nNote that you can use multiple search APIs in one round." |
| 91 | "\n\nNow analyze the issue and select necessary APIs to get more context of the project. Each API call must have concrete arguments as inputs." |
| 92 | ) |
| 93 | msg_thread.add_user(prompt) |
| 94 | |
| 95 | round_no = start_round_no |
| 96 | |
| 97 | round_count = range(start_round_no, globals.conv_round_limit + 1) |
| 98 | |
| 99 | try_generate_locs = False |
| 100 | if globals.disable_patch_generation: |
| 101 | round_count = range( |
| 102 | start_round_no, start_round_no + globals.context_generation_limit + 1 |
| 103 | ) |
| 104 | |
| 105 | for round_no in round_count: |
| 106 | api_manager.start_new_tool_call_layer() |
| 107 | |
| 108 | conversation_file = pjoin(output_dir, f"conversation_round_{round_no}.json") |
| 109 | # save current state before starting a new round |
| 110 | msg_thread.save_to_file(conversation_file) |
| 111 | |
| 112 | print_banner(f"CONTEXT RETRIEVAL ROUND {round_no}") |
| 113 | |
| 114 | print_acr( |
| 115 | prompt, |
| 116 | f"context retrieval round {start_round_no}", |
| 117 | print_callback=print_callback, |
| 118 | ) |
| 119 | |
| 120 | res_text, *_ = common.SELECTED_MODEL.call(msg_thread.to_msg()) |
| 121 | msg_thread.add_model(res_text, tools=[]) |
| 122 | print_retrieval(res_text, f"round {round_no}", print_callback=print_callback) |
| 123 | |
| 124 | selected_apis, _, proxy_threads = api_manager.proxy_apis(res_text) |
| 125 | |
| 126 | proxy_log = Path(output_dir, f"agent_proxy_{round_no}.json") |
| 127 | proxy_messages = [thread.to_msg() for thread in proxy_threads] |
| 128 | proxy_log.write_text(json.dumps(proxy_messages, indent=4)) |
| 129 | |
| 130 | if selected_apis is None: |
| 131 | msg = "The search API calls seem not valid. Please check the arguments you give carefully and try again." |
| 132 | msg_thread.add_user(msg) |
| 133 | print_acr( |
| 134 | msg, |
| 135 | f"context retrieval round {round_no}", |
| 136 | print_callback=print_callback, |
| 137 | ) |
| 138 | continue |
| 139 | |
| 140 | selected_apis_json = json.loads(selected_apis) |
| 141 | |
| 142 | json_api_calls = selected_apis_json.get("API_calls", []) |
| 143 | buggy_locations = selected_apis_json.get("bug_locations", []) |
| 144 | |
| 145 | formatted = [] |
| 146 | if json_api_calls: |
| 147 | formatted.append("API calls:") |
| 148 | for call in json_api_calls: |
| 149 | formatted.extend([f"\n- `{call}`"]) |
| 150 | |
| 151 | if buggy_locations: |
| 152 | formatted.append("\n\nBug locations") |
| 153 | for location in buggy_locations: |
| 154 | s = ", ".join(f"{k}: `{v}`" for k, v in location.items()) |
| 155 | formatted.extend([f"\n- {s}"]) |
| 156 | Path(output_dir, f"fix_locations_{round_no}.json").write_text( |
| 157 | json.dumps(buggy_locations, indent=4) |
| 158 | ) |
| 159 | |
| 160 | print_acr( |
| 161 | "\n".join(formatted), |
| 162 | "Agent-selected API calls", |
| 163 | print_callback=print_callback, |
| 164 | ) |
| 165 | |
| 166 | # collected enough information to write patch |
| 167 | if buggy_locations and (not json_api_calls): |
| 168 | collated_tool_response = "Here is the code in buggy locations:\n\n" |
| 169 | # provide the buggy locations to the model |
| 170 | for bug_location in buggy_locations: |
| 171 | tool_output, *_ = search_for_bug_location( |
| 172 | api_manager, msg_thread, bug_location |
| 173 | ) |
| 174 | collated_tool_response += f"\n\n{tool_output}\n" |
| 175 | |
| 176 | if ( |
| 177 | "Unknown function" not in collated_tool_response |
| 178 | and "Could not" not in collated_tool_response |
| 179 | ): |
| 180 | msg_thread.add_user(collated_tool_response) |
| 181 | |
| 182 | if globals.disable_patch_generation: |
| 183 | logger.debug( |
| 184 | "Gathered enough information. Skipping patch generation due to feature flag." |
| 185 | ) |
| 186 | else: |
| 187 | print_banner("PATCH GENERATION") |
| 188 | logger.debug("Gathered enough information. Invoking write_patch.") |
| 189 | print_acr( |
| 190 | collated_tool_response, |
| 191 | "patch generation round 1", |
| 192 | print_callback=print_callback, |
| 193 | ) |
| 194 | break |
| 195 | |
| 196 | msg = "The buggy locations is not precise. You may need to check whether the arguments are correct and search more information." |
| 197 | msg_thread.add_user(msg) |
| 198 | print_acr( |
| 199 | msg, |
| 200 | f"context retrieval round {round_no}", |
| 201 | print_callback=print_callback, |
| 202 | ) |
| 203 | continue |
| 204 | |
| 205 | # prepare response from tools |
| 206 | collated_tool_response = "" |
| 207 | |
| 208 | for api_call in json_api_calls: |
| 209 | func_name, func_args = parse_function_invocation(api_call) |
| 210 | |
| 211 | arg_spec = inspect.getfullargspec(getattr(SearchManager, func_name)) |
| 212 | arg_names = arg_spec.args[1:] # first parameter is self |
| 213 | |
| 214 | assert len(func_args) == len( |
| 215 | arg_names |
| 216 | ), f"Number of argument is wrong in API call: {api_call}" |
| 217 | |
| 218 | kwargs = dict(zip(arg_names, func_args)) |
| 219 | intent = FunctionCallIntent(func_name, kwargs, None) |
| 220 | tool_output, _, _ = api_manager.dispatch_intent(intent, msg_thread) |
| 221 | |
| 222 | collated_tool_response += f"Result of {api_call}:\n\n" |
| 223 | collated_tool_response += tool_output + "\n\n" |
| 224 | |
| 225 | msg_thread.add_user(collated_tool_response) |
| 226 | print_acr( |
| 227 | collated_tool_response, |
| 228 | f"context retrieval round {round_no}", |
| 229 | print_callback=print_callback, |
| 230 | ) |
| 231 | |
| 232 | msg = "Let's analyze collected context first" |
| 233 | msg_thread.add_user(msg) |
| 234 | print_acr( |
| 235 | msg, f"context retrieval round {round_no}", print_callback=print_callback |
| 236 | ) |
| 237 | |
| 238 | res_text, *_ = common.SELECTED_MODEL.call(msg_thread.to_msg()) |
| 239 | msg_thread.add_model(res_text, tools=[]) |
| 240 | print_retrieval(res_text, f"round {round_no}", print_callback=print_callback) |
| 241 | |
| 242 | if round_no < globals.conv_round_limit: |
| 243 | msg = ( |
| 244 | "Based on your analysis, answer below questions:" |
| 245 | "\n- do we need more context: construct search API calls to get more context of the project. (leave it empty if you don't need more context)" |
| 246 | "\n- where are bug locations: buggy files and methods. (leave it empty if you don't have enough information)" |
| 247 | ) |
| 248 | if isinstance(common.SELECTED_MODEL, ollama.OllamaModel): |
| 249 | # llama models tend to always output search APIs and buggy locations. |
| 250 | msg += "\n\nNOTE: If you have already identified the bug locations, do not make any search API calls." |
| 251 | msg_thread.add_user(msg) |
| 252 | print_acr( |
| 253 | msg, |
| 254 | f"context retrieval round {round_no}", |
| 255 | print_callback=print_callback, |
| 256 | ) |
| 257 | else: |
| 258 | log_msg = "Try writing patch anyway." |
| 259 | # TODO can be improved more |
| 260 | if globals.disable_patch_generation: |
| 261 | all_locs = [] |
| 262 | for fix_location_file in Path(output_dir).glob("*fix_locations_*.json"): |
| 263 | all_locs += json.loads(Path(fix_location_file).read_text()) |
| 264 | all_locs = list(set(map(json.dumps, all_locs))) |
| 265 | Path(output_dir, "fix_locations.json").write_text( |
| 266 | json.dumps(all_locs, indent=4) |
| 267 | ) |
| 268 | try_generate_locs = all_locs != [] |
| 269 | log_msg = "Try outputing some locations still." |
| 270 | |
| 271 | logger.info(f"Too many rounds. {log_msg}") |
| 272 | |
| 273 | round_no += 1 |
| 274 | |
| 275 | if not globals.disable_patch_generation: |
| 276 | intent = FunctionCallIntent("write_patch", {}, None) |
| 277 | elif try_generate_locs: |
| 278 | intent = FunctionCallIntent("propose_locs", {}, None) |
| 279 | else: |
| 280 | intent = None |
| 281 | |
| 282 | if intent: |
| 283 | api_manager.start_new_tool_call_layer() |
| 284 | api_manager.dispatch_intent(intent, msg_thread, print_callback=print_callback) |
| 285 | logger.info(f"Invoked {intent.func_name}.") |
| 286 | |
| 287 | logger.info("Ending workflow.") |
| 288 | conversation_file = pjoin(output_dir, f"conversation_round_{round_no}.json") |
| 289 | msg_thread.save_to_file(conversation_file) |
| 290 | |
| 291 | return True |
| 292 | |
| 293 | |
| 294 | def search_for_bug_location( |
| 295 | api_manager: ProjectApiManager, |
| 296 | msg_thread: MessageThread, |
| 297 | bug_location: dict[str, str], |
| 298 | ) -> tuple[str, str, bool]: |
| 299 | found = False |
| 300 | |
| 301 | file_name = bug_location.get("file") |
| 302 | method_name = bug_location.get("method") |
| 303 | class_name = bug_location.get("class") |
| 304 | |
| 305 | assert method_name or class_name, f"Invalid bug location: {bug_location}" |
| 306 | |
| 307 | call_result = None |
| 308 | |
| 309 | def call_function(func_name: str, kwargs: dict[str, str]) -> None: |
| 310 | nonlocal found, call_result |
| 311 | |
| 312 | intent = FunctionCallIntent(func_name, kwargs, None) |
| 313 | call_result = api_manager.dispatch_intent(intent, msg_thread) |
| 314 | _, _, call_is_ok = call_result |
| 315 | found |= call_is_ok |
| 316 | |
| 317 | if (not found) and method_name and class_name: |
| 318 | kwargs = {"method_name": method_name, "class_name": class_name} |
| 319 | call_function("search_method_in_class", kwargs) |
| 320 | |
| 321 | if (not found) and method_name and file_name: |
| 322 | kwargs = {"method_name": method_name, "file_name": file_name} |
| 323 | call_function("search_method_in_file", kwargs) |
| 324 | |
| 325 | if (not found) and class_name and file_name: |
| 326 | kwargs = {"class_name": class_name, "file_name": file_name} |
| 327 | call_function("search_class_in_file", kwargs) |
| 328 | |
| 329 | if (not found) and class_name: |
| 330 | kwargs = {"class_name": class_name} |
| 331 | call_function("get_class_full_snippet", kwargs) |
| 332 | |
| 333 | if (not found) and method_name: |
| 334 | kwargs = {"method_name": method_name} |
| 335 | call_function("search_method", kwargs) |
| 336 | |
| 337 | assert call_result |
| 338 | |
| 339 | return call_result |
| 340 | |
| 341 | |
| 342 | def dump_tool_call_layers_to_file( |
| 343 | tool_call_layers: list[dict], output_dir: str |
| 344 | ) -> None: |
| 345 | """Dump the layers of tool calls to a file.""" |
| 346 | tool_call_file = pjoin(output_dir, "tool_call_layers.json") |
| 347 | with open(tool_call_file, "w") as f: |
| 348 | json.dump(tool_call_layers, f, indent=4) |
| 349 | |
| 350 | |
| 351 | def start_conversation_round_state_machine( |
| 352 | output_dir: str, |
| 353 | msg_thread: MessageThread, |
| 354 | api_manager: ProjectApiManager, |
| 355 | start_round_no: int = 0, |
| 356 | ) -> bool: |
| 357 | """ |
| 358 | Start the actual rounds of conversations with model. |
| 359 | |
| 360 | Args: |
| 361 | output_dir (str): Path to the output directory. |
| 362 | msg_thread (MessageThread): The message thread to be used. |
| 363 | api_manager (ProjectApiManager): The API manager to be used. |
| 364 | start_round_no (int): The round number to start with. |
| 365 | """ |
| 366 | round_no = start_round_no |
| 367 | for round_no in range(start_round_no, globals.conv_round_limit + 1): |
| 368 | conversation_file = pjoin(output_dir, f"conversation_round_{round_no}.json") |
| 369 | # save current state before starting a new round |
| 370 | msg_thread.save_to_file(conversation_file) |
| 371 | log_and_cprint( |
| 372 | f"\n========== Conversation Round {round_no} ==========", style="red bold" |
| 373 | ) |
| 374 | log_and_print(f"{colored('Current message thread:', 'green')}\n{msg_thread}") |
| 375 | |
| 376 | allowed_tools = api_manager.next_tools() |
| 377 | # TODO: configure the list of tools based on state machine |
| 378 | tools = ProjectApiManager.get_full_funcs_for_openai(allowed_tools) |
| 379 | |
| 380 | log_and_cprint(f"Current tool state: {api_manager.curr_tool}", style="yellow") |
| 381 | log_and_cprint(f"Allowed next tool states: {allowed_tools}", style="yellow") |
| 382 | |
| 383 | # create a new iteration of conversation |
| 384 | res_text, raw_tool_calls, func_call_intents, *_ = common.SELECTED_MODEL.call( |
| 385 | msg_thread.to_msg(), tools=tools |
| 386 | ) |
| 387 | log_and_print( |
| 388 | f"{colored('This roud model response (text):', 'blue')} {res_text}" |
| 389 | ) |
| 390 | # model can decide whether to create a function call |
| 391 | if len(func_call_intents) == 1: |
| 392 | # good case in which we can check function call |
| 393 | func_call_intent: FunctionCallIntent = func_call_intents[0] |
| 394 | log_and_print( |
| 395 | f"{colored('This round model response (function call):', 'blue')} {func_call_intent}" |
| 396 | ) |
| 397 | # dispatch this function call |
| 398 | this_model_response = res_text |
| 399 | this_model_tools = raw_tool_calls |
| 400 | # add previous call information to user message |
| 401 | tool_output, summary, _ = api_manager.dispatch_intent( |
| 402 | func_call_intent, msg_thread |
| 403 | ) |
| 404 | else: |
| 405 | # no function call, let's force the model to make one |
| 406 | this_model_tools = [] |
| 407 | this_model_response = res_text |
| 408 | tool_output = "" |
| 409 | summary = "There is no function call in your previous response. Make sure you include one function call. " |
| 410 | |
| 411 | next_user_message = add_step_trigger(summary) |
| 412 | |
| 413 | # form message thread for next round. should include what the model said as well |
| 414 | msg_thread.add_model(this_model_response, this_model_tools) |
| 415 | if this_model_tools: |
| 416 | tool_call_id = this_model_tools[0].id |
| 417 | msg_thread.add_tool(tool_output, tool_call_id) |
| 418 | msg_thread.add_user(next_user_message) |
| 419 | else: |
| 420 | msg_thread.add_user(next_user_message) |
| 421 | |
| 422 | if len(func_call_intents) == 1: |
| 423 | func_call_name = func_call_intents[0].func_name |
| 424 | if func_call_name == "write_patch": |
| 425 | log_and_print("Ending workflow. write_patch has been invoked.") |
| 426 | break |
| 427 | |
| 428 | log_and_print("Going to next round ..........") |
| 429 | else: |
| 430 | log_and_print("Too many rounds. Try writing patch anyway.") |
| 431 | write_patch_intent = FunctionCallIntent("write_patch", {}, None) |
| 432 | api_manager.dispatch_intent(write_patch_intent, msg_thread) |
| 433 | |
| 434 | round_no += 1 |
| 435 | |
| 436 | # if we end the workflow normally, there is one more round of conversation to store |
| 437 | conversation_file = pjoin(output_dir, f"conversation_round_{round_no}.json") |
| 438 | msg_thread.save_to_file(conversation_file) |
| 439 | return True |
| 440 | |
| 441 | |
| 442 | def run_one_task( |
| 443 | output_dir: str, |
| 444 | api_manager: ProjectApiManager, |
| 445 | problem_stmt: str, |
| 446 | print_callback: Callable[[dict], None] | None = None, |
| 447 | ) -> bool: |
| 448 | """ |
| 449 | Main entry point to run inference on one task. |
| 450 | Args: |
| 451 | output_dir (str): Path to the output directory. |
| 452 | api_manager (ProjectApiManager): The already-initialized API manager. |
| 453 | problem_stmt (str): The original problem statement submitted to the task issue. |
| 454 | """ |
| 455 | print_banner("Starting AutoCodeRover on the following issue") |
| 456 | print_issue(problem_stmt) |
| 457 | msg_thread = MessageThread() |
| 458 | |
| 459 | system_prompt = SYSTEM_PROMPT |
| 460 | if (not globals.enable_layered) and common.SELECTED_MODEL.parallel_tool_call: |
| 461 | # these models support parallel tool calls, let's try to make them not do it |
| 462 | system_prompt += " In your response, DO NOT make more than one tool call." |
| 463 | |
| 464 | msg_thread.add_system(system_prompt) |
| 465 | original_prompt = prepare_issue_prompt(problem_stmt) |
| 466 | msg_thread.add_user(original_prompt) |
| 467 | |
| 468 | # Add another user message about fault localization |
| 469 | if globals.enable_sbfl: |
| 470 | localization_result, _, _ = api_manager.fault_localization() |
| 471 | localization_prompt = "An external analysis tool has been deployed to identify the suspicious code to be fixed. You can choose to use the results from this tool, if you think they are useful." |
| 472 | localization_prompt += "The tool output is as follows:\n" |
| 473 | localization_prompt += localization_result |
| 474 | msg_thread.add_user(localization_prompt) |
| 475 | |
| 476 | if globals.enable_layered: |
| 477 | return start_conversation_round_stratified( |
| 478 | output_dir, msg_thread, api_manager, print_callback=print_callback |
| 479 | ) |
| 480 | else: |
| 481 | return start_conversation_round_state_machine( |
| 482 | output_dir, msg_thread, api_manager |
| 483 | ) |
| 484 | |
| 485 | |
| 486 | # NOTE: deprecated |
| 487 | def continue_task_from_cache( |
| 488 | cache_path: str, output_dir: str, api_manager: ProjectApiManager |
| 489 | ) -> bool: |
| 490 | """ |
| 491 | Run inference on one task, but load conversation history from cache. |
| 492 | Args: |
| 493 | cache_path (str): Path to the old conversation history file. |
| 494 | output_dir (str): Path to the output directory. |
| 495 | api_manager (ProjectApiManager): The already-initialized API manager. |
| 496 | """ |
| 497 | # (1) load the existing message thread |
| 498 | msg_thread = MessageThread.load_from_file(cache_path) |
| 499 | completed_round_no = msg_thread.get_round_number() |
| 500 | |
| 501 | # (2) start the actual workflow |
| 502 | return start_conversation_round_state_machine( |
| 503 | output_dir, msg_thread, api_manager, start_round_no=completed_round_no |
| 504 | ) |