-
Notifications
You must be signed in to change notification settings - Fork 544
/
lollms_webui.py
1536 lines (1352 loc) · 80.4 KB
/
lollms_webui.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
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
File: lollms_web_ui.py
Author: ParisNeo
Description: Singleton class for the LoLLMS web UI.
This class provides a singleton instance of the LoLLMS web UI, allowing access to its functionality and data across multiple endpoints.
"""
from lollms.server.elf_server import LOLLMSElfServer
from datetime import datetime
from lollms.databases.discussions_database import DiscussionsDB, Discussion
from pathlib import Path
from lollms.config import InstallOption
from lollms.types import MSG_TYPE, MSG_OPERATION_TYPE, MSG_OPERATION_TYPE, CONTENT_OPERATION_TYPES, SENDER_TYPES
from lollms.extension import LOLLMSExtension, ExtensionBuilder
from lollms.personality import AIPersonality, PersonalityBuilder
from lollms.binding import LOLLMSConfig, BindingBuilder, LLMBinding, ModelBuilder, BindingType
from lollms.paths import LollmsPaths
from lollms.helpers import ASCIIColors, trace_exception
from lollms.com import NotificationType, NotificationDisplayType, LoLLMsCom
from lollms.app import LollmsApplication
from lollms.utilities import File64BitsManager, PromptReshaper, PackageManager, find_first_available_file_index, run_async, is_asyncio_loop_running, yes_or_no_input, process_ai_output
from lollms.generation import RECEPTION_MANAGER, ROLE_CHANGE_DECISION, ROLE_CHANGE_OURTPUT
from lollms.client_session import Client
import git
import asyncio
import os
import threading
from tqdm import tqdm
import traceback
import sys
import gc
import ctypes
from functools import partial
import json
import shutil
import re
import string
import requests
from datetime import datetime
from typing import List, Tuple,Callable, Any
import time
import numpy as np
from lollms.utilities import find_first_available_file_index, convert_language_name
if not PackageManager.check_package_installed("requests"):
PackageManager.install_package("requests")
if not PackageManager.check_package_installed("bs4"):
PackageManager.install_package("beautifulsoup4")
import requests
def terminate_thread(thread):
if thread:
if not thread.is_alive():
ASCIIColors.yellow("Thread not alive")
return
thread_id = thread.ident
exc = ctypes.py_object(SystemExit)
res = ctypes.pythonapi.PyThreadState_SetAsyncExc(thread_id, exc)
if res > 1:
ctypes.pythonapi.PyThreadState_SetAsyncExc(thread_id, None)
del thread
gc.collect()
raise SystemError("Failed to terminate the thread.")
else:
ASCIIColors.yellow("Canceled successfully")# The current version of the webui
lollms_webui_version="v14.5 Alpha (code name Saïph 🌟)"
class LOLLMSWebUI(LOLLMSElfServer):
__instance = None
@staticmethod
def build_instance(
config: LOLLMSConfig,
lollms_paths: LollmsPaths,
load_binding=True,
load_model=True,
load_voice_service=True,
load_sd_service=True,
try_select_binding=False,
try_select_model=False,
callback=None,
args=None,
sio = None
):
if LOLLMSWebUI.__instance is None:
LOLLMSWebUI(
config,
lollms_paths,
load_binding=load_binding,
load_model=load_model,
load_sd_service=load_sd_service,
load_voice_service=load_voice_service,
try_select_binding=try_select_binding,
try_select_model=try_select_model,
callback=callback,
args=args,
sio=sio
)
return LOLLMSWebUI.__instance
def __init__(
self,
config: LOLLMSConfig,
lollms_paths: LollmsPaths,
load_binding=True,
load_model=True,
load_voice_service=True,
load_sd_service=True,
try_select_binding=False,
try_select_model=False,
callback=None,
args=None,
sio=None
) -> None:
super().__init__(
config,
lollms_paths,
load_binding=load_binding,
load_model=load_model,
try_select_binding=try_select_binding,
try_select_model=try_select_model,
callback=callback,
sio=sio
)
self.app_name:str = "LOLLMSWebUI"
self.version:str = lollms_webui_version
self.args = args
self.busy = False
self.nb_received_tokens = 0
self.config_file_path = config.file_path
self.cancel_gen = False
if self.config.auto_update:
if self.check_update_():
ASCIIColors.info("New version found. Updating!")
self.run_update_script()
# Keeping track of current discussion and message
self._current_user_message_id = 0
self._current_ai_message_id = 0
self._message_id = 0
# migrate old databases to new ones:
databases_path = self.lollms_paths.personal_path/"databases"
if databases_path.exists() and len([f for f in databases_path.iterdir() if f.suffix==".db"])>0:
if yes_or_no_input("Old databases have been spotted on your system. Do you want me to migrate them to the new format?"):
databases_found = False
for database_path in databases_path.iterdir():
if database_path.suffix==".db":
ASCIIColors.red(f"Found old discussion database format : {database_path}")
ASCIIColors.red(f"Migrating to new format... ",end="")
new_db_path = self.lollms_paths.personal_discussions_path/database_path.stem
new_db_path.mkdir(exist_ok=True, parents=True)
try:
shutil.copy(database_path,new_db_path/"database.db")
ASCIIColors.green("ok")
databases_found = True
except Exception as ex:
ASCIIColors.warning(ex)
if databases_found:
ASCIIColors.green(f"Databases are migrated from {databases_path} to the new {self.lollms_paths.personal_discussions_path} path")
if yes_or_no_input("Databases are migrated to the new format. Do you want me to delete the previous version?"):
for database_path in databases_path.iterdir():
if database_path.suffix==".db":
ASCIIColors.red(f"Deleting {database_path}")
database_path.unlink()
if config["discussion_db_name"].endswith(".db"):
config["discussion_db_name"]=config["discussion_db_name"].replace(".db","")
config.save_config()
self.discussion_db_name = config["discussion_db_name"]
# Create database object
self.db = DiscussionsDB(self, self.lollms_paths, self.discussion_db_name)
# If the database is empty, populate it with tables
ASCIIColors.info("Checking discussions database... ",end="")
self.db.create_tables()
self.db.add_missing_columns()
ASCIIColors.success("ok")
# This is used to keep track of messages
self.download_infos={}
# Define a WebSocket event handler
@sio.event
async def connect(sid, environ):
self.session.add_client(sid, sid, self.db.load_last_discussion(), self.db)
await self.sio.emit('connected', to=sid)
ASCIIColors.success(f'Client {sid} connected')
@sio.event
def disconnect(sid):
try:
self.session.add_client(sid, sid, self.db.load_last_discussion(), self.db)
if self.session.get_client(sid).processing:
self.session.get_client(sid).schedule_for_deletion=True
else:
# Clients are now kept forever
pass# self.session.remove_client(sid, sid)
except Exception as ex:
pass
ASCIIColors.error(f'Client {sid} disconnected')
# generation status
self.generating=False
ASCIIColors.blue(f"Your personal data is stored here :",end="")
ASCIIColors.green(f"{self.lollms_paths.personal_path}")
self.start_servers()
def get_uploads_path(self, client_id):
return self.session.get_client(client_id).discussion_path # self.db.discussion_db_path/f'{["discussion"].discussion_id}'
# Other methods and properties of the LoLLMSWebUI singleton class
def check_module_update_(self, repo_path, branch_name="main"):
try:
# Open the repository
ASCIIColors.yellow(f"Checking for updates from {repo_path}")
repo = git.Repo(repo_path)
# Fetch updates from the remote for the specified branch
repo.remotes.origin.fetch(refspec=f"refs/heads/{branch_name}:refs/remotes/origin/{branch_name}")
# Compare the local and remote commit IDs for the specified branch
local_commit = repo.head.commit
remote_commit = repo.remotes.origin.refs[branch_name].commit
# Check if the local branch is behind the remote branch
is_behind = repo.is_ancestor(local_commit, remote_commit) and local_commit!= remote_commit
ASCIIColors.yellow(f"update availability: {is_behind}")
# Return True if the local branch is behind the remote branch
return is_behind
except Exception as e:
# Handle any errors that may occur during the fetch process
# trace_exception(e)
return False
def check_update_(self, branch_name="main"):
try:
# Open the repository
repo_path = str(Path(__file__).parent/"lollms_core")
if self.check_module_update_(repo_path, branch_name):
return True
repo_path = str(Path(__file__).parent)
if self.check_module_update_(repo_path, branch_name):
return True
return False
except Exception as e:
# Handle any errors that may occur during the fetch process
# trace_exception(e)
return False
def run_update_script(self, args=None):
# deactivate trust store for github and pip package install
if 'REQUESTS_CA_BUNDLE' in os.environ:
del os.environ['REQUESTS_CA_BUNDLE']
update_script = Path(__file__).parent/"update_script.py"
# Convert Namespace object to a dictionary
if args:
args_dict = vars(args)
else:
args_dict = {}
# Filter out any key-value pairs where the value is None
valid_args = {key: value for key, value in args_dict.items() if value is not None}
# Save the arguments to a temporary file
temp_file = Path(__file__).parent/"temp_args.txt"
with open(temp_file, "w") as file:
# Convert the valid_args dictionary to a string in the format "key1 value1 key2 value2 ..."
arg_string = " ".join([f"--{key} {value}" for key, value in valid_args.items()])
file.write(arg_string)
os.system(f"python {update_script}")
sys.exit(0)
def run_restart_script(self, args):
restart_script = Path(__file__).parent/"restart_script.py"
# Convert Namespace object to a dictionary
args_dict = vars(args)
# Filter out any key-value pairs where the value is None
valid_args = {key: value for key, value in args_dict.items() if value is not None}
# Save the arguments to a temporary file
temp_file = Path(__file__).parent/"temp_args.txt"
with open(temp_file, "w") as file:
# Convert the valid_args dictionary to a string in the format "key1 value1 key2 value2 ..."
arg_string = " ".join([f"--{key} {value}" for key, value in valid_args.items()])
file.write(arg_string)
os.system(f"python {restart_script}")
sys.exit(0)
def audio_callback(self, text):
if self.summoned:
client_id = 0
self.cancel_gen = False
client = self.session.get_client(client_id)
client.generated_text=""
client.cancel_generation=False
client.continuing=False
client.first_chunk=True
if not self.model:
ASCIIColors.error("Model not selected. Please select a model")
self.error("Model not selected. Please select a model", client_id=client_id)
return
if not self.busy:
if client.discussion is None:
if self.db.does_last_discussion_have_messages():
client.discussion = self.db.create_discussion()
else:
client.discussion = self.db.load_last_discussion()
prompt = text
try:
nb_tokens = len(self.model.tokenize(prompt))
except:
nb_tokens = None
message = client.discussion.add_message(
message_type = MSG_TYPE.MSG_TYPE_CONTENT.value,
sender_type = SENDER_TYPES.SENDER_TYPES_USER.value,
sender = self.config.user_name.strip() if self.config.use_user_name_in_discussions else self.config.user_name,
content = prompt,
metadata = None,
parent_message_id=self.message_id,
nb_tokens=nb_tokens
)
ASCIIColors.green("Starting message generation by "+self.personality.name)
client.generation_thread = threading.Thread(target=self.start_message_generation, args=(message, message.id, client_id))
client.generation_thread.start()
self.sio.sleep(0.01)
ASCIIColors.info("Started generation task")
self.busy=True
#tpe = threading.Thread(target=self.start_message_generation, args=(message, message_id, client_id))
#tpe.start()
else:
self.error("I am busy. Come back later.", client_id=client_id)
else:
if "lollms" in text.lower():
self.summoned = True
# def scrape_and_save(self, url, file_path):
# # Send a GET request to the URL
# response = requests.get(url)
# # Parse the HTML content using BeautifulSoup
# soup = BeautifulSoup(response.content, 'html.parser')
# # Find all the text content in the webpage
# text_content = soup.get_text()
# # Remove extra returns and spaces
# text_content = ' '.join(text_content.split())
# # Save the text content as a text file
# with open(file_path, 'w', encoding="utf-8") as file:
# file.write(text_content)
# self.info(f"Webpage content saved to {file_path}")
def rebuild_personalities(self, reload_all=False):
if reload_all:
self.mounted_personalities=[]
loaded = self.mounted_personalities
loaded_names = [f"{p.category}/{p.personality_folder_name}" for p in loaded if p is not None]
mounted_personalities=[]
ASCIIColors.success(f" ╔══════════════════════════════════════════════════╗ ")
ASCIIColors.success(f" ║ Building mounted Personalities ║ ")
ASCIIColors.success(f" ╚══════════════════════════════════════════════════╝ ")
to_remove=[]
for i,personality in enumerate(self.config['personalities']):
if i==self.config["active_personality_id"]:
ASCIIColors.red("*", end="")
ASCIIColors.green(f" {personality}")
else:
ASCIIColors.yellow(f" {personality}")
if personality in loaded_names:
mounted_personalities.append(loaded[loaded_names.index(personality)])
else:
personality_path = f"{personality}"
try:
personality = AIPersonality(personality_path,
self.lollms_paths,
self.config,
model=self.model,
app=self,
selected_language=self.config.current_language,
run_scripts=True)
mounted_personalities.append(personality)
if self.config.auto_read and len(personality.audio_samples)>0:
try:
from lollms.services.tts.xtts.lollms_xtts import LollmsXTTS
if self.tts is None:
voice=self.config.xtts_current_voice
if voice!="main_voice":
voices_folder = self.lollms_paths.custom_voices_path
else:
voices_folder = Path(__file__).parent.parent.parent/"services/xtts/voices"
self.tts = LollmsXTTS(
self,
voices_folders=[voices_folder, Path(__file__).parent.parent.parent/"services/xtts/voices"],
freq=self.config.xtts_freq
)
except Exception as ex:
trace_exception(ex)
self.warning(f"Personality {personality.name} request using custom voice but couldn't load XTTS")
except Exception as ex:
ASCIIColors.error(f"Personality file not found or is corrupted ({personality_path}).\nReturned the following exception:{ex}\nPlease verify that the personality you have selected exists or select another personality. Some updates may lead to change in personality name or category, so check the personality selection in settings to be sure.")
ASCIIColors.info("Trying to force reinstall")
if self.config["debug"]:
print(ex)
try:
personality = AIPersonality(
personality_path,
self.lollms_paths,
self.config,
self.model,
app = self,
run_scripts=True,
selected_language= self.config.current_language,
installation_option=InstallOption.FORCE_INSTALL)
mounted_personalities.append(personality)
if personality.processor:
personality.processor.mounted()
except Exception as ex:
ASCIIColors.error(f"Couldn't load personality at {personality_path}")
trace_exception(ex)
ASCIIColors.info(f"Unmounting personality")
to_remove.append(i)
personality = AIPersonality(None,
self.lollms_paths,
self.config,
self.model,
app=self,
run_scripts=True,
installation_option=InstallOption.FORCE_INSTALL)
mounted_personalities.append(personality)
if personality.processor:
personality.processor.mounted()
ASCIIColors.info("Reverted to default personality")
if self.config["active_personality_id"]>=0 and self.config["active_personality_id"]<len(self.config["personalities"]):
ASCIIColors.success(f'selected model : {self.config["personalities"][self.config["active_personality_id"]]}')
else:
ASCIIColors.warning('An error was encountered while trying to mount personality')
ASCIIColors.success(f" ╔══════════════════════════════════════════════════╗ ")
ASCIIColors.success(f" ║ Done ║ ")
ASCIIColors.success(f" ╚══════════════════════════════════════════════════╝ ")
# Sort the indices in descending order to ensure correct removal
to_remove.sort(reverse=True)
# Remove elements from the list based on the indices
for index in to_remove:
if 0 <= index < len(mounted_personalities):
mounted_personalities.pop(index)
self.config["personalities"].pop(index)
ASCIIColors.info(f"removed personality {personality_path}")
if self.config["active_personality_id"]>=len(self.config["personalities"]):
self.config["active_personality_id"]=0
return mounted_personalities
# ================================== LOLLMSApp
#properties
@property
def message_id(self):
return self._message_id
@message_id.setter
def message_id(self, id):
self._message_id=id
@property
def current_user_message_id(self):
return self._current_user_message_id
@current_user_message_id.setter
def current_user_message_id(self, id):
self._current_user_message_id=id
self._message_id = id
@property
def current_ai_message_id(self):
return self._current_ai_message_id
@current_ai_message_id.setter
def current_ai_message_id(self, id):
self._current_ai_message_id=id
self._message_id = id
def download_file(self, url, installation_path, callback=None):
"""
Downloads a file from a URL, reports the download progress using a callback function, and displays a progress bar.
Args:
url (str): The URL of the file to download.
installation_path (str): The path where the file should be saved.
callback (function, optional): A callback function to be called during the download
with the progress percentage as an argument. Defaults to None.
"""
try:
response = requests.get(url, stream=True)
# Get the file size from the response headers
total_size = int(response.headers.get('content-length', 0))
with open(installation_path, 'wb') as file:
downloaded_size = 0
with tqdm(total=total_size, unit='B', unit_scale=True, ncols=80) as progress_bar:
for chunk in response.iter_content(chunk_size=8192):
if chunk:
file.write(chunk)
downloaded_size += len(chunk)
if callback is not None:
callback(downloaded_size, total_size)
progress_bar.update(len(chunk))
if callback is not None:
callback(total_size, total_size)
print("File downloaded successfully")
except Exception as e:
print("Couldn't download file:", str(e))
def clean_string(self, input_string):
# Remove extra spaces by replacing multiple spaces with a single space
#cleaned_string = re.sub(r'\s+', ' ', input_string)
# Remove extra line breaks by replacing multiple consecutive line breaks with a single line break
cleaned_string = re.sub(r'\n\s*\n', '\n', input_string)
# Create a string containing all punctuation characters
punctuation_chars = string.punctuation
# Define a regular expression pattern to match and remove non-alphanumeric characters
#pattern = f'[^a-zA-Z0-9\s{re.escape(punctuation_chars)}]' # This pattern matches any character that is not a letter, digit, space, or punctuation
pattern = f'[^a-zA-Z0-9\u00C0-\u017F\s{re.escape(punctuation_chars)}]'
# Use re.sub to replace the matched characters with an empty string
cleaned_string = re.sub(pattern, '', cleaned_string)
return cleaned_string
def make_discussion_title(self, discussion, client_id=None):
"""
Builds a title for a discussion
"""
# Get the list of messages
messages = discussion.get_messages()
discussion_messages = f"{self.start_header_id_template}instruction{self.end_header_id_template}Create a short title to this discussion\nYour response should only contain the title without any comments.\n"
discussion_title = f"\n{self.start_header_id_template}Discussion title{self.end_header_id_template}"
available_space = self.config.ctx_size - 150 - len(self.model.tokenize(discussion_messages))- len(self.model.tokenize(discussion_title))
# Initialize a list to store the full messages
full_message_list = []
# Accumulate messages until the cumulative number of tokens exceeds available_space
tokens_accumulated = 0
# Accumulate messages starting from message_index
for message in messages:
# Check if the message content is not empty and visible to the AI
if message.content != '' and (
message.message_type <= MSG_OPERATION_TYPE.MSG_OPERATION_TYPE_SET_CONTENT_INVISIBLE_TO_USER.value and message.message_type != MSG_OPERATION_TYPE.MSG_OPERATION_TYPE_SET_CONTENT_INVISIBLE_TO_AI.value):
# Tokenize the message content
message_tokenized = self.model.tokenize(
"\n" + self.config.discussion_prompt_separator + message.sender + ": " + message.content.strip())
# Check if adding the message will exceed the available space
if tokens_accumulated + len(message_tokenized) > available_space:
break
# Add the tokenized message to the full_message_list
full_message_list.insert(0, message_tokenized)
# Update the cumulative number of tokens
tokens_accumulated += len(message_tokenized)
# Build the final discussion messages by detokenizing the full_message_list
for message_tokens in full_message_list:
discussion_messages += self.model.detokenize(message_tokens)
discussion_messages += discussion_title
title = [""]
def receive(
chunk:str,
message_type:MSG_OPERATION_TYPE
):
if chunk:
title[0] += chunk
antiprompt = self.personality.detect_antiprompt(title[0])
if antiprompt:
ASCIIColors.warning(f"\n{antiprompt} detected. Stopping generation")
title[0] = self.remove_text_from_string(title[0],antiprompt)
return False
else:
return True
self._generate(discussion_messages, 150, client_id, receive)
ASCIIColors.info(title[0])
return title[0]
def get_discussion_to(self, client_id, message_id=-1):
messages = self.session.get_client(client_id).discussion.get_messages()
full_message_list = []
ump = f"{self.start_header_id_template}{self.config.user_name.strip()if self.config.use_user_name_in_discussions else self.personality.user_message_prefix}{self.end_header_id_template}"
for message in messages:
if message["id"]<= message_id or message_id==-1:
if message["type"]!=MSG_OPERATION_TYPE.MSG_OPERATION_TYPE_SET_CONTENT_INVISIBLE_TO_USER:
if message["sender"]==self.personality.name:
full_message_list.append(self.config.discussion_prompt_separator+self.personality.ai_message_prefix+message["content"])
else:
full_message_list.append(ump + message["content"])
link_text = "\n"# self.personality.link_text
if len(full_message_list) > self.config["nb_messages_to_remember"]:
discussion_messages = self.config.discussion_prompt_separator + self.personality.personality_conditioning+ link_text.join(full_message_list[-self.config["nb_messages_to_remember"]:])
else:
discussion_messages = self.config.discussion_prompt_separator + self.personality.personality_conditioning+ link_text.join(full_message_list)
return discussion_messages # Removes the last return
def set_message_content(self, full_text:str, callback: Callable[[str | list | None, MSG_OPERATION_TYPE, str, Any | None], bool]|None=None, client_id=0):
"""This sends full text to front end
Args:
step_text (dict): The step text
callback (callable, optional): A callable with this signature (str, MSG_TYPE) to send the text to. Defaults to None.
"""
if not callback:
callback = partial(self.process_data,client_id = client_id)
if callback:
callback(full_text, MSG_OPERATION_TYPE.MSG_OPERATION_TYPE_SET_CONTENT)
def emit_socket_io_info(self, name, data, client_id):
run_async(partial(self.sio.emit,name, data, to=client_id))
def notify(
self,
content,
notification_type:NotificationType=NotificationType.NOTIF_SUCCESS,
duration:int=4,
client_id=None,
display_type:NotificationDisplayType=NotificationDisplayType.TOAST,
verbose:bool|None=None,
):
if verbose is None:
verbose = self.verbose
run_async(partial(self.sio.emit,'notification', {
'content': content,
'notification_type': notification_type.value,
"duration": duration,
'display_type':display_type.value
}, to=client_id
)
)
if verbose:
if notification_type==NotificationType.NOTIF_SUCCESS:
ASCIIColors.success(content)
elif notification_type==NotificationType.NOTIF_INFO:
ASCIIColors.info(content)
elif notification_type==NotificationType.NOTIF_WARNING:
ASCIIColors.warning(content)
else:
ASCIIColors.red(content)
def refresh_files(self, client_id=None):
run_async(partial(self.sio.emit,'refresh_files', to=client_id
)
)
def new_message(self,
client_id,
sender=None,
content="",
message_type:MSG_OPERATION_TYPE=MSG_OPERATION_TYPE.MSG_OPERATION_TYPE_SET_CONTENT,
sender_type:SENDER_TYPES=SENDER_TYPES.SENDER_TYPES_AI,
open=False
):
client = self.session.get_client(client_id)
#self.close_message(client_id)
if sender==None:
sender= self.personality.name
msg = client.discussion.add_message(
message_type = message_type.value,
sender_type = sender_type.value,
sender = sender,
content = content,
steps = [],
metadata = None,
ui = None,
rank = 0,
parent_message_id = client.discussion.current_message.id if client.discussion.current_message is not None else 0,
binding = self.config["binding_name"],
model = self.config["model_name"],
personality = self.config["personalities"][self.config["active_personality_id"]],
created_at = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
) # first the content is empty, but we'll fill it at the end
run_async(partial(
self.sio.emit,'new_message',
{
"sender": sender,
"message_type": message_type.value,
"sender_type": SENDER_TYPES.SENDER_TYPES_AI.value,
"content": content,
"metadata": None,
"ui": None,
"id": msg.id,
"parent_message_id": msg.parent_message_id,
'binding': self.binding.binding_folder_name,
'model' : self.model.model_name,
'personality':self.personality.name,
'created_at': client.discussion.current_message.created_at,
'started_generating_at': client.discussion.current_message.started_generating_at,
'finished_generating_at': client.discussion.current_message.finished_generating_at,
'nb_tokens': client.discussion.current_message.nb_tokens,
'open': open
}, to=client_id
)
)
def new_block( self,
client_id,
sender=None,
content="",
parameters=None,
metadata=None,
ui=None,
message_type:MSG_OPERATION_TYPE=MSG_OPERATION_TYPE.MSG_OPERATION_TYPE_SET_CONTENT,
sender_type:SENDER_TYPES=SENDER_TYPES.SENDER_TYPES_AI,
open=False
):
# like new_message but without adding the information to the database
client = self.session.get_client(client_id)
run_async(partial(
self.sio.emit,'new_message',
{
"sender": sender,
"message_type": message_type.value,
"sender_type": SENDER_TYPES.SENDER_TYPES_AI.value,
"content": content,
"parameters": parameters,
"metadata": metadata,
"ui": ui,
"id": 0,
"parent_message_id": 0,
'binding': self.binding.binding_folder_name,
'model' : self.model.model_name,
'personality':self.personality.name,
'created_at': client.discussion.current_message.created_at,
'started_generating_at': client.discussion.current_message.started_generating_at,
'finished_generating_at': client.discussion.current_message.finished_generating_at,
'nb_tokens': client.discussion.current_message.nb_tokens,
'open': open
}, to=client_id
)
)
def send_refresh(self, client_id):
client = self.session.get_client(client_id)
run_async(
partial(self.sio.emit,'update_message', {
"sender": client.discussion.current_message.sender,
'id':client.discussion.current_message.id,
'content': client.discussion.current_message.content,
'discussion_id':client.discussion.discussion_id,
'operation_type': MSG_OPERATION_TYPE.MSG_OPERATION_TYPE_SET_CONTENT.value,
'message_type': client.discussion.current_message.message_type,
'created_at':client.discussion.current_message.created_at,
'started_generating_at': client.discussion.current_message.started_generating_at,
'finished_generating_at': client.discussion.current_message.finished_generating_at,
'nb_tokens': client.discussion.current_message.nb_tokens,
'binding': self.binding.binding_folder_name,
'model' : self.model.model_name,
'personality':self.personality.name,
}, to=client_id
)
)
def update_message(self, client_id, chunk,
parameters=None,
metadata=[],
ui=None,
operation_type:MSG_OPERATION_TYPE=None
):
client = self.session.get_client(client_id)
client.discussion.current_message.finished_generating_at=datetime.now().strftime('%Y-%m-%d %H:%M:%S')
client.discussion.current_message.nb_tokens = self.nb_received_tokens
mtdt = json.dumps(metadata, indent=4) if metadata is not None and type(metadata)== list else metadata
if self.nb_received_tokens==1:
client.discussion.current_message.started_generating_at=datetime.now().strftime('%Y-%m-%d %H:%M:%S')
self.update_message_step(client_id, "🔥 warming up ...",MSG_OPERATION_TYPE.MSG_OPERATION_TYPE_STEP_END_SUCCESS)
self.update_message_step(client_id, "✍ generating ...",MSG_OPERATION_TYPE.MSG_OPERATION_TYPE_STEP_END_SUCCESS)
run_async(
partial(self.sio.emit,'update_message', {
"sender": self.personality.name,
'id':client.discussion.current_message.id,
'content': chunk,
'ui': client.discussion.current_message.ui if ui is None else ui,
'discussion_id':client.discussion.discussion_id,
'operation_type': operation_type.value if operation_type is not None else MSG_OPERATION_TYPE.MSG_OPERATION_TYPE_ADD_CHUNK.value if self.nb_received_tokens>1 else MSG_OPERATION_TYPE.MSG_OPERATION_TYPE_SET_CONTENT.value,
'message_type': MSG_TYPE.MSG_TYPE_CONTENT.value,
'created_at':client.discussion.current_message.created_at,
'started_generating_at': client.discussion.current_message.started_generating_at,
'finished_generating_at': client.discussion.current_message.finished_generating_at,
'nb_tokens': client.discussion.current_message.nb_tokens,
'parameters':parameters,
'metadata':metadata,
'binding': self.binding.binding_folder_name,
'model' : self.model.model_name,
'personality':self.personality.name,
}, to=client_id
)
)
if operation_type and operation_type.value < MSG_OPERATION_TYPE.MSG_OPERATION_TYPE_INFO.value:
client.discussion.update_message(client.generated_text, new_metadata=mtdt, new_ui=ui, started_generating_at=client.discussion.current_message.started_generating_at, nb_tokens=client.discussion.current_message.nb_tokens)
def update_message_content(self, client_id, chunk, operation_type:MSG_OPERATION_TYPE=MSG_OPERATION_TYPE.MSG_OPERATION_TYPE_SET_CONTENT, message_type: MSG_TYPE=None):
client = self.session.get_client(client_id)
client.discussion.current_message.finished_generating_at=datetime.now().strftime('%Y-%m-%d %H:%M:%S')
client.discussion.current_message.nb_tokens = self.nb_received_tokens
if self.nb_received_tokens==1:
client.discussion.current_message.started_generating_at=datetime.now().strftime('%Y-%m-%d %H:%M:%S')
run_async(
partial(self.sio.emit,'update_message', {
"sender": self.personality.name,
'id':client.discussion.current_message.id,
'content': chunk,
'discussion_id':client.discussion.discussion_id,
'operation_type': operation_type.value,
'message_type': client.discussion.current_message.message_type if message_type is None else message_type,
'created_at':client.discussion.current_message.created_at,
'started_generating_at': client.discussion.current_message.started_generating_at,
'finished_generating_at': client.discussion.current_message.finished_generating_at,
'nb_tokens': client.discussion.current_message.nb_tokens,
'binding': self.binding.binding_folder_name,
'model' : self.model.model_name,
'personality':self.personality.name,
}, to=client_id
)
)
client.discussion.update_message_content(client.generated_text, started_generating_at=client.discussion.current_message.started_generating_at, nb_tokens=client.discussion.current_message.nb_tokens)
def update_message_step(self, client_id, step_text, msg_operation_type:MSG_OPERATION_TYPE=None):
client = self.session.get_client(client_id)
if msg_operation_type == MSG_OPERATION_TYPE.MSG_OPERATION_TYPE_STEP:
client.discussion.current_message.add_step(step_text,"instant",True, True)
elif msg_operation_type == MSG_OPERATION_TYPE.MSG_OPERATION_TYPE_STEP_START:
client.discussion.current_message.add_step(step_text,"start_end",True,False)
elif msg_operation_type == MSG_OPERATION_TYPE.MSG_OPERATION_TYPE_STEP_END_SUCCESS:
client.discussion.current_message.add_step(step_text,"start_end",True, True)
elif msg_operation_type == MSG_OPERATION_TYPE.MSG_OPERATION_TYPE_STEP_END_FAILURE:
client.discussion.current_message.add_step(step_text,"start_end",False, True)
run_async(
partial(self.sio.emit,'update_message', {
'id':client.discussion.current_message.id,
'discussion_id':client.discussion.discussion_id,
'operation_type': msg_operation_type.value,
'steps': client.discussion.current_message.steps,
}, to=client_id
)
)
def update_message_metadata(self, client_id, metadata):
client = self.session.get_client(client_id)
md = json.dumps(metadata) if type(metadata)==dict or type(metadata)==list else metadata
run_async(
partial(self.sio.emit,'update_message', {
"sender": self.personality.name,
'id':client.discussion.current_message.id,
'metadata': md,
'discussion_id':client.discussion.discussion_id,
'operation_type': MSG_OPERATION_TYPE.MSG_OPERATION_TYPE_JSON_INFOS.value,
}, to=client_id
)
)
client.discussion.update_message_metadata(metadata)
def update_message_ui(self, client_id, ui):
client = self.session.get_client(client_id)
run_async(
partial(self.sio.emit,'update_message', {
"sender": self.personality.name,
'id':client.discussion.current_message.id,
'ui': ui,
'discussion_id':client.discussion.discussion_id,
'operation_type': MSG_OPERATION_TYPE.MSG_OPERATION_TYPE_UI.value,
}, to=client_id
)
)
client.discussion.update_message_ui(ui)
def close_message(self, client_id):
client = self.session.get_client(client_id)
for msg in client.discussion.messages:
if msg.steps is not None:
for step in msg.steps:
step["done"]=True
if not client.discussion:
return
#fix halucination
if len(client.generated_text)>0 and len(self.start_header_id_template)>0:
client.generated_text=client.generated_text.split(f"{self.start_header_id_template}")[0]
# Send final message
client.discussion.current_message.finished_generating_at=datetime.now().strftime('%Y-%m-%d %H:%M:%S')
try:
client.discussion.current_message.nb_tokens = len(self.model.tokenize(client.generated_text))
except:
client.discussion.current_message.nb_tokens = None
run_async(
partial(self.sio.emit,'close_message', {
"sender": self.personality.name,
"id": client.discussion.current_message.id,
"content":client.generated_text,
'binding': self.binding.binding_folder_name,
'model' : self.model.model_name,
'personality':self.personality.name,
'created_at': client.discussion.current_message.created_at,
'started_generating_at': client.discussion.current_message.started_generating_at,
'finished_generating_at': client.discussion.current_message.finished_generating_at,
'nb_tokens': client.discussion.current_message.nb_tokens,
}, to=client_id
)
)
def process_data(
self,
data:str|list|None,
operation_type:MSG_OPERATION_TYPE,
client_id:str=0,
personality:AIPersonality=None
):
"""
Processes a data of generated text
"""