-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpasquale.py
More file actions
251 lines (192 loc) · 8.97 KB
/
pasquale.py
File metadata and controls
251 lines (192 loc) · 8.97 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
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
import json
import os
import warnings
from openai import OpenAI
from difflib import Differ
from pprint import pprint
class Pasquale:
prompt_types = ("system", "reason", "text")
def __init__(self, prompts_folder="prompts", config_file="config.json"):
with open(config_file) as in_file:
config_json = json.load(in_file)
self.client = OpenAI(**config_json['creds'])
self.config = config_json['config']
self.model_families = set(next(os.walk(prompts_folder))[1])
self.messages = []
self.prompts = {}
self._setup_prompt_family("base", prompts_folder)
for family in self.model_families:
if family == "base":
pass
self._setup_prompt_family(family, prompts_folder)
def _setup_prompt_family(self, family, prompts_folder):
if not os.path.exists(f"{prompts_folder}/{family}") and family == "base":
raise FileNotFoundError(f"No prompts for base family found. Aborting...")
prompt = {}
for language in os.listdir(prompts_folder + "/" + family):
prompt[language] = self._setup_prompt_language(family, prompts_folder, language)
self.prompts[family] = prompt
def _setup_prompt_language(self, family, prompts_folder, language):
language_prompt = {}
for p_type in self.prompt_types:
language_prompt[p_type] = self._setup_prompt_type(family, prompts_folder, language, p_type)
return language_prompt
def _setup_prompt_type(self, family, prompts_folder, language, p_type):
file_name = f"{prompts_folder}/{family}/{language}/{p_type}.md"
try:
with open(file_name) as in_file:
return in_file.read()
except FileNotFoundError as e:
if family == "base":
raise FileNotFoundError(f"Base {p_type} prompt for language {language} missing. Aborting...") from e
else:
warnings.warn(f"""No {p_type} prompt for family '{family}' found.
Pasquale will use base prompts instead.""")
return self.prompts['base'][language][p_type]
return language_prompt
def _get_corrections(text1, text2):
d = Differ()
result = list(d.compare(text1, text2))
corrections = []
added_s = []
removed_s = []
i = 0
start_i = -1
text1_i = 0
text2_i = 0
char_start = 0
char_i = 0
while i < len(result):
if result[i][0] == "+":
if start_i == -1:
start_i = text1_i
char_start = char_i
added_s.append(text2[text2_i])
text2_i += 1
elif result[i][0] == "-":
if start_i == -1:
start_i = text1_i
char_start = char_i
removed_s.append(text1[text1_i])
char_i += len(text1[text1_i])+1
text1_i += 1
if result[i][0] == " " or i == len(result)-1:
if start_i != -1:
aux_dic = {}
aux_dic['added'] = " ".join(added_s) if len(added_s) > 0 else " "
aux_dic['removed'] = " ".join(removed_s)
aux_dic['start'] = start_i
aux_dic['char_start'] = char_start
aux_dic['len'] = len(" ".join(removed_s))
aux_dic['context1'] = " ".join(text1[max(0, start_i-2) : min(text1_i+2, len(text1))])
aux_dic['context2'] = " ".join(text1[max(0, start_i-2) : start_i]
+ added_s+text1[text1_i : min(text1_i+2, len(text1))])
# if just adds, remove its closests neighbor
if aux_dic['len'] == 0:
if text1_i < len(text1):
aux_dic['added'] = aux_dic['added'] + " " + text1[text1_i]
aux_dic['removed'] = text1[text1_i]
aux_dic['len'] = len(text1[text1_i])
else:
aux_dic['added'] = text1[text1_i-1] + " "
aux_dic['removed'] = text1[text1_i-1]
aux_dic['char_start'] -= len(text1[text1_i-1])
aux_dic['len'] = len(text1[text1_i-1])
# if just removes, expand bar to include the neighboring spaces
if aux_dic['added'] == " ":
if text1_i != len(text1):
aux_dic['len'] += 1
if text1_i != 0:
aux_dic['char_start'] -= 1
corrections.append(aux_dic)
start_i = -1
added_s.clear()
removed_s.clear()
if i != len(result)-1:
char_i += len(text1[text1_i])+1
text1_i += 1
text2_i += 1
i += 1
return corrections
def ask_llm_check(
self,
text,
language,
model,
model_family,
genres="",
extra_prompt="",
temperature=0.0,
max_tokens=8000,
thinking=False,
persistent=True):
if model_family not in self.model_families:
warnings.warn(f"No prompts for family '{model_family}' found. Pasquale will use base prompts instead.")
model_family = "base"
current_prompts = self.prompts[model_family][language]
if len(current_prompts['system']) != 0:
system_prompt = current_prompts['system'].format(
genres=genres)
text = current_prompts['text'].format(
text=text) + "\n" + extra_prompt
self.messages=[
{"role": "system", "content": system_prompt},
{"role": "user", "content": text},
]
else:
text = current_prompts['text'].format(
text=text, genres=genres) + "\n" + extra_prompt
self.messages=[{"role": "user", "content": text}]
completion = self.client.chat.completions.create(
model = model,
messages = self.messages,
max_completion_tokens = max_tokens,
temperature = temperature)
if persistent:
self.messages.append(completion.choices[0].message)
if thinking:
return completion.choices[0].message.content.split("</think>\n\n")[1].strip("\n")
else:
return completion.choices[0].message.content.strip("\n")
def ask_llm_reason(
self,
correction,
language,
model,
model_family,
genres="",
extra_prompt="",
temperature=0.0,
max_tokens=8000,
thinking=False,
persistent=False):
if model_family not in self.model_families:
warnings.warn(f"No prompts for family '{model_family}' found. Pasquale will use base prompts instead.")
model_family = "base"
current_prompts = self.prompts[model_family][language]
text = current_prompts['reason'].format(
removed = correction['removed'],
added = correction['added'],
context1 = correction['context1'],
context2 = correction['context2']) + "\n" + extra_prompt
completion = self.client.chat.completions.create(
model = model,
messages = self.messages + [{"role": "user", "content": text}],
max_completion_tokens = max_tokens,
temperature = temperature)
if persistent:
self.messages.append({"role": "user", "content": text})
self.messages.append(completion.choices[0].message)
if thinking:
return completion.choices[0].message.content.split("</think>\n\n")[1].strip("\n")
else:
return completion.choices[0].message.content.strip("\n")
def check(
self,
text,
language):
cor_text = self.ask_llm_check(text, language, **self.config)
corrections = Pasquale._get_corrections(text.split(" "), cor_text.split(" "))
for correction in corrections:
correction['reason'] = self.ask_llm_reason(correction, language, **self.config)
return corrections