-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathutils.py
356 lines (303 loc) · 12.4 KB
/
utils.py
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
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
import json
import os
import re
import numpy as np
import pandas as pd
from sentence_transformers import SentenceTransformer
from sklearn.metrics.pairwise import cosine_similarity
model = SentenceTransformer('sentence-transformers/all-MiniLM-L6-v2') # Embedding model
llama3 = {
"config_list": [
{
"model": "SanctumAI/Meta-Llama-3-8B-Instruct-GGUF",
"base_url": "http://localhost:1234/v1",
"api_key": "lm-studio",
},
],
"cache_seed": None, # Disable caching.
}
# GENERAL FUNCTIONS
def save_personality_to_file(content, filename, folder):
if not filename.endswith(".txt"):
filename += ".txt"
# Verifica se la cartella esiste, altrimenti la crea
if not os.path.exists(folder):
os.makedirs(folder)
# Componi il percorso completo del file
file_path = os.path.join(folder, filename)
with open(file_path, 'w', encoding='utf-8') as file:
file.write(content)
def read_from_file(filename, folder):
# Componi il percorso completo del file
file_path = os.path.join(folder, filename)
if not os.path.exists(file_path):
return "File not found." # Il file non esiste
with open(file_path, 'r', encoding='utf-8') as file:
content = file.read()
return content
def from_string_to_json(text):
try:
# Prova a caricare la stringa JSON utilizzando il modulo json
json_data = json.loads(text)
return json_data
except json.JSONDecodeError:
# Se il parsing JSON fallisce, prova a estrarre il primo blocco JSON
match = re.search(r'{(.*?)}', text, re.DOTALL)
if match:
json_text = match.group(1)
json_text = json_text.strip()
try:
# Tentativo di caricare il testo JSON estratto e formattarlo con i doppi apici
json_data = json.loads("{" + json_text + "}")
return json_data
except json.JSONDecodeError as e:
print(f"JSON string parsing error: {e}")
# Se tutto fallisce, restituisci un dizionario vuoto
return {}
def get_unique_contents(related_content):
seen = {}
unique_contents = []
for doc in related_content['documents'][0]:
if doc not in seen:
seen[doc] = True
unique_contents.append(doc)
return unique_contents
def related_contents_to_string(content_list):
related_content_string = ""
for content in content_list[:10]:
related_content_string += "\"" + content + "\"\n"
return related_content_string
def get_agent_from_agent_list(agent_list, agent_name):
for agent in agent_list:
if agent.name.lower() == agent_name:
return agent
return 'ERROR: Agent not found.'
def suggested_follows_to_string(suggestion_list, personality_folder):
suggested_follows_string = ""
for follow_suggestion in suggestion_list[:5]:
suggested_agent = follow_suggestion['agent']
suggested_agent_personality = read_from_file(f"{suggested_agent.name.lower()}.txt", personality_folder)
suggested_follows_string += "\"" + str(follow_suggestion['agent'].name) + "\" - Personality: " + suggested_agent_personality + "\n"
return suggested_follows_string
# FUNCTIONS FOR CHECKING THE FORMAT OF USER RESPONSES
def check_choice_reason_format(user_proxy, agent):
answer_correct_format = False
attempt = 0
while not answer_correct_format:
answer = user_proxy.last_message(agent)["content"]
json_answer = from_string_to_json(answer)
if all(key.lower() in map(str.lower, json_answer) for key in ["Choice", "Reason"]) and len(json_answer) == 2 and all(isinstance(value, str) for value in json_answer.values()):
answer_correct_format = True
else:
attempt += 1
if attempt <= 3:
user_proxy.initiate_chat(
agent,
message=read_from_file("check_choice_reason_format", "Prompt/errors"),
clear_history=False
)
else:
answer_correct_format = True
json_answer = {
"Choice": "2",
"Reason": "Auto",
"New content": "N/A"
}
return json_answer
def check_new_content_format(user_proxy, agent):
answer_correct_format = False
attempt = 0
while not answer_correct_format:
answer = user_proxy.last_message(agent)["content"]
json_answer = from_string_to_json(answer)
if all(key.lower() in map(str.lower, json_answer) for key in ["New content"]) and len(json_answer) == 1 and all(isinstance(value, str) for value in json_answer.values()):
answer_correct_format = True
else:
attempt += 1
if attempt <= 3:
user_proxy.initiate_chat(
agent,
message=read_from_file("check_new_content_format", "Prompt/errors"),
clear_history=False
)
else:
answer_correct_format = True
json_answer = {
"Choice": "2",
"Reason": "Auto",
"New content": "N/A"
}
return json_answer
def check_shared_content_format(user_proxy, agent):
answer_correct_format = False
attempt = 0
while not answer_correct_format:
answer = user_proxy.last_message(agent)["content"]
json_answer = from_string_to_json(answer)
if all(key.lower() in map(str.lower, json_answer) for key in ["Shared content"]) and len(json_answer) == 1 and all(isinstance(value, str) for value in json_answer.values()):
answer_correct_format = True
else:
attempt += 1
if attempt <= 3:
user_proxy.initiate_chat(
agent,
message=read_from_file("check_shared_content_format", "Prompt/errors"),
clear_history=False
)
else:
answer_correct_format = True
json_answer = {
"Choice": "2",
"Reason": "Auto",
"New content": "N/A"
}
return json_answer
def check_liked_content_format(user_proxy, agent):
answer_correct_format = False
attempt = 0
while not answer_correct_format:
answer = user_proxy.last_message(agent)["content"]
json_answer = from_string_to_json(answer)
if all(key.lower() in map(str.lower, json_answer) for key in ["Liked content"]) and len(json_answer) == 1 and all(isinstance(value, str) for value in json_answer.values()):
answer_correct_format = True
else:
attempt += 1
if attempt <= 3:
user_proxy.initiate_chat(
agent,
message=read_from_file("check_liked_content_format", "Prompt/errors"),
clear_history=False
)
else:
answer_correct_format = True
json_answer = {
"Choice": "2",
"Reason": "Auto",
"New content": "N/A"
}
return json_answer
def check_disliked_content_format(user_proxy, agent):
answer_correct_format = False
attempt = 0
while not answer_correct_format:
answer = user_proxy.last_message(agent)["content"]
json_answer = from_string_to_json(answer)
if all(key.lower() in map(str.lower, json_answer) for key in ["Disliked content"]) and len(json_answer) == 1 and all(isinstance(value, str) for value in json_answer.values()):
answer_correct_format = True
else:
attempt += 1
if attempt <= 3:
user_proxy.initiate_chat(
agent,
message=read_from_file("check_disliked_content_format", "Prompt/errors"),
clear_history=False
)
else:
answer_correct_format = True
json_answer = {
"Choice": "2",
"Reason": "Auto",
"New content": "N/A"
}
return json_answer
def check_commented_content_format(user_proxy, agent):
answer_correct_format = False
attempt = 0
while not answer_correct_format:
answer = user_proxy.last_message(agent)["content"]
json_answer = from_string_to_json(answer)
if all(key.lower() in map(str.lower, json_answer) for key in ["Commented content"]) and len(json_answer) == 1 and all(isinstance(value, str) for value in json_answer.values()):
answer_correct_format = True
else:
attempt += 1
if attempt <= 3:
user_proxy.initiate_chat(
agent,
message=read_from_file("check_commented_content_format", "Prompt/errors"),
clear_history=False
)
else:
answer_correct_format = True
json_answer = {
"Choice": "2",
"Reason": "Auto",
"New content": "N/A"
}
return json_answer
def check_conversation_1_to_1_format(user_proxy, agent):
answer_correct_format = False
attempt = 0
while not answer_correct_format:
answer = user_proxy.last_message(agent)["content"]
json_answer = from_string_to_json(answer)
if all(key.lower() in map(str.lower, json_answer) for key in ["Comment"]) and len(json_answer) == 1 and all(isinstance(value, str) for value in json_answer.values()):
answer_correct_format = True
else:
attempt += 1
if attempt <= 3:
user_proxy.initiate_chat(
agent,
message=read_from_file("check_conversation_1_to_1_format", "Prompt/errors"),
clear_history=False
)
else:
answer_correct_format = True
json_answer = {
"Choice": "2",
"Reason": "Auto",
"New content": "N/A"
}
return json_answer
def check_follow_content_format(user_proxy, agent):
answer_correct_format = False
attempt = 0
while not answer_correct_format:
answer = user_proxy.last_message(agent)["content"]
json_answer = from_string_to_json(answer)
if all(key.lower() in map(str.lower, json_answer) for key in ["Followed user"]) and len(json_answer) == 1 and all(isinstance(value, str) for value in json_answer.values()):
answer_correct_format = True
else:
attempt += 1
if attempt <= 3:
user_proxy.initiate_chat(
agent,
message=read_from_file("check_follow_content_format", "Prompt/errors"),
clear_history=False
)
else:
answer_correct_format = True
json_answer = {
"Choice": "2",
"Reason": "Auto",
"New content": "N/A"
}
return json_answer
def check_interview_format(user_proxy, agent):
answer_correct_format = False
attempt = 0
while not answer_correct_format:
answer = user_proxy.last_message(agent)["content"]
json_answer = from_string_to_json(answer)
if all(key.lower() in map(str.lower, json_answer) for key in ["Main Influence", "Explanation"]) and len(json_answer) == 2 and all(isinstance(value, str) for value in json_answer.values()):
answer_correct_format = True
else:
attempt += 1
if attempt <= 3:
user_proxy.initiate_chat(
agent,
message=read_from_file("check_interview_format", "Prompt/errors"),
clear_history=False
)
else:
answer_correct_format = True
json_answer = {
"Choice": "2",
"Reason": "Auto",
"New content": "N/A"
}
return json_answer
# FUNCTIONS FOR CALCULATING EMBEDDINGS AND SIMILARITY
def get_embedding(text):
return model.encode(text)
def calculate_similarity(embedding1, embedding2):
return cosine_similarity([embedding1], [embedding2])[0][0]