| 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 | for round_no in range(start_round_no, globals.conv_round_limit + 1): |
| 97 | api_manager.start_new_tool_call_layer() |
| 98 | |
| 99 | conversation_file = pjoin(output_dir, f"conversation_round_{round_no}.json") |
| 100 | # save current state before starting a new round |
| 101 | msg_thread.save_to_file(conversation_file) |
| 102 | |
| 103 | print_banner(f"CONTEXT RETRIEVAL ROUND {round_no}") |
| 104 | |
| 105 | print_acr( |
| 106 | prompt, |
| 107 | f"context retrieval round {start_round_no}", |
| 108 | print_callback=print_callback, |
| 109 | ) |
| 110 | |
| 111 | res_text, *_ = common.SELECTED_MODEL.call(msg_thread.to_msg()) |
| 112 | msg_thread.add_model(res_text, tools=[]) |
| 113 | print_retrieval(res_text, f"round {round_no}", print_callback=print_callback) |
| 114 | |
| 115 | selected_apis, _, proxy_threads = api_manager.proxy_apis(res_text) |
| 116 | |
| 117 | proxy_log = Path(output_dir, f"agent_proxy_{round_no}.json") |
| 118 | proxy_messages = [thread.to_msg() for thread in proxy_threads] |
| 119 | proxy_log.write_text(json.dumps(proxy_messages, indent=4)) |
| 120 | |
| 121 | if selected_apis is None: |
| 122 | msg = "The search API calls seem not valid. Please check the arguments you give carefully and try again." |
| 123 | msg_thread.add_user(msg) |
| 124 | print_acr( |
| 125 | msg, |
| 126 | f"context retrieval round {round_no}", |
| 127 | print_callback=print_callback, |
| 128 | ) |
| 129 | continue |
| 130 | |
| 131 | selected_apis_json = json.loads(selected_apis) |
| 132 | |
| 133 | json_api_calls = selected_apis_json.get("API_calls", []) |
| 134 | buggy_locations = selected_apis_json.get("bug_locations", []) |
| 135 | |
| 136 | formatted = [] |
| 137 | if json_api_calls: |
| 138 | formatted.append("API calls:") |
| 139 | for call in json_api_calls: |
| 140 | formatted.extend([f"\n- `{call}`"]) |
| 141 | |
| 142 | if buggy_locations: |
| 143 | formatted.append("\n\nBug locations") |
| 144 | for location in buggy_locations: |
| 145 | s = ", ".join(f"{k}: `{v}`" for k, v in location.items()) |
| 146 | formatted.extend([f"\n- {s}"]) |
| 147 | |
| 148 | print_acr( |
| 149 | "\n".join(formatted), |
| 150 | "Agent-selected API calls", |
| 151 | print_callback=print_callback, |
| 152 | ) |
| 153 | |
| 154 | # collected enough information to write patch |
| 155 | if buggy_locations and (not json_api_calls): |
| 156 | collated_tool_response = "Here is the code in buggy locations:\n\n" |
| 157 | # provide the buggy locations to the model |
| 158 | for bug_location in buggy_locations: |
| 159 | tool_output, *_ = search_for_bug_location( |
| 160 | api_manager, msg_thread, bug_location |
| 161 | ) |
| 162 | collated_tool_response += f"\n\n{tool_output}\n" |
| 163 | |
| 164 | if ( |
| 165 | "Unknown function" not in collated_tool_response |
| 166 | and "Could not" not in collated_tool_response |
| 167 | ): |
| 168 | msg_thread.add_user(collated_tool_response) |
| 169 | |
| 170 | print_banner("PATCH GENERATION") |
| 171 | logger.debug("Gathered enough information. Invoking write_patch.") |
| 172 | print_acr( |
| 173 | collated_tool_response, |
| 174 | "patch generation round 1", |
| 175 | print_callback=print_callback, |
| 176 | ) |
| 177 | break |
| 178 | |
| 179 | msg = "The buggy locations is not precise. You may need to check whether the arguments are correct and search more information." |
| 180 | msg_thread.add_user(msg) |
| 181 | print_acr( |
| 182 | msg, |
| 183 | f"context retrieval round {round_no}", |
| 184 | print_callback=print_callback, |
| 185 | ) |
| 186 | continue |
| 187 | |
| 188 | # prepare response from tools |
| 189 | collated_tool_response = "" |
| 190 | |
| 191 | for api_call in json_api_calls: |
| 192 | func_name, func_args = parse_function_invocation(api_call) |
| 193 | |
| 194 | arg_spec = inspect.getfullargspec(getattr(SearchManager, func_name)) |
| 195 | arg_names = arg_spec.args[1:] # first parameter is self |
| 196 | |
| 197 | assert len(func_args) == len( |
| 198 | arg_names |
| 199 | ), f"Number of argument is wrong in API call: {api_call}" |
| 200 | |
| 201 | kwargs = dict(zip(arg_names, func_args)) |
| 202 | intent = FunctionCallIntent(func_name, kwargs, None) |
| 203 | tool_output, _, _ = api_manager.dispatch_intent(intent, msg_thread) |
| 204 | |
| 205 | collated_tool_response += f"Result of {api_call}:\n\n" |
| 206 | collated_tool_response += tool_output + "\n\n" |
| 207 | |
| 208 | msg_thread.add_user(collated_tool_response) |
| 209 | print_acr( |
| 210 | collated_tool_response, |
| 211 | f"context retrieval round {round_no}", |
| 212 | print_callback=print_callback, |
| 213 | ) |
| 214 | |
| 215 | msg = "Let's analyze collected context first" |
| 216 | msg_thread.add_user(msg) |
| 217 | print_acr( |
| 218 | msg, f"context retrieval round {round_no}", print_callback=print_callback |
| 219 | ) |
| 220 | |
| 221 | res_text, *_ = common.SELECTED_MODEL.call(msg_thread.to_msg()) |
| 222 | msg_thread.add_model(res_text, tools=[]) |
| 223 | print_retrieval(res_text, f"round {round_no}", print_callback=print_callback) |
| 224 | |
| 225 | if round_no < globals.conv_round_limit: |
| 226 | msg = ( |
| 227 | "Based on your analysis, answer below questions:" |
| 228 | "\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)" |
| 229 | "\n- where are bug locations: buggy files and methods. (leave it empty if you don't have enough information)" |
| 230 | ) |
| 231 | if isinstance(common.SELECTED_MODEL, ollama.OllamaModel): |
| 232 | # llama models tend to always output search APIs and buggy locations. |
| 233 | msg += "\n\nNOTE: If you have already identified the bug locations, do not make any search API calls." |
| 234 | msg_thread.add_user(msg) |
| 235 | print_acr( |
| 236 | msg, |
| 237 | f"context retrieval round {round_no}", |
| 238 | print_callback=print_callback, |
| 239 | ) |
| 240 | else: |
| 241 | logger.info("Too many rounds. Try writing patch anyway.") |
| 242 | |
| 243 | round_no += 1 |
| 244 | |
| 245 | api_manager.start_new_tool_call_layer() |
| 246 | |
| 247 | write_patch_intent = FunctionCallIntent("write_patch", {}, None) |
| 248 | api_manager.dispatch_intent( |
| 249 | write_patch_intent, msg_thread, print_callback=print_callback |
| 250 | ) |
| 251 | |
| 252 | conversation_file = pjoin(output_dir, f"conversation_round_{round_no}.json") |
| 253 | msg_thread.save_to_file(conversation_file) |
| 254 | |
| 255 | logger.info("Invoked write_patch. Ending workflow.") |
| 256 | |
| 257 | return True |
| 258 | |
| 259 | |
| 260 | def search_for_bug_location( |
| 261 | api_manager: ProjectApiManager, |
| 262 | msg_thread: MessageThread, |
| 263 | bug_location: dict[str, str], |
| 264 | ) -> tuple[str, str, bool]: |
| 265 | found = False |
| 266 | |
| 267 | file_name = bug_location.get("file") |
| 268 | method_name = bug_location.get("method") |
| 269 | class_name = bug_location.get("class") |
| 270 | |
| 271 | assert method_name or class_name, f"Invalid bug location: {bug_location}" |
| 272 | |
| 273 | call_result = None |
| 274 | |
| 275 | def call_function(func_name: str, kwargs: dict[str, str]) -> None: |
| 276 | nonlocal found, call_result |
| 277 | |
| 278 | intent = FunctionCallIntent(func_name, kwargs, None) |
| 279 | call_result = api_manager.dispatch_intent(intent, msg_thread) |
| 280 | _, _, call_is_ok = call_result |
| 281 | found |= call_is_ok |
| 282 | |
| 283 | if (not found) and method_name and class_name: |
| 284 | kwargs = {"method_name": method_name, "class_name": class_name} |
| 285 | call_function("search_method_in_class", kwargs) |
| 286 | |
| 287 | if (not found) and method_name and file_name: |
| 288 | kwargs = {"method_name": method_name, "file_name": file_name} |
| 289 | call_function("search_method_in_file", kwargs) |
| 290 | |
| 291 | if (not found) and class_name and file_name: |
| 292 | kwargs = {"class_name": class_name, "file_name": file_name} |
| 293 | call_function("search_class_in_file", kwargs) |
| 294 | |
| 295 | if (not found) and class_name: |
| 296 | kwargs = {"class_name": class_name} |
| 297 | call_function("get_class_full_snippet", kwargs) |
| 298 | |
| 299 | if (not found) and method_name: |
| 300 | kwargs = {"method_name": method_name} |
| 301 | call_function("search_method", kwargs) |
| 302 | |
| 303 | assert call_result |
| 304 | |
| 305 | return call_result |
| 306 | |
| 307 | |
| 308 | def dump_tool_call_layers_to_file( |
| 309 | tool_call_layers: list[dict], output_dir: str |
| 310 | ) -> None: |
| 311 | """Dump the layers of tool calls to a file.""" |
| 312 | tool_call_file = pjoin(output_dir, "tool_call_layers.json") |
| 313 | with open(tool_call_file, "w") as f: |
| 314 | json.dump(tool_call_layers, f, indent=4) |
| 315 | |
| 316 | |
| 317 | def start_conversation_round_state_machine( |
| 318 | output_dir: str, |
| 319 | msg_thread: MessageThread, |
| 320 | api_manager: ProjectApiManager, |
| 321 | start_round_no: int = 0, |
| 322 | ) -> bool: |
| 323 | """ |
| 324 | Start the actual rounds of conversations with model. |
| 325 | |
| 326 | Args: |
| 327 | output_dir (str): Path to the output directory. |
| 328 | msg_thread (MessageThread): The message thread to be used. |
| 329 | api_manager (ProjectApiManager): The API manager to be used. |
| 330 | start_round_no (int): The round number to start with. |
| 331 | """ |
| 332 | round_no = start_round_no |
| 333 | for round_no in range(start_round_no, globals.conv_round_limit + 1): |
| 334 | conversation_file = pjoin(output_dir, f"conversation_round_{round_no}.json") |
| 335 | # save current state before starting a new round |
| 336 | msg_thread.save_to_file(conversation_file) |
| 337 | log_and_cprint( |
| 338 | f"\n========== Conversation Round {round_no} ==========", style="red bold" |
| 339 | ) |
| 340 | log_and_print(f"{colored('Current message thread:', 'green')}\n{msg_thread}") |
| 341 | |
| 342 | allowed_tools = api_manager.next_tools() |
| 343 | # TODO: configure the list of tools based on state machine |
| 344 | tools = ProjectApiManager.get_full_funcs_for_openai(allowed_tools) |
| 345 | |
| 346 | log_and_cprint(f"Current tool state: {api_manager.curr_tool}", style="yellow") |
| 347 | log_and_cprint(f"Allowed next tool states: {allowed_tools}", style="yellow") |
| 348 | |
| 349 | # create a new iteration of conversation |
| 350 | res_text, raw_tool_calls, func_call_intents, *_ = common.SELECTED_MODEL.call( |
| 351 | msg_thread.to_msg(), tools=tools |
| 352 | ) |
| 353 | log_and_print( |
| 354 | f"{colored('This roud model response (text):', 'blue')} {res_text}" |
| 355 | ) |
| 356 | # model can decide whether to create a function call |
| 357 | if len(func_call_intents) == 1: |
| 358 | # good case in which we can check function call |
| 359 | func_call_intent: FunctionCallIntent = func_call_intents[0] |
| 360 | log_and_print( |
| 361 | f"{colored('This round model response (function call):', 'blue')} {func_call_intent}" |
| 362 | ) |
| 363 | # dispatch this function call |
| 364 | this_model_response = res_text |
| 365 | this_model_tools = raw_tool_calls |
| 366 | # add previous call information to user message |
| 367 | tool_output, summary, _ = api_manager.dispatch_intent( |
| 368 | func_call_intent, msg_thread |
| 369 | ) |
| 370 | else: |
| 371 | # no function call, let's force the model to make one |
| 372 | this_model_tools = [] |
| 373 | this_model_response = res_text |
| 374 | tool_output = "" |
| 375 | summary = "There is no function call in your previous response. Make sure you include one function call. " |
| 376 | |
| 377 | next_user_message = add_step_trigger(summary) |
| 378 | |
| 379 | # form message thread for next round. should include what the model said as well |
| 380 | msg_thread.add_model(this_model_response, this_model_tools) |
| 381 | if this_model_tools: |
| 382 | tool_call_id = this_model_tools[0].id |
| 383 | msg_thread.add_tool(tool_output, tool_call_id) |
| 384 | msg_thread.add_user(next_user_message) |
| 385 | else: |
| 386 | msg_thread.add_user(next_user_message) |
| 387 | |
| 388 | if len(func_call_intents) == 1: |
| 389 | func_call_name = func_call_intents[0].func_name |
| 390 | if func_call_name == "write_patch": |
| 391 | log_and_print("Ending workflow. write_patch has been invoked.") |
| 392 | break |
| 393 | |
| 394 | log_and_print("Going to next round ..........") |
| 395 | else: |
| 396 | log_and_print("Too many rounds. Try writing patch anyway.") |
| 397 | write_patch_intent = FunctionCallIntent("write_patch", {}, None) |
| 398 | api_manager.dispatch_intent(write_patch_intent, msg_thread) |
| 399 | |
| 400 | round_no += 1 |
| 401 | |
| 402 | # if we end the workflow normally, there is one more round of conversation to store |
| 403 | conversation_file = pjoin(output_dir, f"conversation_round_{round_no}.json") |
| 404 | msg_thread.save_to_file(conversation_file) |
| 405 | return True |
| 406 | |
| 407 | |
| 408 | def run_one_task( |
| 409 | output_dir: str, |
| 410 | api_manager: ProjectApiManager, |
| 411 | problem_stmt: str, |
| 412 | print_callback: Callable[[dict], None] | None = None, |
| 413 | ) -> bool: |
| 414 | """ |
| 415 | Main entry point to run inference on one task. |
| 416 | Args: |
| 417 | output_dir (str): Path to the output directory. |
| 418 | api_manager (ProjectApiManager): The already-initialized API manager. |
| 419 | problem_stmt (str): The original problem statement submitted to the task issue. |
| 420 | """ |
| 421 | print_banner("Starting AutoCodeRover on the following issue") |
| 422 | print_issue(problem_stmt) |
| 423 | msg_thread = MessageThread() |
| 424 | |
| 425 | system_prompt = SYSTEM_PROMPT |
| 426 | if (not globals.enable_layered) and common.SELECTED_MODEL.parallel_tool_call: |
| 427 | # these models support parallel tool calls, let's try to make them not do it |
| 428 | system_prompt += " In your response, DO NOT make more than one tool call." |
| 429 | |
| 430 | msg_thread.add_system(system_prompt) |
| 431 | original_prompt = prepare_issue_prompt(problem_stmt) |
| 432 | msg_thread.add_user(original_prompt) |
| 433 | |
| 434 | # Add another user message about fault localization |
| 435 | if globals.enable_sbfl: |
| 436 | localization_result, _, _ = api_manager.fault_localization() |
| 437 | 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." |
| 438 | localization_prompt += "The tool output is as follows:\n" |
| 439 | localization_prompt += localization_result |
| 440 | msg_thread.add_user(localization_prompt) |
| 441 | |
| 442 | if globals.enable_layered: |
| 443 | return start_conversation_round_stratified( |
| 444 | output_dir, msg_thread, api_manager, print_callback=print_callback |
| 445 | ) |
| 446 | else: |
| 447 | return start_conversation_round_state_machine( |
| 448 | output_dir, msg_thread, api_manager |
| 449 | ) |
| 450 | |
| 451 | |
| 452 | # NOTE: deprecated |
| 453 | def continue_task_from_cache( |
| 454 | cache_path: str, output_dir: str, api_manager: ProjectApiManager |
| 455 | ) -> bool: |
| 456 | """ |
| 457 | Run inference on one task, but load conversation history from cache. |
| 458 | Args: |
| 459 | cache_path (str): Path to the old conversation history file. |
| 460 | output_dir (str): Path to the output directory. |
| 461 | api_manager (ProjectApiManager): The already-initialized API manager. |
| 462 | """ |
| 463 | # (1) load the existing message thread |
| 464 | msg_thread = MessageThread.load_from_file(cache_path) |
| 465 | completed_round_no = msg_thread.get_round_number() |
| 466 | |
| 467 | # (2) start the actual workflow |
| 468 | return start_conversation_round_state_machine( |
| 469 | output_dir, msg_thread, api_manager, start_round_no=completed_round_no |
| 470 | ) |