Elffuss BraidHub

kikocis/auto-code-rover public

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