Elffuss BraidHub

kikocis/auto-code-rover public

6ea11b99288f · 18.3 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 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
260def 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 = {
285 "method_name": method_name,
286 "class_name": class_name,
287 }
288 call_function("search_method_in_class", kwargs)
289
290 if (not found) and method_name and file_name:
291 kwargs = {
292 "method_name": method_name,
293 "file_name": file_name,
294 }
295 call_function("search_method_in_file", kwargs)
296
297 if (not found) and class_name and file_name:
298 kwargs = {
299 "class_name": class_name,
300 "file_name": file_name,
301 }
302 call_function("search_class_in_file", kwargs)
303
304 if (not found) and class_name:
305 kwargs = {"class_name": class_name}
306 call_function("get_class_full_snippet", kwargs)
307
308 if (not found) and method_name:
309 kwargs = {"method_name": method_name}
310 call_function("search_method", kwargs)
311
312 assert call_result
313
314 return call_result
315
316
317def dump_tool_call_layers_to_file(
318 tool_call_layers: list[dict], output_dir: str
319) -> None:
320 """Dump the layers of tool calls to a file."""
321 tool_call_file = pjoin(output_dir, "tool_call_layers.json")
322 with open(tool_call_file, "w") as f:
323 json.dump(tool_call_layers, f, indent=4)
324
325
326def start_conversation_round_state_machine(
327 output_dir: str,
328 msg_thread: MessageThread,
329 api_manager: ProjectApiManager,
330 start_round_no: int = 0,
331) -> bool:
332 """
333 Start the actual rounds of conversations with model.
334
335 Args:
336 output_dir (str): Path to the output directory.
337 msg_thread (MessageThread): The message thread to be used.
338 api_manager (ProjectApiManager): The API manager to be used.
339 start_round_no (int): The round number to start with.
340 """
341 round_no = start_round_no
342 for round_no in range(start_round_no, globals.conv_round_limit + 1):
343 conversation_file = pjoin(output_dir, f"conversation_round_{round_no}.json")
344 # save current state before starting a new round
345 msg_thread.save_to_file(conversation_file)
346 log_and_cprint(
347 f"\n========== Conversation Round {round_no} ==========", style="red bold"
348 )
349 log_and_print(f"{colored('Current message thread:', 'green')}\n{msg_thread}")
350
351 allowed_tools = api_manager.next_tools()
352 # TODO: configure the list of tools based on state machine
353 tools = ProjectApiManager.get_full_funcs_for_openai(allowed_tools)
354
355 log_and_cprint(f"Current tool state: {api_manager.curr_tool}", style="yellow")
356 log_and_cprint(f"Allowed next tool states: {allowed_tools}", style="yellow")
357
358 # create a new iteration of conversation
359 res_text, raw_tool_calls, func_call_intents, *_ = common.SELECTED_MODEL.call(
360 msg_thread.to_msg(), tools=tools
361 )
362 log_and_print(
363 f"{colored('This roud model response (text):', 'blue')} {res_text}"
364 )
365 # model can decide whether to create a function call
366 if len(func_call_intents) == 1:
367 # good case in which we can check function call
368 func_call_intent: FunctionCallIntent = func_call_intents[0]
369 log_and_print(
370 f"{colored('This round model response (function call):', 'blue')} {func_call_intent}",
371 )
372 # dispatch this function call
373 this_model_response = res_text
374 this_model_tools = raw_tool_calls
375 # add previous call information to user message
376 tool_output, summary, _ = api_manager.dispatch_intent(
377 func_call_intent, msg_thread
378 )
379 else:
380 # no function call, let's force the model to make one
381 this_model_tools = []
382 this_model_response = res_text
383 tool_output = ""
384 summary = "There is no function call in your previous response. Make sure you include one function call. "
385
386 next_user_message = add_step_trigger(summary)
387
388 # form message thread for next round. should include what the model said as well
389 msg_thread.add_model(this_model_response, this_model_tools)
390 if this_model_tools:
391 tool_call_id = this_model_tools[0].id
392 msg_thread.add_tool(tool_output, tool_call_id)
393 msg_thread.add_user(next_user_message)
394 else:
395 msg_thread.add_user(next_user_message)
396
397 if len(func_call_intents) == 1:
398 func_call_name = func_call_intents[0].func_name
399 if func_call_name == "write_patch":
400 log_and_print("Ending workflow. write_patch has been invoked.")
401 break
402
403 log_and_print("Going to next round ..........")
404 else:
405 log_and_print("Too many rounds. Try writing patch anyway.")
406 write_patch_intent = FunctionCallIntent("write_patch", {}, None)
407 api_manager.dispatch_intent(write_patch_intent, msg_thread)
408
409 round_no += 1
410
411 # if we end the workflow normally, there is one more round of conversation to store
412 conversation_file = pjoin(output_dir, f"conversation_round_{round_no}.json")
413 msg_thread.save_to_file(conversation_file)
414 return True
415
416
417def run_one_task(
418 output_dir: str,
419 api_manager: ProjectApiManager,
420 problem_stmt: str,
421 print_callback: Callable[[dict], None] | None = None,
422) -> bool:
423 """
424 Main entry point to run inference on one task.
425 Args:
426 output_dir (str): Path to the output directory.
427 api_manager (ProjectApiManager): The already-initialized API manager.
428 problem_stmt (str): The original problem statement submitted to the task issue.
429 """
430 print_banner("Starting AutoCodeRover on the following issue")
431 print_issue(problem_stmt)
432 msg_thread = MessageThread()
433
434 system_prompt = SYSTEM_PROMPT
435 if (not globals.enable_layered) and common.SELECTED_MODEL.parallel_tool_call:
436 # these models support parallel tool calls, let's try to make them not do it
437 system_prompt += " In your response, DO NOT make more than one tool call."
438
439 msg_thread.add_system(system_prompt)
440 original_prompt = prepare_issue_prompt(problem_stmt)
441 msg_thread.add_user(original_prompt)
442
443 # Add another user message about fault localization
444 if globals.enable_sbfl:
445 localization_result, _, _ = api_manager.fault_localization()
446 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."
447 localization_prompt += "The tool output is as follows:\n"
448 localization_prompt += localization_result
449 msg_thread.add_user(localization_prompt)
450
451 if globals.enable_layered:
452 return start_conversation_round_stratified(
453 output_dir, msg_thread, api_manager, print_callback=print_callback
454 )
455 else:
456 return start_conversation_round_state_machine(
457 output_dir, msg_thread, api_manager
458 )
459
460
461# NOTE: deprecated
462def continue_task_from_cache(
463 cache_path: str, output_dir: str, api_manager: ProjectApiManager
464) -> bool:
465 """
466 Run inference on one task, but load conversation history from cache.
467 Args:
468 cache_path (str): Path to the old conversation history file.
469 output_dir (str): Path to the output directory.
470 api_manager (ProjectApiManager): The already-initialized API manager.
471 """
472 # (1) load the existing message thread
473 msg_thread = MessageThread.load_from_file(cache_path)
474 completed_round_no = msg_thread.get_round_number()
475
476 # (2) start the actual workflow
477 return start_conversation_round_state_machine(
478 output_dir, msg_thread, api_manager, start_round_no=completed_round_no
479 )