###### # Project : lollms-webui # File : api.py # Author : ParisNeo with the help of the community # Supported by Nomic-AI # license : Apache 2.0 # Description : # A simple api to communicate with lollms-webui and its models. ###### from flask import request from datetime import datetime from api.db import DiscussionsDB from api.helpers import compare_lists from pathlib import Path import importlib from lollms.config import InstallOption from lollms.personality import AIPersonality, MSG_TYPE from lollms.binding import LOLLMSConfig, BindingBuilder, LLMBinding from lollms.paths import LollmsPaths from lollms.helpers import ASCIIColors import multiprocessing as mp import threading import time import requests from tqdm import tqdm import traceback import sys from lollms.console import MainMenu __author__ = "parisneo" __github__ = "https://github.com/ParisNeo/lollms-webui" __copyright__ = "Copyright 2023, " __license__ = "Apache 2.0" 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) # =========================================================== class LoLLMsAPPI(): def __init__(self, config:LOLLMSConfig, socketio, config_file_path:str, lollms_paths: LollmsPaths) -> None: self.lollms_paths = lollms_paths self.config = config self.is_ready = True self.menu = MainMenu(self) self.socketio = socketio # Check model if config.binding_name is None: self.menu.select_model() self.binding = BindingBuilder().build_binding(self.config, self.lollms_paths) # Check model if config.model_name is None: self.menu.select_model() self.model = self.binding.build_model() self.mounted_personalities = [] self.mounted_personalities = self.rebuild_personalities() if self.config["active_personality_id"] self.config["nb_messages_to_remember"]: discussion_messages = self.personality.personality_conditioning+ link_text.join(self.full_message_list[-self.config["nb_messages_to_remember"]:]) else: discussion_messages = self.personality.personality_conditioning+ link_text.join(self.full_message_list) return discussion_messages # Removes the last return 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 def process_chunk(self, chunk, message_type:MSG_TYPE): """ 0 : a regular message 1 : a notification message 2 : A hidden message """ if message_type == MSG_TYPE.MSG_TYPE_CHUNK: 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, 'message_type': message_type.value }, room=self.current_room_id ) self.socketio.sleep(0) 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: self.cancel_gen = False ASCIIColors.warning("Generation canceled") return False else: self.current_generated_text = self.remove_text_from_string(self.current_generated_text, anti_prompt_to_remove) print("The model is halucinating") return False # Stream the generated text to the main process elif message_type == MSG_TYPE.MSG_TYPE_FULL: self.current_generated_text = chunk 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, 'message_type': message_type.value }, room=self.current_room_id ) self.socketio.sleep(0) return True # Stream the generated text to the main process else: 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, 'message_type': message_type.value }, room=self.current_room_id ) self.socketio.sleep(0) 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") 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.\nError:{ex}") self.process_chunk(f"Workflow run failed\nError:{ex}", MSG_TYPE.MSG_TYPE_EXCEPTION) print("Finished executing the workflow") return self._generate(full_prompt, n_predict, callback) print("Finished executing the generation") 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/ 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}") # 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, binding = self.config["binding_name"], model = self.config["model_name"], personality = self.config["personalities"][self.config["active_personality_id"]] ) # first the content is empty, but we'll fill it at the end self.socketio.emit('infos', { "status":'generation_started', "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, '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, }, room=self.current_room_id ) self.socketio.sleep(0) # prepare query and reception self.discussion_messages, self.current_message = self.prepare_query(message_id) self.prepare_reception() self.generating = True self.generate(self.discussion_messages, self.current_message, n_predict = self.config['n_predict'], callback=self.process_chunk) print() print("## Done Generation ##") print() self.current_discussion.update_message(self.current_ai_message_id, self.current_generated_text) self.full_message_list.append(self.current_generated_text) self.cancel_gen = False # Send final message self.socketio.emit('final', { 'data': self.current_generated_text, 'ai_message_id':self.current_ai_message_id, '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, "message":self.current_generated_text, "user_message_id": self.current_user_message_id, "ai_message_id": self.current_ai_message_id, '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, }, room=self.current_room_id ) self.socketio.sleep(0) print() print("## Done ##") print() else: #No discussion available print("No discussion selected!!!") print("## Done ##") print() self.cancel_gen = False return ""