lollms-webui/endpoints/chat_bar.py

159 lines
7.0 KiB
Python
Raw Normal View History

2024-01-07 23:22:23 +00:00
"""
project: lollms_webui
file: chat_bar.py
author: ParisNeo
description:
This module contains a set of FastAPI routes that provide information about the Lord of Large Language and Multimodal Systems (LoLLMs) Web UI
application. These routes are linked to lollms_webui chatbox
"""
from fastapi import APIRouter, Request
2024-03-17 14:10:24 +00:00
from fastapi import HTTPException
2024-03-17 02:25:52 +00:00
from pydantic import BaseModel, Field
2024-01-07 23:22:23 +00:00
from lollms_webui import LOLLMSWebUI
from pydantic import BaseModel
from starlette.responses import StreamingResponse
2024-08-14 20:15:45 +00:00
from lollms.types import MSG_OPERATION_TYPE
2024-01-07 23:22:23 +00:00
from lollms.main_config import BaseConfig
2024-03-17 02:25:52 +00:00
from lollms.utilities import detect_antiprompt, remove_text_from_string, trace_exception, find_first_available_file_index
2024-01-07 23:22:23 +00:00
from ascii_colors import ASCIIColors
from lollms.databases.discussions_database import DiscussionsDB
2024-03-17 02:25:52 +00:00
from lollms.types import SENDER_TYPES
from typing import List
2024-01-07 23:22:23 +00:00
from pathlib import Path
import tqdm
from fastapi import FastAPI, UploadFile, File
import shutil
import os
import platform
2024-03-28 22:58:51 +00:00
from urllib.parse import urlparse
2024-03-17 02:25:52 +00:00
from functools import partial
from datetime import datetime
2024-01-07 23:22:23 +00:00
from utilities.execution_engines.python_execution_engine import execute_python
from utilities.execution_engines.latex_execution_engine import execute_latex
from utilities.execution_engines.shell_execution_engine import execute_bash
2024-03-28 22:58:51 +00:00
from lollms.security import sanitize_path, forbid_remote_access
2024-03-17 14:10:24 +00:00
from lollms.internet import scrape_and_save
2024-03-28 22:58:51 +00:00
from urllib.parse import urlparse
2024-03-17 14:10:24 +00:00
import threading
2024-01-09 22:26:41 +00:00
# ----------------------- Defining router and main class ------------------------------
2024-01-07 23:22:23 +00:00
router = APIRouter()
lollmsElfServer:LOLLMSWebUI = LOLLMSWebUI.get_instance()
2024-03-17 02:25:52 +00:00
class AddWebPageRequest(BaseModel):
client_id: str = Field(...)
url: str = Field(..., description="Url to be used")
class CmdExecutionRequest(BaseModel):
client_id: str = Field(...)
command: str = Field(..., description="Url to be used")
2024-03-28 22:58:51 +00:00
parameters: List[str] = Field(..., description="Command parameters")
2024-03-17 02:25:52 +00:00
2024-03-17 14:10:24 +00:00
"""
2024-03-17 02:25:52 +00:00
@router.post("/execute_personality_command")
async def execute_personality_command(request: CmdExecutionRequest):
client_id = request.client_id
client = lollmsElfServer.session.get_client(client_id)
lollmsElfServer.cancel_gen = False
client.generated_text=""
client.cancel_generation=False
client.continuing=False
client.first_chunk=True
if not lollmsElfServer.model:
ASCIIColors.error("Model not selected. Please select a model")
lollmsElfServer.error("Model not selected. Please select a model", client_id=client_id)
return {'status':False,"error":"Model not selected. Please select a model"}
if not lollmsElfServer.busy:
if lollmsElfServer.session.get_client(client_id).discussion is None:
if lollmsElfServer.db.does_last_discussion_have_messages():
lollmsElfServer.session.get_client(client_id).discussion = lollmsElfServer.db.create_discussion()
else:
lollmsElfServer.session.get_client(client_id).discussion = lollmsElfServer.db.load_last_discussion()
ump = lollmsElfServer.config.discussion_prompt_separator +lollmsElfServer.config.user_name.strip() if lollmsElfServer.config.use_user_name_in_discussions else lollmsElfServer.personality.user_message_prefix
message = lollmsElfServer.session.get_client(client_id).discussion.add_message(
2024-08-14 20:15:45 +00:00
message_type = MSG_OPERATION_TYPE.MSG_OPERATION_TYPE_SET_CONTENT.value,
2024-03-17 02:25:52 +00:00
sender_type = SENDER_TYPES.SENDER_TYPES_USER.value,
sender = ump.replace(lollmsElfServer.config.discussion_prompt_separator,"").replace(":",""),
content="",
metadata=None,
parent_message_id=lollmsElfServer.message_id
)
lollmsElfServer.busy=True
command = request.command
parameters = request.parameters
lollmsElfServer.prepare_reception(client_id)
if lollmsElfServer.personality.processor is not None:
lollmsElfServer.start_time = datetime.now()
2024-08-15 15:28:33 +00:00
lollmsElfServer.personality.processor.callback = partial(lollmsElfServer.process_data, client_id=client_id)
2024-03-17 02:25:52 +00:00
lollmsElfServer.personality.processor.execute_command(command, parameters)
else:
lollmsElfServer.warning("Non scripted personalities do not support commands",client_id=client_id)
lollmsElfServer.close_message(client_id)
lollmsElfServer.busy=False
#tpe = threading.Thread(target=lollmsElfServer.start_message_generation, args=(message, message_id, client_id))
#tpe.start()
else:
lollmsElfServer.error("I am busy. Come back later.", client_id=client_id)
return {'status':False,"error":"I am busy. Come back later."}
lollmsElfServer.busy=False
return {'status':True,}
2024-03-17 14:10:24 +00:00
"""
2024-03-28 22:58:51 +00:00
MAX_PAGE_SIZE = 10000000
2024-03-17 02:25:52 +00:00
@router.post("/add_webpage")
async def add_webpage(request: AddWebPageRequest):
2024-03-28 22:58:51 +00:00
forbid_remote_access(lollmsElfServer)
2024-03-17 02:25:52 +00:00
client = lollmsElfServer.session.get_client(request.client_id)
2024-03-17 14:10:24 +00:00
if client is None:
raise HTTPException(status_code=400, detail="Unknown client. This service only accepts lollms webui requests")
def do_scraping():
lollmsElfServer.ShowBlockingMessage("Scraping web page\nPlease wait...")
ASCIIColors.yellow("Scaping web page")
client = lollmsElfServer.session.get_client(request.client_id)
url = request.url
2024-05-13 12:25:58 +00:00
index = find_first_available_file_index(client.discussion.discussion_folder/"text_data","web_",".txt")
2024-03-31 01:01:12 +00:00
try:
2024-05-13 12:25:58 +00:00
file_path=sanitize_path(str(client.discussion.discussion_folder/"text_data"/f"web_{index}.txt"),True)
2024-03-31 01:01:12 +00:00
except Exception as ex:
lollmsElfServer.HideBlockingMessage()
raise ex
2024-03-28 22:58:51 +00:00
try:
result = urlparse(url)
if all([result.scheme, result.netloc]): # valid URL
2024-03-31 01:01:12 +00:00
if not scrape_and_save(url=url, file_path=file_path,max_size=MAX_PAGE_SIZE):
lollmsElfServer.HideBlockingMessage()
2024-03-28 22:58:51 +00:00
raise HTTPException(status_code=400, detail="Web page too large")
else:
2024-03-31 01:01:12 +00:00
lollmsElfServer.HideBlockingMessage()
2024-03-28 22:58:51 +00:00
raise HTTPException(status_code=400, detail="Invalid URL")
except Exception as e:
2024-03-31 01:01:12 +00:00
trace_exception(e)
lollmsElfServer.HideBlockingMessage()
2024-03-28 22:58:51 +00:00
raise HTTPException(status_code=400, detail=f"Exception : {e}")
2024-03-17 14:10:24 +00:00
try:
2024-08-15 15:28:33 +00:00
client.discussion.add_file(file_path, client, partial(lollmsElfServer.process_data, client_id = request.client_id))
2024-03-17 14:10:24 +00:00
# File saved successfully
lollmsElfServer.HideBlockingMessage()
lollmsElfServer.refresh_files()
except Exception as e:
# Error occurred while saving the file
lollmsElfServer.HideBlockingMessage()
lollmsElfServer.refresh_files()
return {'status':False,"error":str(e)}
client.generation_thread = threading.Thread(target=do_scraping)
client.generation_thread.start()
return {'status':True}