Elffuss BraidHub

kikocis/auto-code-rover public

main · 8.9 KiBRawPermalink
1import argparse
2import json
3import os
4import random
5import re
6import time
7from glob import glob
8from os.path import basename, join
9from pathlib import Path
10
11import tiktoken
12from rich.columns import Columns
13from rich.console import Console
14from rich.live import Live
15from rich.markdown import Markdown
16from rich.panel import Panel
17
18ENCODING = tiktoken.get_encoding("cl100k_base")
19
20
21def terminal_width():
22 terminal_size = os.get_terminal_size()
23 return terminal_size.columns
24
25
26def remove_lines_console(num_lines):
27 for _ in range(num_lines):
28 # print("\x1b[A" + " " * terminal_width(), end="\r", flush=True)
29 print("\x1b[A", end="\r", flush=True)
30
31
32def estimate_lines(text):
33 columns, _ = os.get_terminal_size()
34 line_count = 1
35 text_lines = text.split("\n")
36 for text_line in text_lines:
37 lines_needed = (len(text_line) // columns) + 1
38
39 line_count += lines_needed
40
41 return line_count
42
43
44class conchat:
45 def __init__(self, history) -> None:
46 self.console = Console()
47 self.history = history
48
49 def tokenize_and_yield(self, s):
50 enc = ENCODING.encode(s)
51 tokens = [ENCODING.decode([token]) for token in enc]
52 n = len(tokens)
53 idx = 0
54 while idx < n:
55 # for idx in range(n - 1):
56 k = random.randint(1, 8)
57 end_idx = idx + k
58 yield "".join(tokens[idx:end_idx]), end_idx >= n
59 idx += k
60 time.sleep(random.random() * 0.00)
61 # yield tokens[n - 1], True
62
63 def handle_streaming(self, content, title, color):
64 stream = self.tokenize_and_yield(content)
65 text = ""
66 block = "█ "
67 with Live(console=self.console, refresh_per_second=1000) as live:
68 for token, is_last in stream:
69 text = text + token
70 if is_last:
71 block = ""
72 markdown = Markdown(text + block)
73 panel = Panel(
74 markdown,
75 title=title,
76 title_align="left",
77 border_style=color,
78 width=terminal_width() * 2 // 3,
79 )
80 unit = terminal_width() * 1 // 6 - 5
81 if "rover" in title.lower():
82 level = 0
83 elif "context" in title.lower():
84 level = 1
85 else:
86 level = 2
87
88 columns = Columns([" " * unit * level, panel], column_first=True)
89 live.update(
90 columns,
91 refresh=True,
92 )
93
94 def chat(self):
95 for msg in self.history:
96 try:
97 self.handle_streaming(
98 content=msg["content"].strip(),
99 title=msg["title"],
100 color=msg["color"],
101 )
102 if msg.get("stop", None):
103 input()
104 # NOTE: Ctrl + c (keyboard) or Ctrl + d (eof) to exit
105 # Adding EOFError prevents an exception and gracefully exits.
106 except (KeyboardInterrupt, EOFError):
107 exit()
108
109
110def replay(history_file):
111 with open(history_file) as f:
112 history = json.load(f)
113
114 chat = conchat(history=history)
115 chat.chat()
116
117
118def make_history(dir):
119 main_conv_file = sorted(
120 glob(
121 join(dir, "conversation_round_*.json"),
122 ),
123 key=lambda s: int(
124 basename(s).removeprefix("conversation_round_").removesuffix(".json")
125 ),
126 )[-1]
127
128 agent_patch_file = sorted(
129 glob(
130 join(dir, "debug_agent_write_patch_*.json"),
131 ),
132 key=lambda s: int(
133 basename(s).removeprefix("debug_agent_write_patch_").removesuffix(".json")
134 ),
135 )[-1]
136
137 print("Using main conversation:", main_conv_file)
138 print("Using patch agent conversation", agent_patch_file)
139 print()
140
141 retrieval_data = json.loads(Path(main_conv_file).read_text())
142 patch_data = json.loads(Path(agent_patch_file).read_text())
143
144 history = []
145
146 name_main = "💻 AutoCodeRover"
147 name_context_retriever = "🔎 Context Retrieval Agent"
148 name_patch_generator = "💊 Patch Generation Agent"
149
150 for msg in retrieval_data:
151 if msg["role"] == "user":
152 content = re.sub(
153 r"(search result \d+:)", r"\n\1\n\n", msg["content"], flags=re.I
154 )
155 if content.startswith("Based on your analysis, answer below questions:"):
156 content = (
157 "Based on your analysis, answer below questions:\n"
158 " - 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)\n"
159 " - where are bug locations: buggy files and methods. (leave it empty if you don't have enough information)"
160 )
161 if content.startswith("Based on the files"):
162 content = """Based on the files, classes, methods, code statements from the issue that related to the bug, you can use below search APIs to get more context of the project.
163
164
165 - search_class(class_name: str): Search for a class in the codebase.
166
167 - search_method_in_file(method_name: str, file_path: str): Search for a method in a given file.
168
169 - search_method_in_class(method_name: str, class_name: str): Search for a method in a given class.
170
171 - search_method(method_name: str): Search for a method in the entire codebase.
172
173 - search_code(code_str: str): Search for a code snippet in the entire codebase.
174
175 - search_code_in_file(code_str: str, file_path: str): Search for a code snippet in a given file file.
176
177Note that you can use multiple search APIs in one round.
178
179Now analyze the issue and select necessary APIs to get more context of the project, each API call must have concrete arguments as inputs.
180 """
181
182 content = (
183 content.replace(r"<file>", "&lt;file&gt;")
184 .replace(r"<class>", "&lt;class&gt;")
185 .replace(r"<func>", "&lt;func&gt;")
186 .replace(r"<code>", "&lt;code&gt;\n```")
187 .replace(r"</file>", "&lt;/file&gt;\n\n")
188 .replace(r"</class>", "&lt;/class&gt;\n\n")
189 .replace(r"</func>", "&lt;/func&gt;\n\n")
190 .replace(r"</code>", "\n```\n&lt;/code&gt;\n\n")
191 )
192
193 content = re.sub(r"Other results are in these files:\s+\n", "", content)
194
195 if content.startswith("Based on your analysis, answer below questions:"):
196 content = content.replace("- do we need", "\n - do we need").replace(
197 "- where are", "\n - where are"
198 )
199
200 history.append(dict(title=name_main, content=content, color="white"))
201 elif msg["role"] == "assistant":
202 history.append(
203 dict(
204 title=name_context_retriever,
205 content=msg["content"],
206 color="blue",
207 )
208 )
209
210 start = False
211 for msg in patch_data:
212 if msg["content"].startswith("Write a patch for the issue"):
213 start = True
214 if not start:
215 continue
216
217 if msg["role"] == "user":
218 content = msg["content"]
219 content = (
220 content.replace(r"<file>", "&lt;file&gt;")
221 .replace(r"<class>", "&lt;class&gt;")
222 .replace(r"<func>", "&lt;method&gt;")
223 .replace(r"<code>", "&lt;code&gt;\n```")
224 .replace(r"</file>", "&lt;/file&gt;\n\n")
225 .replace(r"</class>", "&lt;/class&gt;\n\n")
226 .replace(r"</func>", "&lt;/func&gt;\n\n")
227 .replace(r"</code>", "\n```\n&lt;/code&gt;\n\n")
228 )
229 history.append(dict(title=name_main, content=content, color="white"))
230 elif msg["role"] == "assistant":
231 history.append(
232 dict(
233 title=name_patch_generator,
234 content=msg["content"],
235 color="yellow",
236 )
237 )
238
239 out_file = Path(dir, "history.json")
240 with open(out_file, "w") as f:
241 json.dump(history, f, indent=4)
242
243 print("History extracted successfully:", out_file)
244
245
246def main():
247 parser = argparse.ArgumentParser(
248 description="Console Inference of LLM models. Works with any OpenAI compatible server."
249 )
250 parser.add_argument(
251 "-r",
252 "--replay",
253 help="json file of conversation history",
254 type=str,
255 )
256 parser.add_argument(
257 "-m", "--make-history", help="make history from individual expr directory"
258 )
259
260 args = parser.parse_args()
261
262 if args.replay:
263 replay(args.replay)
264 return
265
266 if args.make_history:
267 make_history(args.make_history)
268 return
269
270 parser.print_help()
271
272
273if __name__ == "__main__":
274 main()