2023-04-15 11:30:08 +00:00
######
2023-06-08 06:58:02 +00:00
# Project : lollms-webui
2023-04-15 11:30:08 +00:00
# File : api.py
# Author : ParisNeo with the help of the community
# Supported by Nomic-AI
2023-05-21 20:46:02 +00:00
# license : Apache 2.0
2023-04-15 11:30:08 +00:00
# Description :
2023-06-08 06:58:02 +00:00
# A simple api to communicate with lollms-webui and its models.
2023-04-15 11:30:08 +00:00
######
from datetime import datetime
2023-05-24 15:28:22 +00:00
from api . db import DiscussionsDB
2023-06-08 06:58:02 +00:00
from api . helpers import compare_lists
2023-04-23 18:28:24 +00:00
from pathlib import Path
import importlib
2023-06-09 23:37:50 +00:00
from lollms import AIPersonality , MSG_TYPE
2023-06-04 23:21:12 +00:00
from lollms . binding import BindingConfig
2023-06-09 23:37:50 +00:00
from lollms . paths import lollms_path , lollms_personal_configuration_path , lollms_personal_path , lollms_personal_models_path , lollms_bindings_zoo_path , lollms_personalities_zoo_path , lollms_default_cfg_path
2023-05-13 22:24:26 +00:00
import multiprocessing as mp
import threading
import time
import requests
2023-05-14 11:33:45 +00:00
from tqdm import tqdm
2023-05-21 23:29:20 +00:00
import traceback
2023-05-29 20:03:12 +00:00
import sys
2023-04-23 18:28:24 +00:00
2023-04-20 17:30:03 +00:00
__author__ = " parisneo "
2023-06-08 06:58:02 +00:00
__github__ = " https://github.com/ParisNeo/lollms-webui "
2023-04-20 17:30:03 +00:00
__copyright__ = " Copyright 2023, "
__license__ = " Apache 2.0 "
2023-04-15 11:30:08 +00:00
2023-05-13 22:24:26 +00:00
2023-05-17 15:38:40 +00:00
import subprocess
import pkg_resources
# ===========================================================
# Manage automatic install scripts
def is_package_installed ( package_name ) :
try :
dist = pkg_resources . get_distribution ( package_name )
return True
except pkg_resources . DistributionNotFound :
return False
def install_package ( package_name ) :
try :
# Check if the package is already installed
__import__ ( package_name )
print ( f " { package_name } is already installed. " )
except ImportError :
print ( f " { package_name } is not installed. Installing... " )
# Install the package using pip
subprocess . check_call ( [ " pip " , " install " , package_name ] )
print ( f " { package_name } has been successfully installed. " )
def parse_requirements_file ( requirements_path ) :
with open ( requirements_path , ' r ' ) as f :
for line in f :
line = line . strip ( )
if not line or line . startswith ( ' # ' ) :
# Skip empty and commented lines
continue
package_name , _ , version_specifier = line . partition ( ' == ' )
package_name , _ , version_specifier = line . partition ( ' >= ' )
if is_package_installed ( package_name ) :
# The package is already installed
print ( f " { package_name } is already installed. " )
else :
# The package is not installed, install it
if version_specifier :
install_package ( f " { package_name } { version_specifier } " )
else :
install_package ( package_name )
# ===========================================================
2023-05-13 22:24:26 +00:00
class ModelProcess :
2023-06-04 23:21:12 +00:00
def __init__ ( self , config : BindingConfig = None ) :
2023-05-13 22:24:26 +00:00
self . config = config
self . generate_queue = mp . Queue ( )
self . generation_queue = mp . Queue ( )
self . cancel_queue = mp . Queue ( maxsize = 1 )
self . clear_queue_queue = mp . Queue ( maxsize = 1 )
self . set_config_queue = mp . Queue ( maxsize = 1 )
2023-05-18 18:00:48 +00:00
self . set_config_result_queue = mp . Queue ( maxsize = 1 )
2023-05-28 18:36:00 +00:00
2023-06-09 23:37:50 +00:00
self . models_path = lollms_personal_models_path
2023-06-04 23:21:12 +00:00
2023-05-13 22:24:26 +00:00
self . process = None
2023-05-28 18:36:00 +00:00
# Create synchronization objects
self . start_signal = mp . Event ( )
self . completion_signal = mp . Event ( )
2023-05-14 09:10:49 +00:00
self . model_ready = mp . Value ( ' i ' , 0 )
2023-05-26 14:22:02 +00:00
self . curent_text = " "
2023-05-13 22:24:26 +00:00
self . ready = False
2023-05-18 22:20:05 +00:00
self . id = 0
self . n_predict = 2048
2023-05-18 18:00:48 +00:00
self . reset_config_result ( )
def reset_config_result ( self ) :
self . _set_config_result = {
' status ' : ' succeeded ' ,
2023-06-07 07:39:38 +00:00
' binding_status ' : True ,
' model_status ' : True ,
2023-06-08 06:58:02 +00:00
' personalities_status ' : True ,
2023-05-18 18:00:48 +00:00
' errors ' : [ ]
}
2023-05-28 18:36:00 +00:00
def remove_text_from_string ( self , string , text_to_find ) :
"""
Removes everything from the first occurrence of the specified text in the string ( case - insensitive ) .
Parameters :
string ( str ) : The original string .
text_to_find ( str ) : The text to find in the string .
Returns :
str : The updated string .
"""
index = string . lower ( ) . find ( text_to_find . lower ( ) )
if index != - 1 :
string = string [ : index ]
return string
2023-05-25 21:24:14 +00:00
def load_binding ( self , binding_name : str , install = False ) :
2023-05-23 18:03:54 +00:00
if install :
2023-05-25 21:24:14 +00:00
print ( f " Loading binding { binding_name } install ON " )
2023-05-23 18:03:54 +00:00
else :
2023-05-25 21:24:14 +00:00
print ( f " Loading binding : { binding_name } install is off " )
2023-06-04 23:21:12 +00:00
binding_path = lollms_path / " bindings_zoo " / binding_name
2023-05-21 19:54:56 +00:00
if install :
# first find out if there is a requirements.txt file
install_file_name = " install.py "
2023-05-25 21:24:14 +00:00
install_script_path = binding_path / install_file_name
2023-05-21 19:54:56 +00:00
if install_script_path . exists ( ) :
module_name = install_file_name [ : - 3 ] # Remove the ".py" extension
module_spec = importlib . util . spec_from_file_location ( module_name , str ( install_script_path ) )
module = importlib . util . module_from_spec ( module_spec )
module_spec . loader . exec_module ( module )
if hasattr ( module , " Install " ) :
2023-05-22 06:52:48 +00:00
module . Install ( self )
2023-05-13 22:24:26 +00:00
# define the full absolute path to the module
2023-05-25 21:24:14 +00:00
absolute_path = binding_path . resolve ( )
2023-05-13 22:24:26 +00:00
# infer the module name from the file path
2023-05-25 21:24:14 +00:00
module_name = binding_path . stem
2023-05-13 22:24:26 +00:00
# use importlib to load the module from the file path
loader = importlib . machinery . SourceFileLoader ( module_name , str ( absolute_path / " __init__.py " ) )
2023-05-25 21:24:14 +00:00
binding_module = loader . load_module ( )
binding_class = getattr ( binding_module , binding_module . binding_name )
return binding_class
2023-05-13 22:24:26 +00:00
def start ( self ) :
if self . process is None :
self . process = mp . Process ( target = self . _run )
self . process . start ( )
def stop ( self ) :
if self . process is not None :
self . generate_queue . put ( None )
self . process . join ( )
self . process = None
2023-05-25 21:24:14 +00:00
def set_binding ( self , binding_path ) :
self . binding = binding_path
2023-05-13 22:24:26 +00:00
def set_model ( self , model_path ) :
self . model = model_path
def set_config ( self , config ) :
2023-05-24 14:37:57 +00:00
try :
self . set_config_result_queue . get_nowait ( )
except :
pass
2023-05-13 22:24:26 +00:00
self . set_config_queue . put ( config )
2023-05-18 18:00:48 +00:00
# Wait for it t o be consumed
while self . set_config_result_queue . empty ( ) :
2023-05-26 14:22:02 +00:00
time . sleep ( 0.1 )
2023-05-18 18:00:48 +00:00
return self . set_config_result_queue . get ( )
2023-05-13 22:24:26 +00:00
2023-05-19 01:32:38 +00:00
def generate ( self , full_prompt , prompt , id , n_predict ) :
2023-05-28 18:36:00 +00:00
self . start_signal . clear ( )
2023-05-28 23:25:25 +00:00
self . completion_signal . clear ( )
2023-05-19 01:32:38 +00:00
self . generate_queue . put ( ( full_prompt , prompt , id , n_predict ) )
2023-05-13 22:24:26 +00:00
def cancel_generation ( self ) :
2023-05-28 18:36:00 +00:00
self . completion_signal . set ( )
2023-05-13 22:24:26 +00:00
self . cancel_queue . put ( ( ' cancel ' , ) )
2023-05-28 18:36:00 +00:00
print ( " Canel request received " )
2023-05-13 22:24:26 +00:00
def clear_queue ( self ) :
self . clear_queue_queue . put ( ( ' clear_queue ' , ) )
2023-05-25 21:24:14 +00:00
def rebuild_binding ( self , config ) :
2023-05-13 22:24:26 +00:00
try :
2023-05-25 21:24:14 +00:00
print ( " ******************* Building Binding from main Process ************************* " )
2023-06-04 23:21:12 +00:00
binding = self . load_binding ( config [ " binding_name " ] , install = True )
2023-05-25 21:24:14 +00:00
print ( " Binding loaded successfully " )
2023-05-13 22:24:26 +00:00
except Exception as ex :
2023-05-25 21:24:14 +00:00
print ( " Couldn ' t build binding. " )
2023-05-13 22:24:26 +00:00
print ( ex )
2023-05-25 21:24:14 +00:00
binding = None
return binding
2023-05-13 22:24:26 +00:00
def _rebuild_model ( self ) :
try :
2023-05-24 14:08:42 +00:00
self . reset_config_result ( )
2023-05-25 21:24:14 +00:00
print ( " ******************* Building Binding from generation Process ************************* " )
2023-06-04 23:21:12 +00:00
self . binding = self . load_binding ( self . config [ " binding_name " ] , install = True )
2023-05-25 21:24:14 +00:00
print ( " Binding loaded successfully " )
2023-05-13 22:24:26 +00:00
try :
2023-06-09 23:37:50 +00:00
model_file = self . config . models_path / self . config [ " binding_name " ] / self . config [ " model_name " ]
2023-05-13 22:24:26 +00:00
print ( f " Loading model : { model_file } " )
2023-05-25 21:24:14 +00:00
self . model = self . binding ( self . config )
2023-05-14 09:10:49 +00:00
self . model_ready . value = 1
2023-05-19 20:21:13 +00:00
print ( " Model created successfully \n " )
2023-05-13 22:24:26 +00:00
except Exception as ex :
2023-06-04 23:21:12 +00:00
if self . config [ " model_name " ] is None :
2023-05-25 22:04:50 +00:00
print ( " No model is selected. \n Please select a backend and a model to start using the ui. " )
else :
2023-06-04 23:21:12 +00:00
print ( f " Couldn ' t build model { self . config [ ' model_name ' ] } : { ex } " )
2023-05-13 22:24:26 +00:00
self . model = None
2023-05-24 14:17:00 +00:00
self . _set_config_result [ ' status ' ] = ' failed '
2023-05-25 21:24:14 +00:00
self . _set_config_result [ ' binding_status ' ] = ' failed '
self . _set_config_result [ ' errors ' ] . append ( f " couldn ' t build binding: { ex } " )
2023-05-13 22:24:26 +00:00
except Exception as ex :
2023-05-21 23:29:20 +00:00
traceback . print_exc ( )
2023-05-25 21:24:14 +00:00
print ( " Couldn ' t build binding " )
2023-05-13 22:24:26 +00:00
print ( ex )
2023-05-25 21:24:14 +00:00
self . binding = None
2023-05-13 22:24:26 +00:00
self . model = None
2023-05-24 14:17:00 +00:00
self . _set_config_result [ ' status ' ] = ' failed '
2023-05-25 21:24:14 +00:00
self . _set_config_result [ ' binding_status ' ] = ' failed '
self . _set_config_result [ ' errors ' ] . append ( f " couldn ' t build binding: { ex } " )
2023-05-13 22:24:26 +00:00
2023-06-08 06:58:02 +00:00
def rebuild_personalities ( self ) :
mounted_personalities = [ ]
print ( f " ******************* Building mounted Personalities from main Process ************************* " )
for personality in self . config [ ' personalities ' ] :
try :
print ( f " { personality } " )
personality_path = lollms_path / f " personalities_zoo/ { personality } "
personality = AIPersonality ( personality_path , run_scripts = False )
mounted_personalities . append ( personality )
except Exception as ex :
print ( f " Personality file not found or is corrupted ( { personality_path } ). \n Please 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. " )
if self . config [ " debug " ] :
print ( ex )
personality = AIPersonality ( )
2023-05-18 18:00:48 +00:00
2023-06-08 06:58:02 +00:00
print ( f " ************ Personalities mounted (Main process) *************************** " )
return mounted_personalities
2023-05-13 22:24:26 +00:00
2023-06-08 06:58:02 +00:00
def _rebuild_personalities ( self ) :
self . mounted_personalities = [ ]
failed_personalities = [ ]
self . reset_config_result ( )
print ( f " ******************* Building mounted Personalities from generation Process ************************* " )
for personality in self . config [ ' personalities ' ] :
try :
print ( f " { personality } " )
personality_path = lollms_path / f " personalities_zoo/ { personality } "
personality = AIPersonality ( personality_path , run_scripts = True )
self . mounted_personalities . append ( personality )
except Exception as ex :
print ( f " Personality file not found or is corrupted ( { personality_path } ). \n Please 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. " )
if self . config [ " debug " ] :
print ( ex )
personality = AIPersonality ( )
failed_personalities . append ( personality_path )
self . _set_config_result [ ' errors ' ] . append ( f " couldn ' t build personalities: { ex } " )
print ( f " ************ Personalities mounted (Generation process) *************************** " )
if len ( failed_personalities ) == len ( self . config [ ' personalities ' ] ) :
2023-05-24 14:17:00 +00:00
self . _set_config_result [ ' status ' ] = ' failed '
2023-06-08 06:58:02 +00:00
self . _set_config_result [ ' personalities_status ' ] = ' failed '
elif len ( failed_personalities ) > 0 :
self . _set_config_result [ ' status ' ] = ' semi_failed '
self . _set_config_result [ ' personalities_status ' ] = ' semi_failed '
2023-06-10 00:03:29 +00:00
self . personality = self . config [ " personalities " ] [ self . config [ ' active_personality_id ' ] ]
self . mounted_personalities = self . config [ " personalities " ]
2023-06-08 06:58:02 +00:00
print ( " Personality set successfully " )
2023-05-26 12:01:21 +00:00
2023-05-22 06:52:48 +00:00
def _run ( self ) :
2023-05-13 22:24:26 +00:00
self . _rebuild_model ( )
2023-06-08 06:58:02 +00:00
self . _rebuild_personalities ( )
2023-05-26 14:22:02 +00:00
self . check_set_config_thread = threading . Thread ( target = self . _check_set_config_queue , args = ( ) )
print ( " Launching config verification thread " )
self . check_set_config_thread . start ( )
self . check_cancel_thread = threading . Thread ( target = self . _check_cancel_queue , args = ( ) )
print ( " Launching cancel verification thread " )
self . check_cancel_thread . start ( )
self . _check_clear_thread = threading . Thread ( target = self . _check_clear_queue , args = ( ) )
print ( " Launching clear verification thread " )
self . _check_clear_thread . start ( )
2023-05-14 09:10:49 +00:00
if self . model_ready . value == 1 :
2023-05-29 22:38:32 +00:00
# self.n_predict = 1
# self._generate("I",1)
2023-05-14 09:10:49 +00:00
print ( )
print ( " Ready to receive data " )
else :
print ( " No model loaded. Waiting for new configuration instructions " )
2023-05-13 22:24:26 +00:00
self . ready = True
2023-05-14 09:10:49 +00:00
print ( f " Listening on :http:// { self . config [ ' host ' ] } : { self . config [ ' port ' ] } " )
2023-05-13 22:24:26 +00:00
while True :
2023-05-14 00:29:09 +00:00
try :
if not self . generate_queue . empty ( ) :
command = self . generate_queue . get ( )
2023-05-26 14:22:02 +00:00
if command is not None :
if self . cancel_queue . empty ( ) and self . clear_queue_queue . empty ( ) :
self . id = command [ 2 ]
self . n_predict = command [ 3 ]
if self . personality . processor is not None :
if self . personality . processor_cfg is not None :
if " custom_workflow " in self . personality . processor_cfg :
if self . personality . processor_cfg [ " custom_workflow " ] :
print ( " Running workflow " )
2023-05-28 18:36:00 +00:00
self . completion_signal . clear ( )
self . start_signal . set ( )
2023-05-26 14:22:02 +00:00
output = self . personality . processor . run_workflow ( self . _generate , command [ 1 ] , command [ 0 ] , self . _callback )
self . _callback ( output , 0 )
2023-05-28 18:36:00 +00:00
self . completion_signal . set ( )
2023-05-28 23:25:25 +00:00
self . start_signal . clear ( )
2023-05-28 18:36:00 +00:00
print ( " Finished executing the workflow " )
2023-05-26 14:22:02 +00:00
continue
2023-05-28 18:36:00 +00:00
self . start_signal . set ( )
self . completion_signal . clear ( )
2023-05-26 14:22:02 +00:00
self . _generate ( command [ 0 ] , self . n_predict , self . _callback )
2023-05-28 18:36:00 +00:00
self . completion_signal . set ( )
2023-05-28 23:25:25 +00:00
self . start_signal . clear ( )
2023-05-28 18:36:00 +00:00
print ( " Finished executing the generation " )
2023-05-14 00:29:09 +00:00
except Exception as ex :
print ( ex )
2023-05-26 14:22:02 +00:00
time . sleep ( 1 )
2023-05-20 09:48:21 +00:00
def _generate ( self , prompt , n_predict = 50 , callback = None ) :
2023-05-26 14:22:02 +00:00
self . curent_text = " "
2023-05-14 08:23:28 +00:00
if self . model is not None :
2023-05-23 22:35:19 +00:00
print ( " Generating message... " )
2023-05-18 22:20:05 +00:00
self . id = self . id
2023-05-14 08:23:28 +00:00
if self . config [ " override_personality_model_parameters " ] :
2023-05-19 01:32:38 +00:00
output = self . model . generate (
2023-05-14 08:23:28 +00:00
prompt ,
2023-06-05 22:17:23 +00:00
callback = callback ,
2023-05-20 09:48:21 +00:00
n_predict = n_predict ,
2023-05-29 22:55:45 +00:00
temperature = self . config [ ' temperature ' ] ,
2023-05-14 08:23:28 +00:00
top_k = self . config [ ' top_k ' ] ,
top_p = self . config [ ' top_p ' ] ,
repeat_penalty = self . config [ ' repeat_penalty ' ] ,
repeat_last_n = self . config [ ' repeat_last_n ' ] ,
seed = self . config [ ' seed ' ] ,
n_threads = self . config [ ' n_threads ' ]
)
else :
2023-05-19 01:32:38 +00:00
output = self . model . generate (
2023-05-14 08:23:28 +00:00
prompt ,
2023-06-05 22:17:23 +00:00
callback = callback ,
2023-05-18 22:20:05 +00:00
n_predict = self . n_predict ,
2023-05-29 22:55:45 +00:00
temperature = self . personality . model_temperature ,
2023-05-14 08:23:28 +00:00
top_k = self . personality . model_top_k ,
top_p = self . personality . model_top_p ,
repeat_penalty = self . personality . model_repeat_penalty ,
repeat_last_n = self . personality . model_repeat_last_n ,
#seed=self.config['seed'],
n_threads = self . config [ ' n_threads ' ]
)
2023-05-13 22:24:26 +00:00
else :
2023-05-14 08:23:28 +00:00
print ( " No model is installed or selected. Please make sure to install a model and select it inside your configuration before attempting to communicate with the model. " )
2023-05-25 21:24:14 +00:00
print ( " To do this: Install the model to your models/<binding name> folder. " )
2023-05-26 22:18:04 +00:00
print ( " Then set your model information in your local configuration file that you can find in configs/local_config.yaml " )
2023-05-14 08:23:28 +00:00
print ( " You can also use the ui to set your model in the settings page. " )
2023-05-19 01:32:38 +00:00
output = " "
return output
2023-05-18 22:20:05 +00:00
2023-05-26 12:01:21 +00:00
def _callback ( self , text , text_type = 0 ) :
2023-05-26 14:22:02 +00:00
self . curent_text + = text
detected_anti_prompt = False
anti_prompt_to_remove = " "
for prompt in self . personality . anti_prompts :
2023-06-05 22:17:23 +00:00
if prompt . lower ( ) in self . curent_text . lower ( ) :
2023-05-26 14:22:02 +00:00
detected_anti_prompt = True
anti_prompt_to_remove = prompt . lower ( )
if not detected_anti_prompt :
if not self . ready :
2023-05-13 22:24:26 +00:00
return True
else :
2023-05-26 14:22:02 +00:00
# Stream the generated text to the main process
self . generation_queue . put ( ( text , self . id , text_type ) )
# if stop generation is detected then stop
2023-05-29 19:26:20 +00:00
if not self . completion_signal . is_set ( ) :
2023-05-26 14:22:02 +00:00
return True
else :
return False
else :
self . curent_text = self . remove_text_from_string ( self . curent_text , anti_prompt_to_remove )
print ( " The model is halucinating " )
2023-05-28 18:36:00 +00:00
return False
2023-05-26 14:22:02 +00:00
2023-05-13 22:24:26 +00:00
def _check_cancel_queue ( self ) :
2023-05-26 14:22:02 +00:00
while True :
2023-05-13 22:24:26 +00:00
command = self . cancel_queue . get ( )
if command is not None :
2023-05-26 20:05:08 +00:00
self . _cancel_generation ( )
print ( " Stop generation received " )
2023-05-13 22:24:26 +00:00
def _check_clear_queue ( self ) :
2023-05-26 14:22:02 +00:00
while True :
2023-05-13 22:24:26 +00:00
command = self . clear_queue_queue . get ( )
if command is not None :
self . _clear_queue ( )
2023-05-26 20:05:08 +00:00
print ( " Clear received " )
2023-05-13 22:24:26 +00:00
def _check_set_config_queue ( self ) :
2023-05-26 14:22:02 +00:00
while True :
2023-05-13 22:24:26 +00:00
config = self . set_config_queue . get ( )
if config is not None :
2023-05-17 15:38:40 +00:00
print ( " Inference process : Setting configuration " )
2023-05-18 18:00:48 +00:00
self . reset_config_result ( )
2023-05-13 22:24:26 +00:00
self . _set_config ( config )
2023-05-18 18:00:48 +00:00
self . set_config_result_queue . put ( self . _set_config_result )
2023-05-13 22:24:26 +00:00
def _cancel_generation ( self ) :
2023-05-28 18:36:00 +00:00
self . completion_signal . set ( )
2023-05-13 22:24:26 +00:00
def _clear_queue ( self ) :
while not self . generate_queue . empty ( ) :
self . generate_queue . get ( )
def _set_config ( self , config ) :
bk_cfg = self . config
self . config = config
2023-05-14 00:29:09 +00:00
print ( " Changing configuration " )
2023-05-25 21:24:14 +00:00
# verify that the binding is the same
2023-06-04 23:21:12 +00:00
if self . config [ " binding_name " ] != bk_cfg [ " binding_name " ] or self . config [ " model_name " ] != bk_cfg [ " model_name " ] :
2023-05-13 22:24:26 +00:00
self . _rebuild_model ( )
# verify that the personality is the same
2023-06-08 06:58:02 +00:00
if not compare_lists ( self . config [ " personalities " ] , bk_cfg [ " personalities " ] ) :
self . _rebuild_personalities ( )
2023-05-13 22:24:26 +00:00
2023-06-04 23:21:12 +00:00
class LoLLMsAPPI ( ) :
def __init__ ( self , config : BindingConfig , socketio , config_file_path : str ) - > None :
2023-05-13 22:24:26 +00:00
self . socketio = socketio
#Create and launch the process
self . process = ModelProcess ( config )
2023-04-15 11:30:08 +00:00
self . config = config
2023-06-10 00:03:29 +00:00
self . mounted_personalities = self . config [ " personalities " ]
2023-05-25 21:24:14 +00:00
self . binding = self . process . rebuild_binding ( self . config )
2023-06-08 06:58:02 +00:00
self . personalities = self . process . rebuild_personalities ( )
self . personality = self . personalities [ self . config [ " active_personality_id " ] ]
2023-05-07 01:44:42 +00:00
if config [ " debug " ] :
2023-05-13 22:24:26 +00:00
print ( print ( f " { self . personality } " ) )
2023-04-15 11:30:08 +00:00
self . config_file_path = config_file_path
2023-04-23 22:19:15 +00:00
self . cancel_gen = False
2023-04-15 11:30:08 +00:00
# Keeping track of current discussion and message
self . current_discussion = None
2023-05-09 05:06:01 +00:00
self . _current_user_message_id = 0
self . _current_ai_message_id = 0
self . _message_id = 0
2023-04-15 11:30:08 +00:00
self . db_path = config [ " db_path " ]
# Create database object
self . db = DiscussionsDB ( self . db_path )
# If the database is empty, populate it with tables
self . db . populate ( )
# This is used to keep track of messages
self . full_message_list = [ ]
2023-05-13 22:24:26 +00:00
# =========================================================================================
# Socket IO stuff
# =========================================================================================
@socketio.on ( ' connect ' )
def connect ( ) :
print ( ' Client connected ' )
@socketio.on ( ' disconnect ' )
def disconnect ( ) :
print ( ' Client disconnected ' )
@socketio.on ( ' install_model ' )
def install_model ( data ) :
def install_model_ ( ) :
print ( " Install model triggered " )
model_path = data [ " path " ]
progress = 0
2023-06-04 23:21:12 +00:00
installation_dir = Path ( f ' ./models/ { self . config [ " binding_name " ] } / ' )
2023-05-13 22:24:26 +00:00
filename = Path ( model_path ) . name
installation_path = installation_dir / filename
print ( " Model install requested " )
print ( f " Model path : { model_path } " )
if installation_path . exists ( ) :
print ( " Error: Model already exists " )
socketio . emit ( ' install_progress ' , { ' status ' : ' failed ' , ' error ' : ' model already exists ' } )
socketio . emit ( ' install_progress ' , { ' status ' : ' progress ' , ' progress ' : progress } )
def callback ( progress ) :
socketio . emit ( ' install_progress ' , { ' status ' : ' progress ' , ' progress ' : progress } )
2023-05-29 15:08:06 +00:00
if hasattr ( self . binding , " download_model " ) :
self . binding . download_model ( model_path , installation_path , callback )
else :
self . download_file ( model_path , installation_path , callback )
2023-05-13 22:24:26 +00:00
socketio . emit ( ' install_progress ' , { ' status ' : ' succeeded ' , ' error ' : ' ' } )
tpe = threading . Thread ( target = install_model_ , args = ( ) )
tpe . start ( )
2023-05-22 06:52:48 +00:00
2023-05-13 22:24:26 +00:00
@socketio.on ( ' uninstall_model ' )
def uninstall_model ( data ) :
model_path = data [ ' path ' ]
2023-06-04 23:21:12 +00:00
installation_dir = Path ( f ' ./models/ { self . config [ " binding_name " ] } / ' )
2023-05-13 22:24:26 +00:00
filename = Path ( model_path ) . name
installation_path = installation_dir / filename
if not installation_path . exists ( ) :
socketio . emit ( ' install_progress ' , { ' status ' : ' failed ' , ' error ' : ' The model does not exist ' } )
installation_path . unlink ( )
socketio . emit ( ' install_progress ' , { ' status ' : ' succeeded ' , ' error ' : ' ' } )
2023-04-15 11:30:08 +00:00
2023-05-13 22:24:26 +00:00
@socketio.on ( ' generate_msg ' )
def generate_msg ( data ) :
2023-05-14 09:10:49 +00:00
if self . process . model_ready . value == 1 :
if self . current_discussion is None :
if self . db . does_last_discussion_have_messages ( ) :
self . current_discussion = self . db . create_discussion ( )
else :
self . current_discussion = self . db . load_last_discussion ( )
2023-05-13 22:24:26 +00:00
2023-05-14 09:10:49 +00:00
message = data [ " prompt " ]
message_id = self . current_discussion . add_message (
" user " , message , parent = self . message_id
)
2023-04-20 17:30:03 +00:00
2023-05-14 09:10:49 +00:00
self . current_user_message_id = message_id
2023-05-28 23:25:25 +00:00
print ( " Starting message generation " )
2023-05-14 09:10:49 +00:00
tpe = threading . Thread ( target = self . start_message_generation , args = ( message , message_id ) )
tpe . start ( )
else :
self . socketio . emit ( ' infos ' ,
{
" status " : ' model_not_ready ' ,
" type " : " input_message_infos " ,
2023-05-20 14:07:16 +00:00
' logo ' : " " ,
2023-05-14 09:10:49 +00:00
" bot " : self . personality . name ,
" user " : self . personality . user_name ,
" message " : " " ,
" user_message_id " : self . current_user_message_id ,
" ai_message_id " : self . current_ai_message_id ,
}
)
2023-05-13 22:24:26 +00:00
@socketio.on ( ' generate_msg_from ' )
def handle_connection ( data ) :
message_id = int ( data [ ' id ' ] )
message = data [ " prompt " ]
self . current_user_message_id = message_id
tpe = threading . Thread ( target = self . start_message_generation , args = ( message , message_id ) )
tpe . start ( )
2023-04-15 11:30:08 +00:00
# generation status
self . generating = False
2023-05-22 06:52:48 +00:00
self . process . start ( )
2023-04-15 11:30:08 +00:00
2023-05-09 05:06:01 +00:00
#properties
@property
def message_id ( self ) :
return self . _message_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
2023-05-13 22:24:26 +00:00
def download_file ( self , url , installation_path , callback = None ) :
"""
2023-05-14 11:33:45 +00:00
Downloads a file from a URL , reports the download progress using a callback function , and displays a progress bar .
2023-05-13 22:24:26 +00:00
Args :
url ( str ) : The URL of the file to download .
2023-05-14 11:33:45 +00:00
installation_path ( str ) : The path where the file should be saved .
2023-05-13 22:24:26 +00:00
callback ( function , optional ) : A callback function to be called during the download
with the progress percentage as an argument . Defaults to None .
"""
2023-05-14 09:10:49 +00:00
try :
2023-05-14 11:33:45 +00:00
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 :
percentage = ( downloaded_size / total_size ) * 100
callback ( percentage )
progress_bar . update ( len ( chunk ) )
2023-05-09 05:06:01 +00:00
2023-05-14 09:10:49 +00:00
if callback is not None :
callback ( 100.0 )
2023-05-14 11:33:45 +00:00
print ( " File downloaded successfully " )
except Exception as e :
print ( " Couldn ' t download file: " , str ( e ) )
2023-05-21 19:54:56 +00:00
2023-05-13 22:24:26 +00:00
def condition_chatbot ( self ) :
2023-04-15 11:30:08 +00:00
if self . current_discussion is None :
self . current_discussion = self . db . load_last_discussion ( )
2023-05-09 05:06:01 +00:00
2023-04-30 20:40:19 +00:00
if self . personality . welcome_message != " " :
2023-05-09 05:06:01 +00:00
message_id = self . current_discussion . add_message (
self . personality . name , self . personality . welcome_message ,
DiscussionsDB . MSG_TYPE_NORMAL ,
0 ,
- 1
)
2023-04-15 11:30:08 +00:00
2023-05-09 05:06:01 +00:00
self . current_ai_message_id = message_id
2023-05-16 23:48:35 +00:00
else :
message_id = 0
2023-04-15 11:30:08 +00:00
return message_id
def prepare_reception ( self ) :
self . bot_says = " "
self . full_text = " "
self . is_bot_text_started = False
def create_new_discussion ( self , title ) :
self . current_discussion = self . db . create_discussion ( title )
# Get the current timestamp
timestamp = datetime . now ( ) . strftime ( " % Y- % m- %d % H: % M: % S " )
# Chatbot conditionning
2023-05-13 23:27:19 +00:00
self . condition_chatbot ( )
2023-04-15 11:30:08 +00:00
return timestamp
def prepare_query ( self , message_id = - 1 ) :
messages = self . current_discussion . get_messages ( )
self . full_message_list = [ ]
for message in messages :
2023-05-16 23:48:35 +00:00
if message [ " id " ] < message_id or message_id == - 1 :
2023-05-09 05:06:01 +00:00
if message [ " type " ] == self . db . MSG_TYPE_NORMAL :
2023-04-30 20:40:19 +00:00
if message [ " sender " ] == self . personality . name :
self . full_message_list . append ( self . personality . ai_message_prefix + message [ " content " ] )
2023-04-15 11:30:08 +00:00
else :
2023-04-30 20:40:19 +00:00
self . full_message_list . append ( self . personality . user_message_prefix + message [ " content " ] )
2023-05-16 23:48:35 +00:00
else :
break
2023-05-18 22:20:05 +00:00
2023-05-16 23:48:35 +00:00
if self . personality . processor is not None :
preprocessed_prompt = self . personality . processor . process_model_input ( message [ " content " ] )
else :
preprocessed_prompt = message [ " content " ]
if preprocessed_prompt is not None :
self . full_message_list . append ( self . personality . user_message_prefix + preprocessed_prompt + self . personality . link_text + self . personality . ai_message_prefix )
else :
2023-05-19 01:32:38 +00:00
self . full_message_list . append ( self . personality . user_message_prefix + message [ " content " ] + self . personality . link_text + self . personality . ai_message_prefix )
2023-05-16 23:48:35 +00:00
2023-04-16 11:47:39 +00:00
2023-04-30 20:40:19 +00:00
link_text = self . personality . link_text
2023-04-16 11:47:39 +00:00
2023-06-04 23:21:12 +00:00
discussion_messages = self . personality . personality_conditioning + link_text . join ( self . full_message_list )
2023-04-16 11:47:39 +00:00
2023-05-19 01:32:38 +00:00
return discussion_messages , message [ " content " ]
2023-04-17 22:23:31 +00:00
def get_discussion_to ( self , message_id = - 1 ) :
messages = self . current_discussion . get_messages ( )
self . full_message_list = [ ]
for message in messages :
if message [ " id " ] < = message_id or message_id == - 1 :
if message [ " type " ] != self . db . MSG_TYPE_CONDITIONNING :
2023-04-30 20:40:19 +00:00
if message [ " sender " ] == self . personality . name :
self . full_message_list . append ( self . personality . ai_message_prefix + message [ " content " ] )
2023-04-17 22:23:31 +00:00
else :
2023-04-30 20:40:19 +00:00
self . full_message_list . append ( self . personality . user_message_prefix + message [ " content " ] )
2023-04-17 22:23:31 +00:00
2023-04-30 20:40:19 +00:00
link_text = self . personality . link_text
2023-04-17 22:23:31 +00:00
if len ( self . full_message_list ) > self . config [ " nb_messages_to_remember " ] :
2023-05-01 22:09:57 +00:00
discussion_messages = self . personality . personality_conditioning + link_text . join ( self . full_message_list [ - self . config [ " nb_messages_to_remember " ] : ] )
2023-04-17 22:23:31 +00:00
else :
2023-05-01 22:09:57 +00:00
discussion_messages = self . personality . personality_conditioning + link_text . join ( self . full_message_list )
2023-04-17 22:23:31 +00:00
return discussion_messages # Removes the last return
2023-04-23 22:19:15 +00:00
2023-06-05 22:17:23 +00:00
def process_chunk ( self , chunk , message_type : MSG_TYPE ) :
2023-05-28 23:25:25 +00:00
"""
0 : a regular message
1 : a notification message
2 : A hidden message
"""
2023-06-05 22:17:23 +00:00
if message_type == MSG_TYPE . MSG_TYPE_CHUNK :
2023-05-28 21:26:05 +00:00
self . bot_says + = chunk
2023-06-05 22:17:23 +00:00
if message_type . value < 2 :
2023-05-28 21:26:05 +00:00
self . socketio . emit ( ' message ' , {
' data ' : self . bot_says ,
' user_message_id ' : self . current_user_message_id ,
' ai_message_id ' : self . current_ai_message_id ,
' discussion_id ' : self . current_discussion . discussion_id ,
2023-06-05 22:17:23 +00:00
' message_type ' : message_type . value
2023-05-28 21:26:05 +00:00
}
)
2023-05-26 14:22:02 +00:00
if self . cancel_gen :
print ( " Generation canceled " )
2023-05-13 22:24:26 +00:00
self . process . cancel_generation ( )
2023-05-26 14:22:02 +00:00
self . cancel_gen = False
2023-05-26 12:01:21 +00:00
self . current_discussion . update_message ( self . current_ai_message_id , self . bot_says )
2023-05-13 22:24:26 +00:00
def start_message_generation ( self , message , message_id ) :
bot_says = " "
# send the message to the bot
print ( f " Received message : { message } " )
if self . current_discussion :
# First we need to send the new message ID to the client
self . current_ai_message_id = self . current_discussion . add_message (
self . personality . name , " " , parent = self . current_user_message_id
) # first the content is empty, but we'll fill it at the end
self . socketio . emit ( ' infos ' ,
{
2023-05-14 09:10:49 +00:00
" status " : ' generation_started ' ,
2023-05-13 22:24:26 +00:00
" type " : " input_message_infos " ,
" bot " : self . personality . name ,
" user " : self . personality . user_name ,
" message " : message , #markdown.markdown(message),
" user_message_id " : self . current_user_message_id ,
" ai_message_id " : self . current_ai_message_id ,
}
2023-05-05 12:23:07 +00:00
)
2023-05-13 22:24:26 +00:00
# prepare query and reception
2023-05-19 01:32:38 +00:00
self . discussion_messages , self . current_message = self . prepare_query ( message_id )
2023-05-13 22:24:26 +00:00
self . prepare_reception ( )
2023-05-28 18:36:00 +00:00
self . generating = True
2023-05-19 01:32:38 +00:00
self . process . generate ( self . discussion_messages , self . current_message , message_id , n_predict = self . config [ ' n_predict ' ] )
2023-05-28 18:36:00 +00:00
while ( not self . process . completion_signal . is_set ( ) or not self . process . generation_queue . empty ( ) ) : # Simulating other commands being issued
2023-05-26 12:01:21 +00:00
try :
chunk , tok , message_type = self . process . generation_queue . get ( False , 2 )
2023-05-29 20:03:12 +00:00
print ( chunk , end = " " )
2023-05-26 12:01:21 +00:00
if chunk != " " :
self . process_chunk ( chunk , message_type )
2023-05-28 18:36:00 +00:00
except Exception as ex :
2023-05-26 14:22:02 +00:00
time . sleep ( 0.1 )
2023-05-13 22:24:26 +00:00
print ( )
2023-05-28 23:25:25 +00:00
print ( " ## Done Generation ## " )
2023-05-13 22:24:26 +00:00
print ( )
# Send final message
self . socketio . emit ( ' final ' , {
' data ' : self . bot_says ,
' ai_message_id ' : self . current_ai_message_id ,
' parent ' : self . current_user_message_id , ' discussion_id ' : self . current_discussion . discussion_id
}
)
self . current_discussion . update_message ( self . current_ai_message_id , self . bot_says )
self . full_message_list . append ( self . bot_says )
2023-05-28 23:25:25 +00:00
self . cancel_gen = False
print ( )
print ( " ## Done ## " )
print ( )
2023-05-05 12:23:07 +00:00
else :
2023-05-13 22:24:26 +00:00
#No discussion available
print ( " No discussion selected!!! " )
print ( " ## Done ## " )
print ( )
self . cancel_gen = False
return " "