Elffuss BraidHub

kikocis/auto-code-rover public

main · 4.2 KiBRawPermalink
1"""
2A proxy agent. Process raw response into json format.
3"""
4
5import inspect
6from typing import Any
7
8from loguru import logger
9
10from app.data_structures import MessageThread
11from app.model import common
12from app.post_process import ExtractStatus, is_valid_json
13from app.search.search_manage import SearchManager
14from app.utils import parse_function_invocation
15
16PROXY_PROMPT = """
17You are a helpful assistant that retreive API calls and bug locations from a text into json format.
18The text will consist of two parts:
191. do we need more context?
202. where are bug locations?
21Extract API calls from question 1 (leave empty if not exist) and bug locations from question 2 (leave empty if not exist).
22
23The API calls include:
24search_method_in_class(method_name: str, class_name: str)
25search_method_in_file(method_name: str, file_path: str)
26search_method(method_name: str)
27search_class_in_file(self, class_name, file_name: str)
28search_class(class_name: str)
29search_code_in_file(code_str: str, file_path: str)
30search_code(code_str: str)
31
32Provide your answer in JSON structure like this, you should ignore the argument placeholders in api calls.
33For example, search_code(code_str="str") should be search_code("str")
34search_method_in_file("method_name", "path.to.file") should be search_method_in_file("method_name", "path/to/file")
35Make sure each API call is written as a valid python expression.
36
37{
38 "API_calls": ["api_call_1(args)", "api_call_2(args)", ...],
39 "bug_locations":[{"file": "path/to/file", "class": "class_name", "method": "method_name"}, {"file": "path/to/file", "class": "class_name", "method": "method_name"} ... ]
40}
41
42NOTE: a bug location should at least has a "class" or "method".
43"""
44
45
46def run_with_retries(text: str, retries=5) -> tuple[str | None, list[MessageThread]]:
47 msg_threads = []
48 for idx in range(1, retries + 1):
49 logger.debug(
50 "Trying to select search APIs in json. Try {} of {}.", idx, retries
51 )
52
53 res_text, new_thread = run(text)
54 msg_threads.append(new_thread)
55
56 extract_status, data = is_valid_json(res_text)
57
58 if extract_status != ExtractStatus.IS_VALID_JSON:
59 logger.debug("Invalid json. Will retry.")
60 continue
61
62 valid, diagnosis = is_valid_response(data)
63 if not valid:
64 logger.debug(f"{diagnosis}. Will retry.")
65 continue
66
67 logger.debug("Extracted a valid json")
68 return res_text, msg_threads
69 return None, msg_threads
70
71
72def run(text: str) -> tuple[str, MessageThread]:
73 """
74 Run the agent to extract issue to json format.
75 """
76
77 msg_thread = MessageThread()
78 msg_thread.add_system(PROXY_PROMPT)
79 msg_thread.add_user(text)
80 res_text, *_ = common.SELECTED_MODEL.call(
81 msg_thread.to_msg(), response_format="json_object"
82 )
83
84 msg_thread.add_model(res_text, []) # no tools
85
86 return res_text, msg_thread
87
88
89def is_valid_response(data: Any) -> tuple[bool, str]:
90 if not isinstance(data, dict):
91 return False, "Json is not a dict"
92
93 if not data.get("API_calls"):
94 bug_locations = data.get("bug_locations")
95 if not isinstance(bug_locations, list) or not bug_locations:
96 return False, "Both API_calls and bug_locations are empty"
97
98 for loc in bug_locations:
99 if loc.get("class") or loc.get("method"):
100 continue
101 return False, "Bug location not detailed enough"
102 else:
103 for api_call in data["API_calls"]:
104 if not isinstance(api_call, str):
105 return False, "Every API call must be a string"
106
107 try:
108 func_name, func_args = parse_function_invocation(api_call)
109 except Exception:
110 return False, "Every API call must be of form api_call(arg1, ..., argn)"
111
112 function = getattr(SearchManager, func_name, None)
113 if function is None:
114 return False, f"the API call '{api_call}' calls a non-existent function"
115
116 arg_spec = inspect.getfullargspec(function)
117 arg_names = arg_spec.args[1:] # first parameter is self
118
119 if len(func_args) != len(arg_names):
120 return False, f"the API call '{api_call}' has wrong number of arguments"
121
122 return True, "OK"