| 1 | import json |
| 2 | import os |
| 3 | import shutil |
| 4 | from collections.abc import Callable, Mapping |
| 5 | from copy import deepcopy |
| 6 | from os.path import join as pjoin |
| 7 | from pathlib import Path |
| 8 | |
| 9 | from docstring_parser import parse |
| 10 | from loguru import logger |
| 11 | |
| 12 | from app import log |
| 13 | from app.analysis import sbfl |
| 14 | from app.analysis.sbfl import NoCoverageData |
| 15 | from app.api import agent_proxy, agent_write_locations, agent_write_patch |
| 16 | from app.data_structures import FunctionCallIntent, MessageThread |
| 17 | from app.log import log_exception |
| 18 | from app.search.search_manage import SearchManager |
| 19 | |
| 20 | # from app.api.python.validation import PythonValidator |
| 21 | from app.task import Task |
| 22 | |
| 23 | |
| 24 | class ProjectApiManager: |
| 25 | ################# State machine specific ################ |
| 26 | # NOTE: this section is for state machine; APIs in stratified mode are specified |
| 27 | # in agent_api_selector.py |
| 28 | api_functions = [ |
| 29 | "search_class", |
| 30 | "search_class_in_file", |
| 31 | "search_method", |
| 32 | "search_method_in_class", |
| 33 | "search_method_in_file", |
| 34 | "search_code", |
| 35 | "search_code_in_file", |
| 36 | "write_patch", |
| 37 | ] |
| 38 | |
| 39 | def next_tools(self) -> list[str]: |
| 40 | """ |
| 41 | Return the list of tools that should be used in the next round. |
| 42 | """ |
| 43 | search_tools = [ |
| 44 | "search_class", |
| 45 | "search_class_in_file", |
| 46 | "search_method", |
| 47 | "search_method_in_class", |
| 48 | "search_method_in_file", |
| 49 | "search_code", |
| 50 | "search_code_in_file", |
| 51 | ] |
| 52 | all_tools = search_tools + ["write_patch"] |
| 53 | if not self.curr_tool: |
| 54 | # this means we are at the beginning of the conversation |
| 55 | # you have to start from doing some search |
| 56 | return search_tools |
| 57 | |
| 58 | state_machine = { |
| 59 | "search_class": search_tools, |
| 60 | "search_class_in_file": search_tools, |
| 61 | "search_method": all_tools, |
| 62 | "search_method_in_class": all_tools, |
| 63 | "search_method_in_file": all_tools, |
| 64 | "search_code": all_tools, |
| 65 | "search_code_in_file": all_tools, |
| 66 | "write_patch": [], |
| 67 | } |
| 68 | return state_machine[self.curr_tool] |
| 69 | |
| 70 | def __init__(self, task: Task, output_dir: str): |
| 71 | # for logging of this task instance |
| 72 | self.task = task |
| 73 | |
| 74 | # where to write our output |
| 75 | self.output_dir = os.path.abspath(output_dir) |
| 76 | |
| 77 | self.task.setup_project() |
| 78 | # self.setup_project(self.task) |
| 79 | |
| 80 | # build search manager |
| 81 | self.search_manager = SearchManager(self.task.project_path) |
| 82 | |
| 83 | # keeps track which tools is currently being used |
| 84 | self.curr_tool: str | None = None |
| 85 | |
| 86 | # record the sequence of tools used, and their return status |
| 87 | self.tool_call_sequence: list[Mapping] = [] |
| 88 | |
| 89 | # record layered API calls |
| 90 | self.tool_call_layers: list[list[Mapping]] = [] |
| 91 | |
| 92 | # record cost and token information |
| 93 | self.cost: float = 0.0 |
| 94 | self.input_tokens: int = 0 |
| 95 | self.output_tokens: int = 0 |
| 96 | |
| 97 | @classmethod |
| 98 | def get_short_func_summary_for_openai(cls) -> str: |
| 99 | """ |
| 100 | Get a short summary of all tool functions. |
| 101 | Intended to be used for constructing the initial system prompt. |
| 102 | """ |
| 103 | summary = "" |
| 104 | for fname in cls.api_functions: |
| 105 | if not hasattr(cls, fname): |
| 106 | continue |
| 107 | func_obj = getattr(cls, fname) |
| 108 | doc = parse(func_obj.__doc__) |
| 109 | short_desc = ( |
| 110 | doc.short_description if doc.short_description is not None else "" |
| 111 | ) |
| 112 | summary += f"\n- {fname}: {short_desc}" |
| 113 | return summary |
| 114 | |
| 115 | @classmethod |
| 116 | def get_full_funcs_for_openai(cls, tool_list: list[str]) -> list[dict]: |
| 117 | """ |
| 118 | Return a list of function objects which can be sent to OpenAI for |
| 119 | the function calling feature. |
| 120 | |
| 121 | Args: |
| 122 | tool_list (List[str]): The available tools to generate doc for. |
| 123 | """ |
| 124 | tool_template = { |
| 125 | "type": "function", |
| 126 | "function": { |
| 127 | "name": "", |
| 128 | "description": "", |
| 129 | "parameters": { |
| 130 | "type": "object", |
| 131 | "properties": {}, # mapping from para name to type+description |
| 132 | "required": [], # name of required parameters |
| 133 | }, |
| 134 | }, |
| 135 | } |
| 136 | all_tool_objs = [] |
| 137 | |
| 138 | for fname in tool_list: |
| 139 | if not hasattr(cls, fname): |
| 140 | continue |
| 141 | tool_obj = deepcopy(tool_template) |
| 142 | tool_obj["function"]["name"] = fname |
| 143 | func_obj = getattr(cls, fname) |
| 144 | # UPDATE: we only parse docstring now |
| 145 | # there are two sources of information: |
| 146 | # 1. the docstring |
| 147 | # 2. the function signature |
| 148 | # Docstring is where we get most of the textual descriptions; for accurate |
| 149 | # info about parameters (whether optional), we check signature. |
| 150 | |
| 151 | ## parse docstring |
| 152 | doc = parse(func_obj.__doc__) |
| 153 | short_desc = ( |
| 154 | doc.short_description if doc.short_description is not None else "" |
| 155 | ) |
| 156 | long_desc = doc.long_description if doc.long_description is not None else "" |
| 157 | description = short_desc + "\n" + long_desc |
| 158 | tool_obj["function"]["description"] = description |
| 159 | doc_params = doc.params |
| 160 | for doc_param in doc_params: |
| 161 | param_name = doc_param.arg_name |
| 162 | if param_name == "self": |
| 163 | continue |
| 164 | typ = doc_param.type_name |
| 165 | desc = doc_param.description |
| 166 | is_optional = doc_param.is_optional |
| 167 | # now add this param to the tool object |
| 168 | tool_obj["function"]["parameters"]["properties"][param_name] = { |
| 169 | "type": typ, |
| 170 | "description": desc, |
| 171 | } |
| 172 | if not is_optional: |
| 173 | tool_obj["function"]["parameters"]["required"].append(param_name) |
| 174 | |
| 175 | all_tool_objs.append(tool_obj) |
| 176 | |
| 177 | return all_tool_objs |
| 178 | |
| 179 | def dispatch_intent( |
| 180 | self, |
| 181 | intent: FunctionCallIntent, |
| 182 | message_thread: MessageThread, |
| 183 | print_callback: Callable[[dict], None] | None = None, |
| 184 | ) -> tuple[str, str, bool]: |
| 185 | """Dispatch a function call intent to actually perform its action. |
| 186 | |
| 187 | Args: |
| 188 | intent (FunctionCallIntent): The intent to dispatch. |
| 189 | message_thread (MessageThread): the current message thread, |
| 190 | since some tools require it. |
| 191 | Returns: |
| 192 | The result of the action. |
| 193 | Also a summary that should be communicated to the model. |
| 194 | """ |
| 195 | if (intent.func_name not in self.api_functions) and ( |
| 196 | intent.func_name not in ["get_class_full_snippet", "propose_locs"] |
| 197 | ): |
| 198 | error = f"Unknown function name {intent.func_name}." |
| 199 | summary = "You called a tool that does not exist. Please only use the tools provided." |
| 200 | return error, summary, False |
| 201 | func_obj = getattr(self, intent.func_name) |
| 202 | try: |
| 203 | # ready to call a function |
| 204 | self.curr_tool = intent.func_name |
| 205 | if intent.func_name in ["write_patch", "propose_locs"]: |
| 206 | # these two functions require the message thread |
| 207 | call_res = func_obj(message_thread, print_callback=print_callback) |
| 208 | else: |
| 209 | call_res = func_obj(**intent.arg_values) |
| 210 | except Exception as e: |
| 211 | # TypeError can happen when the function is called with wrong parameters |
| 212 | # we just return the error message as the call result |
| 213 | log_exception(e) |
| 214 | error = str(e) |
| 215 | summary = "The tool returned error message." |
| 216 | call_res = (error, summary, False) |
| 217 | |
| 218 | logger.debug("Result of dispatch_intent: {}", call_res) |
| 219 | |
| 220 | # record this call and its result separately |
| 221 | _, _, call_is_ok = call_res |
| 222 | self.tool_call_sequence.append(intent.to_dict_with_result(call_is_ok)) |
| 223 | |
| 224 | if not self.tool_call_layers: |
| 225 | self.tool_call_layers.append([]) |
| 226 | self.tool_call_layers[-1].append(intent.to_dict_with_result(call_is_ok)) |
| 227 | |
| 228 | return call_res |
| 229 | |
| 230 | def start_new_tool_call_layer(self): |
| 231 | self.tool_call_layers.append([]) |
| 232 | |
| 233 | def dump_tool_call_sequence_to_file(self): |
| 234 | """Dump the sequence of tool calls to a file.""" |
| 235 | tool_call_file = pjoin(self.output_dir, "tool_call_sequence.json") |
| 236 | with open(tool_call_file, "w") as f: |
| 237 | json.dump(self.tool_call_sequence, f, indent=4) |
| 238 | |
| 239 | def dump_tool_call_layers_to_file(self): |
| 240 | """Dump the layers of tool calls to a file.""" |
| 241 | tool_call_file = pjoin(self.output_dir, "tool_call_layers.json") |
| 242 | with open(tool_call_file, "w") as f: |
| 243 | json.dump(self.tool_call_layers, f, indent=4) |
| 244 | |
| 245 | ################################################################### |
| 246 | ########################## API functions ########################## |
| 247 | ################################################################### |
| 248 | |
| 249 | def fault_localization(self) -> tuple[str, str, bool]: |
| 250 | """Localize the faulty code snippets by executing test cases. |
| 251 | |
| 252 | Perform fault localization by running the passing and failing test-cases. |
| 253 | Returns a list of code snippets that are likely to be related to the issue. |
| 254 | """ |
| 255 | sbfl_result_file = Path(self.output_dir, "sbfl_result.json") |
| 256 | sbfl_method_result_file = Path(self.output_dir, "sbfl_result_method.json") |
| 257 | |
| 258 | log_file = None |
| 259 | try: |
| 260 | test_file_names, ranked_lines, log_file = sbfl.run(self.task) |
| 261 | except NoCoverageData as e: |
| 262 | sbfl_result_file.write_text("") |
| 263 | sbfl_method_result_file.write_text("") |
| 264 | |
| 265 | log_file = e.testing_log_file |
| 266 | |
| 267 | tool_output = "Error in running localization tool" |
| 268 | summary = tool_output |
| 269 | return tool_output, summary, False |
| 270 | finally: |
| 271 | if log_file is not None: |
| 272 | shutil.move(log_file, pjoin(self.output_dir, "run_developer_tests.log")) |
| 273 | |
| 274 | ranked_ranges_abs = sbfl.collate_results(ranked_lines, test_file_names) |
| 275 | ranked_methods_abs = sbfl.map_collated_results_to_methods(ranked_ranges_abs) |
| 276 | |
| 277 | def relativize_filename(tup: tuple) -> tuple: |
| 278 | file = tup[0] |
| 279 | relative_file = os.path.relpath(file, self.task.project_path) |
| 280 | return (relative_file,) + tup[1:] |
| 281 | |
| 282 | ranked_ranges = [relativize_filename(t) for t in ranked_ranges_abs] |
| 283 | ranked_methods = [relativize_filename(t) for t in ranked_methods_abs] |
| 284 | |
| 285 | sbfl_result_file.write_text(json.dumps(ranked_ranges, indent=4)) |
| 286 | |
| 287 | sbfl_method_result_file.write_text(json.dumps(ranked_methods, indent=4)) |
| 288 | |
| 289 | log.log_and_print(f"SBFL result (lines): {ranked_ranges}") |
| 290 | log.log_and_print(f"SBFL result (methods): {ranked_methods}") |
| 291 | |
| 292 | return self._form_sbfl_output(ranked_methods) |
| 293 | |
| 294 | @classmethod |
| 295 | def _form_sbfl_output(cls, ranked_methods) -> tuple[str, str, bool]: |
| 296 | if not ranked_methods: |
| 297 | # empty sbfl results |
| 298 | tool_output = "Localization could not produce any output." |
| 299 | summary = tool_output |
| 300 | return tool_output, summary, False |
| 301 | |
| 302 | if len(ranked_methods) > 5: |
| 303 | ranked_methods = ranked_methods[:5] |
| 304 | |
| 305 | tool_output = f"Top-{len(ranked_methods)} suspicious methods:\n" |
| 306 | for idx, (file, class_name, method_name, _) in enumerate(ranked_methods): |
| 307 | |
| 308 | res_str = f"<file>{file}</file>" |
| 309 | if class_name: |
| 310 | res_str += f" <class>{class_name}</class>" |
| 311 | if method_name: |
| 312 | res_str += f" <func>{method_name}</func>" |
| 313 | |
| 314 | tool_output += f"Suspicious method #{idx + 1}:\n{res_str}\n\n" |
| 315 | |
| 316 | summary = f"Returned top-{len(ranked_methods)} suspicious methods." |
| 317 | |
| 318 | return tool_output, summary, True |
| 319 | |
| 320 | # not a search API - just to get full class definition when bug_location only specifies a class |
| 321 | def get_class_full_snippet(self, class_name: str): |
| 322 | return self.search_manager.get_class_full_snippet(class_name) |
| 323 | |
| 324 | def search_class(self, class_name: str) -> tuple[str, str, bool]: |
| 325 | """Search for a class in the codebase. |
| 326 | |
| 327 | Only the signature of the class is returned. The class signature |
| 328 | includes class name, base classes, and signatures for all of its methods/properties. |
| 329 | |
| 330 | Args: |
| 331 | class_name (string): Name of the class to search for. |
| 332 | |
| 333 | Returns: |
| 334 | string: the class signature in string if success; |
| 335 | an error message if the class cannot be found. |
| 336 | string: a message summarizing the method. |
| 337 | """ |
| 338 | return self.search_manager.search_class(class_name) |
| 339 | |
| 340 | def search_class_in_file( |
| 341 | self, class_name: str, file_name: str |
| 342 | ) -> tuple[str, str, bool]: |
| 343 | """Search for a class in a given file. |
| 344 | |
| 345 | Returns the actual code of the entire class definition. |
| 346 | |
| 347 | Args: |
| 348 | class_name (string): Name of the class to search for. |
| 349 | file_name (string): The file to search in. Must be a valid python file name. |
| 350 | |
| 351 | Returns: |
| 352 | part 1 - the searched class code or error message. |
| 353 | part 2 - summary of the tool call. |
| 354 | """ |
| 355 | return self.search_manager.search_class_in_file(class_name, file_name) |
| 356 | |
| 357 | def search_method_in_file( |
| 358 | self, method_name: str, file_name: str |
| 359 | ) -> tuple[str, str, bool]: |
| 360 | """Search for a method in a given file. |
| 361 | |
| 362 | Returns the actual code of the method. |
| 363 | |
| 364 | Args: |
| 365 | method_name (string): Name of the method to search for. |
| 366 | file_name (string): The file to search in. Must be a valid python file name. |
| 367 | |
| 368 | Returns: |
| 369 | part 1 - the searched code or error message. |
| 370 | part 2 - summary of the tool call. |
| 371 | """ |
| 372 | return self.search_manager.search_method_in_file(method_name, file_name) |
| 373 | |
| 374 | def search_method_in_class( |
| 375 | self, method_name: str, class_name: str |
| 376 | ) -> tuple[str, str, bool]: |
| 377 | """Search for a method in a given class. |
| 378 | |
| 379 | Returns the actual code of the method. |
| 380 | |
| 381 | Args: |
| 382 | method_name (string): Name of the method to search for. |
| 383 | class_name (string): Consider only methods in this class. |
| 384 | |
| 385 | Returns: |
| 386 | part 1 - the searched code or error message. |
| 387 | part 2 - summary of the tool call. |
| 388 | """ |
| 389 | return self.search_manager.search_method_in_class(method_name, class_name) |
| 390 | |
| 391 | def search_method(self, method_name: str) -> tuple[str, str, bool]: |
| 392 | """Search for a method in the entire codebase. |
| 393 | |
| 394 | Returns the actual code of the method. |
| 395 | |
| 396 | Args: |
| 397 | method_name (string): Name of the method to search for. |
| 398 | |
| 399 | Returns: |
| 400 | part 1 - the searched code or error message. |
| 401 | part 2 - summary of the tool call. |
| 402 | """ |
| 403 | return self.search_manager.search_method(method_name) |
| 404 | |
| 405 | def search_code(self, code_str: str) -> tuple[str, str, bool]: |
| 406 | """Search for a code snippet in the entire codebase. |
| 407 | |
| 408 | Returns the method that contains the code snippet, if it is found inside a file. |
| 409 | Otherwise, returns the region of code surrounding it. |
| 410 | |
| 411 | Args: |
| 412 | code_str (string): The code snippet to search for. |
| 413 | |
| 414 | Returns: |
| 415 | The region of code containing the searched code string. |
| 416 | """ |
| 417 | return self.search_manager.search_code(code_str) |
| 418 | |
| 419 | def search_code_in_file( |
| 420 | self, code_str: str, file_name: str |
| 421 | ) -> tuple[str, str, bool]: |
| 422 | """Search for a code snippet in a given file file. |
| 423 | |
| 424 | Returns the entire method that contains the code snippet. |
| 425 | |
| 426 | Args: |
| 427 | code_str (string): The code snippet to search for. |
| 428 | file_name (string): The file to search in. Must be a valid python file name in the project. |
| 429 | |
| 430 | Returns: |
| 431 | The method code that contains the searched code string. |
| 432 | """ |
| 433 | return self.search_manager.search_code_in_file(code_str, file_name) |
| 434 | |
| 435 | def write_patch( |
| 436 | self, |
| 437 | message_thread: MessageThread, |
| 438 | print_callback: Callable[[dict], None] | None = None, |
| 439 | ) -> tuple[str, str, bool]: |
| 440 | """Based on the current context, ask another agent to write a patch. |
| 441 | |
| 442 | When you think the current information is sufficient to write a patch, invoke this tool. |
| 443 | |
| 444 | The tool returns a patch based on the current available information. |
| 445 | """ |
| 446 | tool_output = agent_write_patch.run_with_retries( |
| 447 | message_thread, |
| 448 | self.output_dir, |
| 449 | self.task, |
| 450 | # self.validator, |
| 451 | print_callback=print_callback, |
| 452 | ) |
| 453 | summary = "The tool returned the patch written by another agent." |
| 454 | # The return status of write_patch does not really matter, so we just use True here |
| 455 | return tool_output, summary, True |
| 456 | |
| 457 | def propose_locs( |
| 458 | self, |
| 459 | message_thread: MessageThread, |
| 460 | print_callback: Callable[[dict], None] | None = None, |
| 461 | ) -> tuple[str, str, bool]: |
| 462 | """Propose locations for fixing the bug. |
| 463 | |
| 464 | Based on the current context, ask another agent to propose locations for fixing the bug. |
| 465 | |
| 466 | The tool returns a list of locations that are likely to be related to the issue. |
| 467 | """ |
| 468 | tool_output = agent_write_locations.run_with_retries( |
| 469 | message_thread, |
| 470 | self.output_dir, |
| 471 | self.task, |
| 472 | # self.validator, |
| 473 | print_callback=print_callback, |
| 474 | ) |
| 475 | summary = "The tool returned the locations proposed by another agent." |
| 476 | # The return status of propose_locs does not really matter, so we just use True here |
| 477 | return tool_output, summary, True |
| 478 | |
| 479 | def proxy_apis(self, text: str) -> tuple[str | None, str, list[MessageThread]]: |
| 480 | """Proxy APIs to another agent.""" |
| 481 | tool_output, new_thread = agent_proxy.run_with_retries( |
| 482 | text |
| 483 | ) # FIXME: type of `text` |
| 484 | if tool_output is None: |
| 485 | summary = "The tool returned nothing. The main agent probably did not provide enough clues." |
| 486 | else: |
| 487 | summary = "The tool returned the selected search APIs in json format generaetd by another agent." |
| 488 | return tool_output, summary, new_thread |