Elffuss BraidHub

kikocis/auto-code-rover public

Add fix location proposal agent and refactor flow a little
Changeset56470e97eeb7eb45229053acb4c4e50eaf6e6a3fdf037670893bd9fabb416984
AuthorMartin Mirchev <mirchevmartin2203@gmail.com> · 2024-07-18 22:38 +08:00
CommitterMartin Mirchev <mirchevmartin2203@gmail.com> · 2024-07-18 22:38 +08:00
Parents7c421ef867a3

Browse the files at this changeset

4 files changed

added app/api/agent_write_locations.py +125 −0
@@ -0,0 +1,125 @@
1+"""
2+An agent, which is only responsible for the summarize locations tool call.
3+"""
4+
5+import json
6+import re
7+from collections.abc import Callable
8+from copy import deepcopy
9+from os.path import join as pjoin
10+from pathlib import Path
11+
12+from loguru import logger
13+
14+from app.api import agent_common
15+from app.data_structures import MessageThread
16+from app.log import print_acr, print_fix_loc_generation
17+from app.model import common
18+from app.task import Task
19+
20+SYSTEM_PROMPT = """You are a software developer maintaining a large project.
21+You are working on an issue submitted to your project.
22+The issue contains a description marked between <issue> and </issue>.
23+You ultimate goal is to write a list of locations that you can give to another devloper.
24+"""
25+
26+
27+USER_PROMPT_INIT = """Write a list of fix locations, based on the retrieved context.\n\n
28+Return the list of locations in the format below.\n\nWithin `<file></file>`, replace `...` with actual file path. Within `<class></class>`, replace `...` with a class name if needed. Within `<method></method`, replace `...` with a method name.\n\n
29+You can write multiple locations if needed.
30+
31+```
32+# candidate 1
33+<file>...</file>
34+<class>...</class>
35+<method>...</method>
36+
37+
38+# candidate 2
39+<file>...</file>
40+<class>...</class>
41+<method>...</method>
42+
43+# candidate 3
44+...
45+```
46+"""
47+
48+
49+def run_with_retries(
50+ message_thread: MessageThread,
51+ output_dir: str,
52+ task: Task,
53+ retries=3,
54+ print_callback: Callable[[dict], None] | None = None,
55+) -> tuple[str, float, int, int]:
56+ """
57+ Since the agent may not always write a correct list, we allow for retries.
58+ This is a wrapper around the actual run.
59+ """
60+ # (1) replace system prompt
61+ messages = deepcopy(message_thread.messages)
62+ new_thread: MessageThread = MessageThread(messages=messages)
63+ new_thread = agent_common.replace_system_prompt(new_thread, SYSTEM_PROMPT)
64+
65+ # (2) add the initial user prompt
66+ new_thread.add_user(USER_PROMPT_INIT)
67+ print_acr(
68+ USER_PROMPT_INIT, "fix location generation", print_callback=print_callback
69+ )
70+
71+ can_stop = False
72+ result_msg = ""
73+
74+ logger.info("Starting the agent to propose fix locations.")
75+
76+ for i in range(1, retries + 2):
77+ if i > 1:
78+ debug_file = pjoin(output_dir, f"debug_agent_propose_locs_{i - 1}.json")
79+ with open(debug_file, "w") as f:
80+ json.dump(new_thread.to_msg(), f, indent=4)
81+
82+ if can_stop or i > retries:
83+ break
84+
85+ logger.info(f"Trying to propose fix locations. Try {i} of {retries}.")
86+
87+ raw_location_file = pjoin(output_dir, f"agent_loc_list_{i}")
88+
89+ # actually calling model
90+ res_text, *_ = common.SELECTED_MODEL.call(new_thread.to_msg())
91+
92+ new_thread.add_model(res_text, []) # no tools
93+
94+ logger.info(f"Fix locations produced in try {i}. Writing locations into file.")
95+
96+ with open(raw_location_file, "w") as f:
97+ f.write(res_text)
98+
99+ # print("HI", raw_location_file)
100+
101+ print_fix_loc_generation(
102+ res_text, f"try {i} / {retries}", print_callback=print_callback
103+ )
104+
105+ fragment_pattern = re.compile(
106+ r"<file>(.*?)</file>\s*<class>(.*?)</class>\s*<method>(.*?)</method>"
107+ )
108+
109+ result_msg = "No fragments found"
110+ res = []
111+ for match in fragment_pattern.finditer(res_text):
112+ res.append(
113+ {
114+ "file": match.group(1),
115+ "class": match.group(2),
116+ "method": match.group(3),
117+ }
118+ )
119+ result_msg = "Found fragments"
120+
121+ can_stop = res != []
122+ Path(output_dir, f"agent_fix_locations_{i}.json").write_text(
123+ json.dumps(res, indent=4)
124+ )
125+ return result_msg
modified app/api/manage.py +25 −3
@@ -12,7 +12,7 @@
1212 from app import log
1313 from app.analysis import sbfl
1414 from app.analysis.sbfl import NoCoverageData
15-from app.api import agent_proxy, agent_write_patch
15+from app.api import agent_proxy, agent_write_locations, agent_write_patch
1616 from app.data_structures import FunctionCallIntent, MessageThread
1717 from app.log import log_exception
1818 from app.search.search_manage import SearchManager
@@ -193,7 +193,7 @@
193193 Also a summary that should be communicated to the model.
194194 """
195195 if (intent.func_name not in self.api_functions) and (
196- intent.func_name != "get_class_full_snippet"
196+ intent.func_name not in ["get_class_full_snippet", "propose_locs"]
197197 ):
198198 error = f"Unknown function name {intent.func_name}."
199199 summary = "You called a tool that does not exist. Please only use the tools provided."
@@ -202,7 +202,7 @@
202202 try:
203203 # ready to call a function
204204 self.curr_tool = intent.func_name
205- if intent.func_name in ["write_patch"]:
205+ if intent.func_name in ["write_patch", "propose_locs"]:
206206 # these two functions require the message thread
207207 call_res = func_obj(message_thread, print_callback=print_callback)
208208 else:
@@ -454,6 +454,28 @@
454454 # The return status of write_patch does not really matter, so we just use True here
455455 return tool_output, summary, True
456456
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+
457479 def proxy_apis(self, text: str) -> tuple[str | None, str, list[MessageThread]]:
458480 """Proxy APIs to another agent."""
459481 tool_output, new_thread = agent_proxy.run_with_retries(
modified app/inference.py +28 −11
@@ -96,6 +96,7 @@
9696
9797 round_count = range(start_round_no, globals.conv_round_limit + 1)
9898
99+ try_generate_locs = False
99100 if globals.disable_patch_generation:
100101 round_count = range(
101102 start_round_no, start_round_no + globals.context_generation_limit + 1
@@ -152,6 +153,9 @@
152153 for location in buggy_locations:
153154 s = ", ".join(f"{k}: `{v}`" for k, v in location.items())
154155 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+ )
155159
156160 print_acr(
157161 "\n".join(formatted),
@@ -179,9 +183,6 @@
179183 logger.debug(
180184 "Gathered enough information. Skipping patch generation due to feature flag."
181185 )
182- Path(output_dir, "fix_locations.json").write_text(
183- json.dumps(buggy_locations, indent=4)
184- )
185186 else:
186187 print_banner("PATCH GENERATION")
187188 logger.debug("Gathered enough information. Invoking write_patch.")
@@ -254,23 +255,39 @@
254255 print_callback=print_callback,
255256 )
256257 else:
257- logger.info("Too many rounds. Try writing patch anyway.")
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 = True # all_locs != []
269+ log_msg = "Try outputing some locations still."
270+
271+ logger.info(f"Too many rounds. {log_msg}")
258272
259273 round_no += 1
260274
261275 if not globals.disable_patch_generation:
262- api_manager.start_new_tool_call_layer()
276+ intent = FunctionCallIntent("write_patch", {}, None)
277+ elif try_generate_locs:
278+ intent = FunctionCallIntent("propose_locs", {}, None)
279+ else:
280+ intent = None
263281
264- write_patch_intent = FunctionCallIntent("write_patch", {}, None)
265- api_manager.dispatch_intent(
266- write_patch_intent, msg_thread, print_callback=print_callback
267- )
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}.")
268286
287+ logger.info("Ending workflow.")
269288 conversation_file = pjoin(output_dir, f"conversation_round_{round_no}.json")
270289 msg_thread.save_to_file(conversation_file)
271290
272- logger.info("Invoked write_patch. Ending workflow.")
273-
274291 return True
275292
276293
modified app/log.py +29 −0
@@ -143,6 +143,35 @@
143143 )
144144
145145
146+def print_fix_loc_generation(
147+ msg: str, desc="", print_callback: Callable[[dict], None] | None = None
148+) -> None:
149+ if not print_stdout:
150+ return
151+
152+ msg = replace_html_tags(msg)
153+ markdown = Markdown(msg)
154+
155+ name = "Fix Location Generation"
156+ if desc:
157+ title = f"{name} ({desc})"
158+ else:
159+ title = name
160+
161+ panel = Panel(
162+ markdown, title=title, title_align="left", border_style="green", width=WIDTH
163+ )
164+ console.print(panel)
165+ if print_callback:
166+ print_callback(
167+ {
168+ "title": f"{name} ({desc})",
169+ "message": msg,
170+ "category": "fix_loc_generation",
171+ }
172+ )
173+
174+
146175 def print_issue(content: str) -> None:
147176 if not print_stdout:
148177 return