forked from CopilotC-Nvim/CopilotChat.nvim
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathchat_handler.py
More file actions
209 lines (169 loc) · 6.09 KB
/
Copy pathchat_handler.py
File metadata and controls
209 lines (169 loc) · 6.09 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
from typing import Optional, cast
import prompts as prompts
from copilot import Copilot
from mypynvim.core.buffer import MyBuffer
from mypynvim.core.nvim import MyNvim
def is_module_installed(name):
try:
__import__(name)
return True
except ImportError:
return False
class ChatHandler:
def __init__(self, nvim: MyNvim, buffer: MyBuffer):
self.nvim: MyNvim = nvim
self.copilot = None
self.buffer: MyBuffer = buffer
# public
def chat(
self,
prompt: str,
filetype: str,
code: str = "",
winnr: int = 0,
system_prompt: Optional[str] = None,
disable_start_separator: bool = False,
disable_end_separator: bool = False,
model: str = "gpt-4",
):
if system_prompt is None:
system_prompt = self._construct_system_prompt(prompt)
# Start the spinner
self.nvim.exec_lua('require("CopilotChat.spinner").show()')
self.nvim.exec_lua(
'require("CopilotChat.utils").log_info(...)', f"Chatting with {model} model"
)
if not disable_start_separator:
self._add_start_separator(system_prompt, prompt, code, filetype, winnr)
self._add_chat_messages(system_prompt, prompt, code, filetype, model)
# Stop the spinner
self.nvim.exec_lua('require("CopilotChat.spinner").hide()')
if not disable_end_separator:
self._add_end_separator()
# private
def _construct_system_prompt(self, prompt: str):
system_prompt = prompts.COPILOT_INSTRUCTIONS
if prompt == prompts.FIX_SHORTCUT:
system_prompt = prompts.COPILOT_FIX
elif prompt == prompts.TEST_SHORTCUT:
system_prompt = prompts.COPILOT_TESTS
elif prompt == prompts.EXPLAIN_SHORTCUT:
system_prompt = prompts.COPILOT_EXPLAIN
return system_prompt
def _add_start_separator(
self,
system_prompt: str,
prompt: str,
code: str,
file_type: str,
winnr: int,
):
if is_module_installed("tiktoken"):
self._add_start_separator_with_token_count(
system_prompt, prompt, code, file_type, winnr
)
else:
self._add_regular_start_separator(
system_prompt, prompt, code, file_type, winnr
)
def _add_regular_start_separator(
self,
system_prompt: str,
prompt: str,
code: str,
file_type: str,
winnr: int,
):
if code:
code = f"\n \nCODE:\n```{file_type}\n{code}\n```"
last_row_before = len(self.buffer.lines())
system_prompt_height = len(system_prompt.split("\n"))
code_height = len(code.split("\n"))
start_separator = f"""### User
SYSTEM PROMPT:
```
{system_prompt}
```
{prompt}{code}
### Copilot
"""
self.buffer.append(start_separator.split("\n"))
self._add_folds(code, code_height, last_row_before, system_prompt_height, winnr)
def _add_start_separator_with_token_count(
self,
system_prompt: str,
prompt: str,
code: str,
file_type: str,
winnr: int,
):
import tiktoken
encoding = tiktoken.encoding_for_model("gpt-4")
num_total_tokens = len(encoding.encode(f"{system_prompt}\n{prompt}\n{code}"))
num_system_tokens = len(encoding.encode(system_prompt))
num_prompt_tokens = len(encoding.encode(prompt))
num_code_tokens = len(encoding.encode(code))
if code:
code = f"\n \nCODE: {num_code_tokens} Tokens \n```{file_type}\n{code}\n```"
last_row_before = len(self.buffer.lines())
system_prompt_height = len(system_prompt.split("\n"))
code_height = len(code.split("\n"))
start_separator = f"""### User
SYSTEM PROMPT: {num_system_tokens} Tokens
```
{system_prompt}
```
{prompt}{code}
### Copilot
"""
self.buffer.append(start_separator.split("\n"))
last_row_after = last_row_before + system_prompt_height + 5
self.buffer.eol(last_row_before, f"{num_total_tokens} Total Tokens", "@float")
self.buffer.eol(
last_row_after, f"{num_prompt_tokens} Tokens", "NightflySteelBlue"
)
self._add_folds(code, code_height, last_row_before, system_prompt_height, winnr)
def _add_folds(
self,
code: str,
code_height: int,
last_row_before: int,
system_prompt_height: int,
winnr: int,
):
system_fold_start = last_row_before + 2
system_fold_end = system_fold_start + system_prompt_height + 3
main_command = f"{system_fold_start}, {system_fold_end} fold | normal! Gzz"
full_command = f"call win_execute({winnr}, '{main_command}')"
self.nvim.command(full_command)
if code != "":
code_fold_start = system_fold_end + 2
code_fold_end = code_fold_start + code_height - 1
main_command = f"{code_fold_start}, {code_fold_end} fold | normal! G"
full_command = f"call win_execute({winnr}, '{main_command}')"
self.nvim.command(full_command)
def _add_chat_messages(
self, system_prompt: str, prompt: str, code: str, file_type: str, model: str
):
if self.copilot is None:
self.copilot = Copilot()
for token in self.copilot.ask(
system_prompt, prompt, code, language=cast(str, file_type), model=model
):
self.nvim.exec_lua(
'require("CopilotChat.utils").log_info(...)', f"Token: {token}"
)
buffer_lines = cast(list[str], self.buffer.lines())
last_line_row = len(buffer_lines) - 1
last_line_col = len(buffer_lines[-1])
self.nvim.api.buf_set_text(
self.buffer.number,
last_line_row,
last_line_col,
last_line_row,
last_line_col,
token.split("\n"),
)
def _add_end_separator(self):
end_separator = "\n---\n"
self.buffer.append(end_separator.split("\n"))