added better documentation

This commit is contained in:
Falko Victor Habel 2024-05-20 13:24:41 +02:00
parent 52310a9021
commit 4a8026ec72
5 changed files with 43 additions and 35 deletions

View File

@ -4,6 +4,7 @@ class OllamaChatBot:
def __init__(self, base_url, model, headers): def __init__(self, base_url, model, headers):
self.base_url = base_url self.base_url = base_url
self.model = model self.model = model
# check if header exists
if self.is_empty(headers): if self.is_empty(headers):
self.headers = "" self.headers = ""
else: else:
@ -22,12 +23,11 @@ class OllamaChatBot:
headers = self.headers headers = self.headers
) )
def is_empty(self, dictionary): def is_empty(self, dictionary: dict) -> bool:
return len(dictionary) == 1 and list(dictionary.keys())[0] == '' and list(dictionary.values())[0] == '' return len(dictionary) == 1 and list(dictionary.keys())[0] == '' and list(dictionary.values())[0] == ''
def get_request(self, prompt: str) -> str:
def get_request(self, prompt):
messanges = [] messanges = []
self.messanges.append(prompt) self.messanges.append(prompt)
if len(self.messanges) > 5: if len(self.messanges) > 5:

View File

@ -24,7 +24,7 @@ class ChatGUI(CTk.CTk):
self.create_widgets() self.create_widgets()
self.start_message_processing_thread() self.start_message_processing_thread()
def get_response_from_ollama(self, prompt, context): def get_response_from_ollama(self, prompt: str, context: str):
try: try:
if context != "": if context != "":
if self.context != context: if self.context != context:
@ -52,7 +52,7 @@ class ChatGUI(CTk.CTk):
self.entry_bar.delete(0, CTk.END) # Clear input field after sending self.entry_bar.delete(0, CTk.END) # Clear input field after sending
Thread(target=lambda q, arg1, arg2: q.put(self.get_response_from_ollama(arg1, arg2)), args=(self.message_queue, message, context)).start() Thread(target=lambda q, arg1, arg2: q.put(self.get_response_from_ollama(arg1, arg2)), args=(self.message_queue, message, context)).start()
def show_reply(self, message): def show_reply(self, message: str):
bot_reply = Reply(master=self.messages_frame,reply_type = "Fabelous-AI-Bot", message=message) bot_reply = Reply(master=self.messages_frame,reply_type = "Fabelous-AI-Bot", message=message)
self.history.append(bot_reply) self.history.append(bot_reply)
bot_reply.pack(anchor="w", padx=5, pady=2) bot_reply.pack(anchor="w", padx=5, pady=2)
@ -115,7 +115,7 @@ class ChatGUI(CTk.CTk):
self.history = [] self.history = []
self.bot.messanges = [] self.bot.messanges = []
self.rag.init_ollama() self.rag.init_ollama()
self.file_entry.delete(0, "end")
def start_message_processing_thread(self): def start_message_processing_thread(self):

View File

@ -7,7 +7,6 @@ class Reply(tk.Frame):
def __init__(self, master, message,reply_type, font_size=12, background="#252525", text_color="white"): def __init__(self, master, message,reply_type, font_size=12, background="#252525", text_color="white"):
super().__init__(master) super().__init__(master)
# Define style configurations
self.font = ("Helvetica", font_size) self.font = ("Helvetica", font_size)
self.background = background self.background = background
self.text_color = text_color self.text_color = text_color
@ -16,7 +15,7 @@ class Reply(tk.Frame):
self.message = self.extract_code(message) self.message = self.extract_code(message)
self.reply_scope = [] self.reply_scope = []
# Adjust the overall background of the ttk.Notebook # change background of message
self.configure(background=self.background) self.configure(background=self.background)
@ -28,6 +27,7 @@ class Reply(tk.Frame):
row_index = 1 # Track the current grid row for widgets row_index = 1 # Track the current grid row for widgets
for part in self.message: for part in self.message:
# part is a code block
if part.startswith(CODE_PREFIX): if part.startswith(CODE_PREFIX):
part = part[len(CODE_PREFIX):] part = part[len(CODE_PREFIX):]
code = tk.Text(master=self, width=50, font=self.font, code = tk.Text(master=self, width=50, font=self.font,
@ -48,22 +48,31 @@ class Reply(tk.Frame):
row_index += 1 row_index += 1
def extract_code(self, input_string, replacement=CODE_PREFIX): def extract_code(self, input_string: str, replacement=CODE_PREFIX) -> list:
split_parts = re.split(r'(```)', input_string) # Split the input string on the ``` delimiter
output_array = [] split_parts = re.split(r'(```)', input_string) # Include the delimiter in the results
previously_delimiter = False
for part in split_parts: # Initialize an empty list to store the output array
if part == "```": output_array = []
previously_delimiter = True
continue
if previously_delimiter: # Track whether the previous part was a ``` delimiter
part = re.sub(r'^\b\w+\b', replacement, part, count=1) previously_delimiter = False
previously_delimiter = False
if part.strip():
output_array.append(part)
return output_array for part in split_parts:
# Check if the current part is a ``` delimiter
if part == "```":
previously_delimiter = True # Set flag if a delimiter is found
continue # Skip adding the delimiter to the output
# If the previous part was a delimiter, replace the first word with the specified string
if previously_delimiter:
part = re.sub(r'^\b\w+\b', replacement, part, count=1) # Replace the programming Language
previously_delimiter = False # Reset the flag
# Only add non-empty parts to the output array
if part.strip():
output_array.append(part)
return output_array

View File

@ -20,7 +20,7 @@ class Rag:
self.base_url_llm = base_url_llm self.base_url_llm = base_url_llm
self.base_url_embed = base_url_embed self.base_url_embed = base_url_embed
# check if header exists
if self.is_empty(base_header): if self.is_empty(base_header):
self.base_header = "" self.base_header = ""
else: else:
@ -38,7 +38,7 @@ class Rag:
headers = self.base_header headers = self.base_header
) )
def get_file(self, file_path): def get_file(self, file_path: str):
# Check if the file path starts with 'https://' # Check if the file path starts with 'https://'
if file_path.startswith('https://'): if file_path.startswith('https://'):
try: try:
@ -73,12 +73,10 @@ class Rag:
return True return True
def is_empty(self, dictionary): def is_empty(self, dictionary: dict) -> bool:
return len(dictionary) == 1 and list(dictionary.keys())[0] == '' and list(dictionary.values())[0] == '' return len(dictionary) == 1 and list(dictionary.keys())[0] == '' and list(dictionary.values())[0] == ''
def receive_data(self, file_path: str):
def receive_data(self, file_path):
try: try:
if self.get_file(file_path): if self.get_file(file_path):
text_splitter = RecursiveCharacterTextSplitter(chunk_size=250, chunk_overlap=0) text_splitter = RecursiveCharacterTextSplitter(chunk_size=250, chunk_overlap=0)
@ -89,10 +87,11 @@ class Rag:
return (True, f"'{file_path}' unsupported, read documentation for more information") return (True, f"'{file_path}' unsupported, read documentation for more information")
except (ValueError, AttributeError) as e: except (ValueError, AttributeError) as e:
return (True, f"An unexpected Error occuried: {e}") return (True, f"An unexpected Error occuried: {e}")
def get_request(self, prompt):
def get_request(self, prompt: str) -> str:
qachain=RetrievalQA.from_chain_type(self.chat_ollama, retriever=self.retriever) qachain=RetrievalQA.from_chain_type(self.chat_ollama, retriever=self.retriever)
try: try:
return qachain.invoke({"query": prompt})["result"] return qachain.invoke({"query": prompt})["result"]
except ValueError as e: except ValueError as e:
return (True, f"An unexpected Error occuried: {e}") return f"An unexpected Error occuried: {e}"

View File

@ -70,7 +70,7 @@ class TerminalBot:
else: else:
print(colored(message + "\n", "white")) print(colored(message + "\n", "white"))
def extract_code(self, input_string, replacement=CODE_PREFIX): def extract_code(self, input_string, replacement=CODE_PREFIX) -> list:
# Split the input string on the ``` delimiter # Split the input string on the ``` delimiter
split_parts = re.split(r'(```)', input_string) # Include the delimiter in the results split_parts = re.split(r'(```)', input_string) # Include the delimiter in the results
@ -89,7 +89,7 @@ class TerminalBot:
# If the previous part was a delimiter, replace the first word with the specified string # If the previous part was a delimiter, replace the first word with the specified string
if previously_delimiter: if previously_delimiter:
part = re.sub(r'^\b\w+\b', replacement, part, count=1) # Replace the first word part = re.sub(r'^\b\w+\b', replacement, part, count=1) # Replace the programming Language
previously_delimiter = False # Reset the flag previously_delimiter = False # Reset the flag
# Only add non-empty parts to the output array # Only add non-empty parts to the output array