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
######
2023-06-10 21:09:56 +00:00
from flask import request
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-21 22:43:59 +00:00
from lollms . config import InstallOption
2023-06-22 21:33:57 +00:00
from lollms . types import MSG_TYPE
from lollms . personality import AIPersonality , PersonalityBuilder
from lollms . binding import LOLLMSConfig , BindingBuilder , LLMBinding , ModelBuilder
2023-06-10 13:16:28 +00:00
from lollms . paths import LollmsPaths
2023-06-10 20:49:03 +00:00
from lollms . helpers import ASCIIColors
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-06-15 10:03:05 +00:00
from lollms . console import MainMenu
2023-06-23 12:44:25 +00:00
import urllib
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-06-04 23:21:12 +00:00
class LoLLMsAPPI ( ) :
2023-06-10 13:16:28 +00:00
def __init__ ( self , config : LOLLMSConfig , socketio , config_file_path : str , lollms_paths : LollmsPaths ) - > None :
self . lollms_paths = lollms_paths
2023-06-15 10:03:05 +00:00
self . config = config
2023-06-21 22:43:59 +00:00
self . is_ready = True
2023-06-15 10:03:05 +00:00
self . menu = MainMenu ( self )
2023-06-19 22:53:53 +00:00
2023-06-10 13:16:28 +00:00
2023-05-13 22:24:26 +00:00
self . socketio = socketio
2023-06-21 22:43:59 +00:00
# Check model
if config . binding_name is None :
2023-06-25 19:31:24 +00:00
self . menu . select_binding ( )
2023-06-19 23:29:06 +00:00
2023-06-21 22:43:59 +00:00
self . binding = BindingBuilder ( ) . build_binding ( self . config , self . lollms_paths )
2023-06-19 22:53:53 +00:00
# Check model
if config . model_name is None :
2023-06-21 22:43:59 +00:00
self . menu . select_model ( )
2023-06-19 22:53:53 +00:00
2023-06-21 22:43:59 +00:00
self . mounted_personalities = [ ]
2023-06-26 10:45:46 +00:00
try :
self . model = self . binding . build_model ( )
self . mounted_personalities = self . rebuild_personalities ( )
if self . config [ " active_personality_id " ] < len ( self . mounted_personalities ) :
self . personality : AIPersonality = self . mounted_personalities [ self . config [ " active_personality_id " ] ]
else :
self . personality : AIPersonality = None
if config [ " debug " ] :
print ( print ( f " { self . personality } " ) )
except Exception as ex :
ASCIIColors . error ( f " Couldn ' t load model: \n Exception generated: { ex } " )
self . model = None
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 " ]
2023-06-10 13:49:41 +00:00
if Path ( self . db_path ) . is_absolute ( ) :
# Create database object
self . db = DiscussionsDB ( self . db_path )
else :
# Create database object
self . db = DiscussionsDB ( self . lollms_paths . personal_path / " databases " / self . db_path )
2023-04-15 11:30:08 +00:00
# If the database is empty, populate it with tables
2023-06-15 16:51:04 +00:00
ASCIIColors . info ( " Checking discussions database... " , end = " " )
2023-06-15 16:49:47 +00:00
self . db . create_tables ( )
self . db . add_missing_columns ( )
2023-06-15 16:51:04 +00:00
ASCIIColors . success ( " ok " )
2023-04-15 11:30:08 +00:00
# This is used to keep track of messages
self . full_message_list = [ ]
2023-06-10 21:09:56 +00:00
self . current_room_id = None
2023-06-23 12:18:55 +00:00
self . download_infos = { }
2023-05-13 22:24:26 +00:00
# =========================================================================================
# Socket IO stuff
# =========================================================================================
@socketio.on ( ' connect ' )
def connect ( ) :
2023-06-11 19:02:06 +00:00
ASCIIColors . success ( f ' Client { request . sid } connected ' )
2023-05-13 22:24:26 +00:00
@socketio.on ( ' disconnect ' )
def disconnect ( ) :
2023-06-11 19:02:06 +00:00
ASCIIColors . error ( f ' Client { request . sid } disconnected ' )
2023-05-13 22:24:26 +00:00
2023-06-23 00:02:37 +00:00
2023-06-23 12:18:55 +00:00
@socketio.on ( ' cancel_install ' )
def cancel_install ( data ) :
model_name = data [ " model_name " ]
binding_folder = data [ " binding_folder " ]
model_url = data [ " model_url " ]
signature = f " { model_name } _ { binding_folder } _ { model_url } "
self . download_infos [ signature ] [ " cancel " ] = True
2023-06-28 20:08:18 +00:00
self . socketio . emit ( ' canceled ' , {
' status ' : True
} ,
room = self . current_room_id
)
2023-06-23 12:18:55 +00:00
2023-05-13 22:24:26 +00:00
@socketio.on ( ' install_model ' )
def install_model ( data ) :
2023-06-10 21:09:56 +00:00
room_id = request . sid
2023-06-23 12:44:25 +00:00
def get_file_size ( url ) :
# Send a HEAD request to retrieve file metadata
response = urllib . request . urlopen ( url )
# Extract the Content-Length header value
file_size = response . headers . get ( ' Content-Length ' )
# Convert the file size to integer
if file_size :
file_size = int ( file_size )
2023-06-24 15:17:15 +00:00
return file_size
2023-05-13 22:24:26 +00:00
def install_model_ ( ) :
print ( " Install model triggered " )
model_path = data [ " path " ]
progress = 0
2023-06-10 21:09:56 +00:00
installation_dir = self . lollms_paths . personal_models_path / 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 } " )
2023-06-23 10:23:18 +00:00
model_name = filename
binding_folder = self . config [ " binding_name " ]
model_url = model_path
2023-06-23 12:18:55 +00:00
signature = f " { model_name } _ { binding_folder } _ { model_url } "
self . download_infos [ signature ] = {
2023-06-23 12:44:25 +00:00
" start_time " : datetime . now ( ) ,
" total_size " : get_file_size ( model_path ) ,
" downloaded_size " : 0 ,
2023-06-23 12:18:55 +00:00
" progress " : 0 ,
2023-06-23 12:44:25 +00:00
" speed " : 0 ,
2023-06-23 12:18:55 +00:00
" cancel " : False
}
2023-05-13 22:24:26 +00:00
if installation_path . exists ( ) :
print ( " Error: Model already exists " )
2023-06-23 10:23:18 +00:00
socketio . emit ( ' install_progress ' , {
' status ' : False ,
' error ' : ' model already exists ' ,
' model_name ' : model_name ,
' binding_folder ' : binding_folder ,
2023-06-23 12:44:25 +00:00
' model_url ' : model_url ,
2023-06-23 13:24:22 +00:00
' start_time ' : self . download_infos [ signature ] [ ' start_time ' ] . strftime ( " % Y- % m- %d % H: % M: % S " ) ,
2023-06-23 12:44:25 +00:00
' total_size ' : self . download_infos [ signature ] [ ' total_size ' ] ,
' downloaded_size ' : self . download_infos [ signature ] [ ' downloaded_size ' ] ,
' progress ' : self . download_infos [ signature ] [ ' progress ' ] ,
' speed ' : self . download_infos [ signature ] [ ' speed ' ] ,
2023-06-23 10:23:18 +00:00
} , room = room_id
)
2023-05-13 22:24:26 +00:00
2023-06-23 10:23:18 +00:00
socketio . emit ( ' install_progress ' , {
2023-06-23 12:53:58 +00:00
' status ' : True ,
2023-06-23 10:23:18 +00:00
' progress ' : progress ,
' model_name ' : model_name ,
' binding_folder ' : binding_folder ,
2023-06-23 12:44:25 +00:00
' model_url ' : model_url ,
2023-06-23 13:24:22 +00:00
' start_time ' : self . download_infos [ signature ] [ ' start_time ' ] . strftime ( " % Y- % m- %d % H: % M: % S " ) ,
2023-06-23 12:44:25 +00:00
' total_size ' : self . download_infos [ signature ] [ ' total_size ' ] ,
' downloaded_size ' : self . download_infos [ signature ] [ ' downloaded_size ' ] ,
' progress ' : self . download_infos [ signature ] [ ' progress ' ] ,
' speed ' : self . download_infos [ signature ] [ ' speed ' ] ,
2023-06-23 10:23:18 +00:00
} , room = room_id )
2023-05-13 22:24:26 +00:00
2023-06-23 12:44:25 +00:00
def callback ( downloaded_size , total_size ) :
progress = ( downloaded_size / total_size ) * 100
now = datetime . now ( )
dt = ( now - self . download_infos [ signature ] [ ' start_time ' ] ) . total_seconds ( )
speed = downloaded_size / dt
self . download_infos [ signature ] [ ' downloaded_size ' ] = downloaded_size
self . download_infos [ signature ] [ ' speed ' ] = speed
2023-06-23 14:19:01 +00:00
if progress - self . download_infos [ signature ] [ ' progress ' ] > 2 :
2023-06-23 12:44:25 +00:00
self . download_infos [ signature ] [ ' progress ' ] = progress
socketio . emit ( ' install_progress ' , {
2023-06-23 12:53:58 +00:00
' status ' : True ,
2023-06-23 12:44:25 +00:00
' model_name ' : model_name ,
' binding_folder ' : binding_folder ,
' model_url ' : model_url ,
2023-06-23 13:24:22 +00:00
' start_time ' : self . download_infos [ signature ] [ ' start_time ' ] . strftime ( " % Y- % m- %d % H: % M: % S " ) ,
2023-06-23 12:44:25 +00:00
' total_size ' : self . download_infos [ signature ] [ ' total_size ' ] ,
' downloaded_size ' : self . download_infos [ signature ] [ ' downloaded_size ' ] ,
' progress ' : self . download_infos [ signature ] [ ' progress ' ] ,
' speed ' : self . download_infos [ signature ] [ ' speed ' ] ,
} , room = room_id )
2023-05-13 22:24:26 +00:00
2023-06-23 12:18:55 +00:00
if self . download_infos [ signature ] [ " cancel " ] :
raise Exception ( " canceled " )
2023-06-28 20:08:18 +00:00
2023-06-23 12:18:55 +00:00
2023-05-29 15:08:06 +00:00
if hasattr ( self . binding , " download_model " ) :
2023-06-23 12:18:55 +00:00
try :
self . binding . download_model ( model_path , installation_path , callback )
except Exception as ex :
ASCIIColors . warning ( str ( ex ) )
socketio . emit ( ' install_progress ' , {
' status ' : False ,
' error ' : ' canceled ' ,
' model_name ' : model_name ,
' binding_folder ' : binding_folder ,
2023-06-23 12:44:25 +00:00
' model_url ' : model_url ,
2023-06-23 13:24:22 +00:00
' start_time ' : self . download_infos [ signature ] [ ' start_time ' ] . strftime ( " % Y- % m- %d % H: % M: % S " ) ,
2023-06-23 12:44:25 +00:00
' total_size ' : self . download_infos [ signature ] [ ' total_size ' ] ,
' downloaded_size ' : self . download_infos [ signature ] [ ' downloaded_size ' ] ,
' progress ' : self . download_infos [ signature ] [ ' progress ' ] ,
' speed ' : self . download_infos [ signature ] [ ' speed ' ] ,
2023-06-23 12:18:55 +00:00
} , room = room_id
)
del self . download_infos [ signature ]
2023-06-23 12:19:31 +00:00
installation_path . unlink ( )
2023-06-23 12:18:55 +00:00
return
2023-05-29 15:08:06 +00:00
else :
2023-06-23 12:44:25 +00:00
try :
self . download_file ( model_path , installation_path , callback )
except Exception as ex :
ASCIIColors . warning ( str ( ex ) )
socketio . emit ( ' install_progress ' , {
' status ' : False ,
' error ' : ' canceled ' ,
' model_name ' : model_name ,
' binding_folder ' : binding_folder ,
' model_url ' : model_url ,
2023-06-23 13:24:22 +00:00
' start_time ' : self . download_infos [ signature ] [ ' start_time ' ] . strftime ( " % Y- % m- %d % H: % M: % S " ) ,
2023-06-23 12:44:25 +00:00
' total_size ' : self . download_infos [ signature ] [ ' total_size ' ] ,
' downloaded_size ' : self . download_infos [ signature ] [ ' downloaded_size ' ] ,
' progress ' : self . download_infos [ signature ] [ ' progress ' ] ,
' speed ' : self . download_infos [ signature ] [ ' speed ' ] ,
} , room = room_id
)
del self . download_infos [ signature ]
installation_path . unlink ( )
return
2023-06-23 10:23:18 +00:00
socketio . emit ( ' install_progress ' , {
' status ' : True ,
' error ' : ' ' ,
' model_name ' : model_name ,
' binding_folder ' : binding_folder ,
2023-06-23 12:44:25 +00:00
' model_url ' : model_url ,
2023-06-23 13:24:22 +00:00
' start_time ' : self . download_infos [ signature ] [ ' start_time ' ] . strftime ( " % Y- % m- %d % H: % M: % S " ) ,
2023-06-23 12:44:25 +00:00
' total_size ' : self . download_infos [ signature ] [ ' total_size ' ] ,
' downloaded_size ' : self . download_infos [ signature ] [ ' downloaded_size ' ] ,
2023-06-23 12:53:58 +00:00
' progress ' : 100 ,
2023-06-23 12:44:25 +00:00
' speed ' : self . download_infos [ signature ] [ ' speed ' ] ,
2023-06-23 10:23:18 +00:00
} , room = room_id )
2023-06-23 12:18:55 +00:00
del self . download_infos [ signature ]
2023-05-13 22:24:26 +00:00
tpe = threading . Thread ( target = install_model_ , args = ( ) )
tpe . start ( )
2023-06-22 21:23:56 +00:00
2023-05-13 22:24:26 +00:00
@socketio.on ( ' uninstall_model ' )
def uninstall_model ( data ) :
model_path = data [ ' path ' ]
2023-06-10 21:09:56 +00:00
installation_dir = self . lollms_paths . personal_models_path / self . config [ " binding_name " ]
2023-05-13 22:24:26 +00:00
filename = Path ( model_path ) . name
installation_path = installation_dir / filename
2023-06-23 10:30:05 +00:00
model_name = filename
binding_folder = self . config [ " binding_name " ]
2023-05-13 22:24:26 +00:00
if not installation_path . exists ( ) :
2023-06-23 10:30:05 +00:00
socketio . emit ( ' install_progress ' , {
' status ' : False ,
' error ' : ' The model does not exist ' ,
' model_name ' : model_name ,
' binding_folder ' : binding_folder
} , room = request . sid )
2023-05-13 22:24:26 +00:00
installation_path . unlink ( )
2023-06-23 10:30:05 +00:00
socketio . emit ( ' install_progress ' , {
' status ' : True ,
' error ' : ' ' ,
' model_name ' : model_name ,
' binding_folder ' : binding_folder
} , room = request . sid )
2023-06-22 21:33:57 +00:00
@socketio.on ( ' upload_file ' )
def upload_file ( data ) :
file = data [ ' file ' ]
filename = file . filename
save_path = self . lollms_paths . personal_uploads_path / filename # Specify the desired folder path
try :
2023-06-22 21:39:05 +00:00
if not self . personality . processor is None :
self . personality . processor . add_file ( save_path )
file . save ( save_path )
# File saved successfully
socketio . emit ( ' progress ' , { ' status ' : True , ' progress ' : 100 } )
2023-06-23 00:02:37 +00:00
2023-06-22 21:39:05 +00:00
else :
# Personality doesn't support file sending
socketio . emit ( ' progress ' , { ' status ' : False , ' error ' : " Personality doesn ' t support file sending " } )
2023-06-22 21:33:57 +00:00
except Exception as e :
# Error occurred while saving the file
2023-06-22 21:39:05 +00:00
socketio . emit ( ' progress ' , { ' status ' : False , ' error ' : str ( e ) } )
2023-05-13 22:24:26 +00:00
2023-06-25 20:56:06 +00:00
@socketio.on ( ' cancel_generation ' )
def cancel_generation ( ) :
self . cancel_gen = True
ASCIIColors . error ( f ' Client { request . sid } canceled generation ' )
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-06-10 21:09:56 +00:00
self . current_room_id = request . sid
2023-06-21 22:43:59 +00:00
if self . is_ready :
2023-05-14 09:10:49 +00:00
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 (
2023-06-17 21:52:34 +00:00
" user " ,
message ,
parent = self . message_id
2023-05-14 09:10:49 +00:00
)
2023-04-20 17:30:03 +00:00
2023-05-14 09:10:49 +00:00
self . current_user_message_id = message_id
2023-06-15 14:56:08 +00:00
ASCIIColors . green ( " Starting message generation by " + self . personality . name )
2023-06-21 22:43:59 +00:00
task = self . socketio . start_background_task ( self . start_message_generation , message , message_id )
2023-06-25 22:05:34 +00:00
self . socketio . sleep ( 0 )
2023-06-23 00:02:37 +00:00
ASCIIColors . info ( " Started generation task " )
2023-06-21 22:43:59 +00:00
#tpe = threading.Thread(target=self.start_message_generation, args=(message, message_id))
#tpe.start()
2023-05-14 09:10:49 +00:00
else :
2023-06-21 22:43:59 +00:00
self . socketio . emit ( " buzzy " , { " message " : " I am buzzy. Come back later. " } , room = self . current_room_id )
self . socketio . sleep ( 0 )
ASCIIColors . warning ( f " OOps request { self . current_room_id } refused!! Server buzy " )
2023-05-14 09:10:49 +00:00
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-06-18 07:06:52 +00:00
' binding ' : self . current_discussion . current_message_binding ,
' model ' : self . current_discussion . current_message_model ,
' personality ' : self . current_discussion . current_message_personality ,
' created_at ' : self . current_discussion . current_message_created_at ,
' finished_generating_at ' : self . current_discussion . current_message_finished_generating_at ,
2023-06-10 22:53:26 +00:00
} , room = self . current_room_id
2023-05-14 09:10:49 +00:00
)
2023-06-21 22:43:59 +00:00
self . socketio . sleep ( 0 )
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-06-25 17:26:22 +00:00
ASCIIColors . blue ( f " Your personal data is stored here : " , end = " " )
ASCIIColors . green ( f " { self . lollms_paths . personal_path } " )
2023-05-22 06:52:48 +00:00
2023-04-15 11:30:08 +00:00
2023-06-21 22:43:59 +00:00
def rebuild_personalities ( self ) :
loaded = self . mounted_personalities
2023-06-21 23:23:34 +00:00
loaded_names = [ f " { p . language } / { p . category } / { p . personality_folder_name } " for p in loaded ]
2023-06-21 22:43:59 +00:00
mounted_personalities = [ ]
ASCIIColors . success ( f " ╔══════════════════════════════════════════════════╗ " )
ASCIIColors . success ( f " ║ Building mounted Personalities ║ " )
ASCIIColors . success ( f " ╚══════════════════════════════════════════════════╝ " )
2023-06-23 07:36:52 +00:00
to_remove = [ ]
2023-06-21 22:43:59 +00:00
for i , personality in enumerate ( self . config [ ' personalities ' ] ) :
if personality in loaded_names :
mounted_personalities . append ( loaded [ loaded_names . index ( personality ) ] )
else :
2023-06-21 23:23:34 +00:00
personality_path = self . lollms_paths . personalities_zoo_path / f " { personality } "
2023-06-21 22:43:59 +00:00
try :
if i == self . config [ " active_personality_id " ] :
ASCIIColors . red ( " * " , end = " " )
2023-06-22 08:10:52 +00:00
ASCIIColors . green ( f " { personality } " )
else :
ASCIIColors . yellow ( f " { personality } " )
2023-06-21 22:43:59 +00:00
personality = AIPersonality ( personality_path ,
self . lollms_paths ,
self . config ,
2023-06-21 23:40:15 +00:00
model = self . model ,
2023-06-21 23:23:34 +00:00
run_scripts = True )
2023-06-21 22:43:59 +00:00
mounted_personalities . append ( personality )
except Exception as ex :
2023-06-21 23:23:34 +00:00
ASCIIColors . error ( f " Personality file not found or is corrupted ( { personality_path } ). \n Returned the following exception: { ex } \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. " )
2023-06-23 07:36:52 +00:00
ASCIIColors . info ( " Trying to force reinstall " )
2023-06-21 22:43:59 +00:00
if self . config [ " debug " ] :
print ( ex )
2023-06-23 06:49:05 +00:00
try :
personality = AIPersonality (
personality_path ,
self . lollms_paths ,
self . config ,
self . model ,
run_scripts = True ,
installation_option = InstallOption . FORCE_INSTALL )
2023-06-23 07:36:52 +00:00
mounted_personalities . append ( personality )
2023-06-23 06:49:05 +00:00
except :
ASCIIColors . error ( f " Couldn ' t load personality at { personality_path } " )
2023-06-23 07:36:52 +00:00
ASCIIColors . info ( f " Unmounting personality " )
to_remove . append ( i )
2023-06-23 06:49:05 +00:00
personality = AIPersonality ( None , self . lollms_paths ,
self . config ,
self . model ,
run_scripts = True ,
installation_option = InstallOption . FORCE_INSTALL )
2023-06-23 07:36:52 +00:00
mounted_personalities . append ( personality )
2023-06-23 06:49:05 +00:00
ASCIIColors . info ( " Reverted to default personality " )
2023-06-21 22:43:59 +00:00
print ( f ' selected : { self . config [ " active_personality_id " ] } ' )
ASCIIColors . success ( f " ╔══════════════════════════════════════════════════╗ " )
ASCIIColors . success ( f " ║ Done ║ " )
ASCIIColors . success ( f " ╚══════════════════════════════════════════════════╝ " )
2023-06-23 07:36:52 +00:00
# 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
2023-06-21 22:43:59 +00:00
return mounted_personalities
2023-06-22 21:33:57 +00:00
# ================================== LOLLMSApp
def load_binding ( self ) :
if self . config . binding_name is None :
print ( f " No bounding selected " )
print ( " Please select a valid model or install a new one from a url " )
self . menu . select_binding ( )
# cfg.download_model(url)
else :
try :
self . binding = BindingBuilder ( ) . build_binding ( self . config , self . lollms_paths )
except Exception as ex :
print ( ex )
print ( f " Couldn ' t find binding. Please verify your configuration file at { self . config . file_path } or use the next menu to select a valid binding " )
print ( f " Trying to reinstall binding " )
self . binding = BindingBuilder ( ) . build_binding ( self . config , self . lollms_paths , InstallOption . FORCE_INSTALL )
self . menu . select_binding ( )
def load_model ( self ) :
try :
self . active_model = ModelBuilder ( self . binding ) . get_model ( )
ASCIIColors . success ( " Model loaded successfully " )
except Exception as ex :
ASCIIColors . error ( f " Couldn ' t load model. " )
ASCIIColors . error ( f " Binding returned this exception : { ex } " )
ASCIIColors . error ( f " { self . config . get_model_path_infos ( ) } " )
print ( " Please select a valid model or install a new one from a url " )
self . menu . select_model ( )
def load_personality ( self ) :
try :
self . personality = PersonalityBuilder ( self . lollms_paths , self . config , self . model ) . build_personality ( )
except Exception as ex :
ASCIIColors . error ( f " Couldn ' t load personality. " )
ASCIIColors . error ( f " Binding returned this exception : { ex } " )
ASCIIColors . error ( f " { self . config . get_personality_path_infos ( ) } " )
print ( " Please select a valid model or install a new one from a url " )
self . menu . select_model ( )
self . cond_tk = self . personality . model . tokenize ( self . personality . personality_conditioning )
self . n_cond_tk = len ( self . cond_tk )
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 :
2023-06-23 12:44:25 +00:00
callback ( downloaded_size , total_size )
2023-05-14 11:33:45 +00:00
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 :
2023-06-23 14:19:01 +00:00
callback ( total_size , total_size )
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 ,
2023-06-15 12:19:25 +00:00
- 1 ,
binding = self . config [ " binding_name " ] ,
model = self . config [ " model_name " ] ,
2023-06-14 22:26:12 +00:00
personality = self . config [ " personalities " ] [ self . config [ " active_personality_id " ] ]
2023-05-09 05:06:01 +00:00
)
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 ) :
2023-06-21 22:43:59 +00:00
self . current_generated_text = " "
2023-04-15 11:30:08 +00:00
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-06-21 22:43:59 +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 ( ) )
2023-04-23 22:19:15 +00:00
2023-06-21 22:43:59 +00:00
if index != - 1 :
string = string [ : index ]
return string
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-27 06:57:32 +00:00
if message_type == MSG_TYPE . MSG_TYPE_STEP_START :
ASCIIColors . info ( " --> Step started: " + chunk )
if message_type == MSG_TYPE . MSG_TYPE_STEP_END :
ASCIIColors . success ( " --> Step ended: " + chunk )
if message_type == MSG_TYPE . MSG_TYPE_EXCEPTION :
ASCIIColors . error ( " --> Exception from personality: " + chunk )
2023-06-05 22:17:23 +00:00
if message_type == MSG_TYPE . MSG_TYPE_CHUNK :
2023-06-21 22:43:59 +00:00
self . current_generated_text + = chunk
detected_anti_prompt = False
anti_prompt_to_remove = " "
for prompt in self . personality . anti_prompts :
if prompt . lower ( ) in self . current_generated_text . lower ( ) :
detected_anti_prompt = True
anti_prompt_to_remove = prompt . lower ( )
if not detected_anti_prompt :
ASCIIColors . green ( f " generated: { len ( self . current_generated_text ) } words " , end = ' \r ' )
self . socketio . emit ( ' message ' , {
' data ' : self . current_generated_text ,
' 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-27 09:23:52 +00:00
' message_type ' : MSG_TYPE . MSG_TYPE_FULL . value
2023-06-21 22:43:59 +00:00
} , room = self . current_room_id
)
2023-06-21 23:23:34 +00:00
self . socketio . sleep ( 0 )
2023-06-21 22:43:59 +00:00
self . current_discussion . update_message ( self . current_ai_message_id , self . current_generated_text )
# if stop generation is detected then stop
if not self . cancel_gen :
return True
else :
2023-06-22 12:52:04 +00:00
self . cancel_gen = False
ASCIIColors . warning ( " Generation canceled " )
2023-06-21 22:43:59 +00:00
return False
else :
self . current_generated_text = self . remove_text_from_string ( self . current_generated_text , anti_prompt_to_remove )
2023-06-27 09:09:52 +00:00
ASCIIColors . warning ( " The model is halucinating " )
2023-06-21 22:43:59 +00:00
return False
# Stream the generated text to the main process
elif message_type == MSG_TYPE . MSG_TYPE_FULL :
self . current_generated_text = chunk
2023-05-28 21:26:05 +00:00
self . socketio . emit ( ' message ' , {
2023-06-21 22:43:59 +00:00
' data ' : self . current_generated_text ,
' user_message_id ' : self . current_user_message_id ,
' ai_message_id ' : self . current_ai_message_id ,
' discussion_id ' : self . current_discussion . discussion_id ,
' message_type ' : message_type . value
} , room = self . current_room_id
)
2023-06-21 23:23:34 +00:00
self . socketio . sleep ( 0 )
2023-06-21 22:43:59 +00:00
return True
2023-06-27 06:57:32 +00:00
# Stream the generated text to the frontend
2023-06-21 22:43:59 +00:00
else :
self . socketio . emit ( ' message ' , {
2023-06-27 06:57:32 +00:00
' data ' : chunk ,
2023-05-28 21:26:05 +00:00
' 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-06-10 21:09:56 +00:00
} , room = self . current_room_id
2023-05-28 21:26:05 +00:00
)
2023-06-21 23:23:34 +00:00
self . socketio . sleep ( 0 )
2023-05-26 14:22:02 +00:00
2023-06-21 22:43:59 +00:00
return True
def generate ( self , full_prompt , prompt , n_predict = 50 , callback = None ) :
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 " ] :
ASCIIColors . success ( " Running workflow " )
2023-06-21 23:40:15 +00:00
try :
output = self . personality . processor . run_workflow ( prompt , full_prompt , self . process_chunk )
self . process_chunk ( output , MSG_TYPE . MSG_TYPE_FULL )
except Exception as ex :
ASCIIColors . error ( f " Workflow run failed. \n Error: { ex } " )
self . process_chunk ( f " Workflow run failed \n Error: { ex } " , MSG_TYPE . MSG_TYPE_EXCEPTION )
2023-06-21 22:43:59 +00:00
print ( " Finished executing the workflow " )
return
self . _generate ( full_prompt , n_predict , callback )
print ( " Finished executing the generation " )
2023-05-13 22:24:26 +00:00
2023-06-21 22:43:59 +00:00
def _generate ( self , prompt , n_predict = 50 , callback = None ) :
self . current_generated_text = " "
if self . model is not None :
ASCIIColors . info ( " warmup " )
if self . config [ " override_personality_model_parameters " ] :
output = self . model . generate (
prompt ,
callback = callback ,
n_predict = n_predict ,
temperature = self . config [ ' temperature ' ] ,
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 :
output = self . model . generate (
prompt ,
callback = callback ,
n_predict = self . personality . model_n_predicts ,
temperature = self . personality . model_temperature ,
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 ' ]
)
else :
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. " )
print ( " To do this: Install the model to your models/<binding name> folder. " )
print ( " Then set your model information in your local configuration file that you can find in configs/local_config.yaml " )
print ( " You can also use the ui to set your model in the settings page. " )
output = " "
return output
def start_message_generation ( self , message , message_id ) :
ASCIIColors . info ( f " Text generation requested by client: { self . current_room_id } " )
2023-05-13 22:24:26 +00:00
# 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 (
2023-06-15 19:19:19 +00:00
self . personality . name ,
" " ,
2023-06-15 20:18:56 +00:00
parent = self . current_user_message_id ,
2023-06-17 21:52:34 +00:00
binding = self . config [ " binding_name " ] ,
2023-06-15 20:18:56 +00:00
model = self . config [ " model_name " ] ,
2023-06-17 21:52:34 +00:00
personality = self . config [ " personalities " ] [ self . config [ " active_personality_id " ] ]
2023-05-13 22:24:26 +00:00
) # 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-06-18 07:06:52 +00:00
' binding ' : self . current_discussion . current_message_binding ,
' model ' : self . current_discussion . current_message_model ,
' personality ' : self . current_discussion . current_message_personality ,
' created_at ' : self . current_discussion . current_message_created_at ,
' finished_generating_at ' : self . current_discussion . current_message_finished_generating_at ,
2023-06-10 21:09:56 +00:00
} , room = self . current_room_id
2023-05-05 12:23:07 +00:00
)
2023-06-21 23:23:34 +00:00
self . socketio . sleep ( 0 )
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-06-21 22:43:59 +00:00
self . generate ( self . discussion_messages , self . current_message , n_predict = self . config [ ' n_predict ' ] , callback = self . process_chunk )
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 ( )
2023-06-21 22:43:59 +00:00
self . current_discussion . update_message ( self . current_ai_message_id , self . current_generated_text )
self . full_message_list . append ( self . current_generated_text )
2023-06-18 07:06:52 +00:00
self . cancel_gen = False
2023-05-13 22:24:26 +00:00
# Send final message
self . socketio . emit ( ' final ' , {
2023-06-21 22:43:59 +00:00
' data ' : self . current_generated_text ,
2023-05-13 22:24:26 +00:00
' ai_message_id ' : self . current_ai_message_id ,
2023-06-16 20:19:39 +00:00
' parent ' : self . current_user_message_id , ' discussion_id ' : self . current_discussion . discussion_id ,
" status " : ' model_not_ready ' ,
" type " : " input_message_infos " ,
' logo ' : " " ,
" bot " : self . personality . name ,
" user " : self . personality . user_name ,
2023-06-21 22:43:59 +00:00
" message " : self . current_generated_text ,
2023-06-16 20:19:39 +00:00
" user_message_id " : self . current_user_message_id ,
" ai_message_id " : self . current_ai_message_id ,
2023-06-18 07:06:52 +00:00
' binding ' : self . current_discussion . current_message_binding ,
' model ' : self . current_discussion . current_message_model ,
' personality ' : self . current_discussion . current_message_personality ,
' created_at ' : self . current_discussion . current_message_created_at ,
' finished_generating_at ' : self . current_discussion . current_message_finished_generating_at ,
2023-06-10 21:09:56 +00:00
} , room = self . current_room_id
2023-05-13 22:24:26 +00:00
)
2023-06-21 23:23:34 +00:00
self . socketio . sleep ( 0 )
2023-05-13 22:24:26 +00:00
2023-05-28 23:25:25 +00:00
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 " "