forked from AIexandr/LordGPT
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLordGPT.py
1453 lines (1192 loc) · 52.5 KB
/
LordGPT.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# region ### IMPORTS ###
# Standard library imports
import os
import sys
import re
import time
import random
import json
import subprocess
import datetime
import ssl
import requests
import shutil
import traceback
import logging
import inspect
from collections import deque
from time import sleep
from typing import Dict
# Third-party imports
from requests.exceptions import ReadTimeout
from dotenv import load_dotenv
from termcolor import colored
from bs4 import BeautifulSoup
from fake_useragent import UserAgent
from unidecode import unidecode
from yaspin import yaspin
from serpapi import GoogleSearch
import pdfkit
import urllib.request
from playwright.sync_api import sync_playwright
# Local file imports
from scripts.bot_prompts import *
from scripts.bot_commands import *
from scripts.func_prompt import *
current_version = "2.4"
current_path = os.getcwd()
working_folder = os.path.join(current_path, "LordGPT_folder")
if not os.path.exists(working_folder):
os.makedirs(working_folder)
session = PromptSession()
# endregion
# region ### DEBUG CODE ###
debug_code = True
logging.basicConfig(filename="debug.log", level=logging.DEBUG)
logger = logging.getLogger(__name__)
logger.debug("Debug message")
logger.info("Info message")
logger.warning("Warning message")
logger.error("Error message")
logger.critical("Critical message")
def log_all_functions(logger, log_vars_callback=None):
def decorator(func):
def wrapper(*args, **kwargs):
entry_time = time.time()
logger.debug("Entering function {}() at {}".format(func.__name__, entry_time))
logger.debug("Input arguments: {}, {}".format(args, kwargs))
logger.debug("Input argument types: {}".format({k: type(v) for k, v in zip(inspect.signature(func).parameters.keys(), args)}))
try:
result = func(*args, **kwargs)
exit_time = time.time()
elapsed_time = exit_time - entry_time
# Log specific variables
if log_vars_callback is not None:
log_vars = log_vars_callback()
for index, (var, value) in enumerate(log_vars.items(), start=1):
logger.debug("Variable{} ({}): {}".format(index, var, value))
logger.debug("Function {}() executed successfully at {}".format(func.__name__, exit_time))
logger.debug("Output: {}".format(result))
logger.debug("Elapsed time: {} seconds".format(elapsed_time))
logger.debug("Model Type: " + model)
logger.debug("Message History: " + str(message_history))
logger.debug("Command String: " + str(command_string))
logger.debug("Command Argument: " + str(command_argument))
logger.debug("Self Prompt: " + str(self_prompt_action))
logger.debug("Current Task: " + str(current_task))
logger.debug("System Directive: " + str(system_directive))
return result
except Exception as e:
logger.error("Function {}() raised an exception: {}".format(func.__name__, e))
raise
return wrapper
return decorator
def log_exception(exc_type, exc_value, exc_traceback):
# Log the exception to a file
with open("exceptions.log", "a") as f:
f.write("\n\n" + "=" * 80 + "\n")
f.write(f"Exception Timestamp: {datetime.datetime.now()}\n")
traceback.print_exception(exc_type, exc_value, exc_traceback, file=f)
# Ask the user for permission to collect telemetry
if telemetry_choice == "y":
# Send the exception content to Discord
exc_str = "".join(traceback.format_exception(exc_type, exc_value, exc_traceback))
message = f"Exception Timestamp: {datetime.datetime.now()}\n```{exc_str}```"
sys.excepthook = log_exception
def telemetry_data(description, message):
if telemetry_choice == "y":
url = "https://discord.com/api/webhooks/1103090713345921034/awCGnH5nC782FtN7qLJcKBr0_kTNhVmLSwgctCayXFrxR_FtZgxHzM8jqFlzCTGdwzHT"
payload = {
"content": description + " " + message
}
headers = {'Content-Type': 'application/json'}
response = requests.post(url, data=json.dumps(payload), headers=headers)
return
# endregion
# region ### GLOBAL VARIABLES ###
config_file = "config.json"
update_url = "https://thelordg.com/downloads/version.txt"
changelog_url = "https://thelordg.com/downloads/changelog.txt"
download_link = "https://thelordg.com/downloads/LordGPT.exe"
message_history = []
api_type = ""
success = False
current_task = ""
user_goal = ""
self_prompt_action = ""
self_prompt_action = ""
command_string = ""
command_argument = ""
system_directive=""
api_count = 0
telemetry_choice = "y"
config_file = "config.json"
task_counter = 0
task_call_history = []
# endregion
# region ### GLOBAL FUNCTIONS ###
# Define the global variable system_directive
def typing_print(text, color=None):
if text is None or len(text.strip()) == 0:
return
highlight_words = {
"[COMPLETED]": "light_green",
"[FAILED]": "red",
"y": "green",
"n": "red",
}
number_pattern = re.compile(r'\[\d+(\.\d+)?\]')
quote_pattern = re.compile(r'"[^"]*":')
link_pattern = re.compile(r'(http|https)://[^\s]+')
lines = text.split('\n')
for line in lines:
colored_line = ""
words = line.split(' ')
for word in words:
word_color = highlight_words.get(word)
if word in highlight_words:
colored_word = colored(word, color=highlight_words[word])
elif number_pattern.match(word):
colored_word = colored(word, color="light_blue")
elif quote_pattern.match(word):
colored_word = colored(word, color="light_green")
elif link_pattern.match(word):
colored_word = colored(word, color="blue", attrs=["underline"])
else:
colored_word = colored(word, color=color) if color else word
colored_line += colored_word + " "
for char in colored_line:
print(char, end="", flush=True)
time.sleep(0.002) # adjust delay time as desired
print()
def sys_directive_handler(command_issued, status):
global botcommands
# Handle None and blank command_issued values
if command_issued is None or command_issued.strip() == "":
return "No Sys Directive at this time"
# Check if the command exists in the botcommands list
for command in botcommands:
if command["cmd_str"] == command_issued:
return command[status]
# If the command is not found in the list
return "Command not found."
def set_global_success(value):
global success
success = value
def clean_data(content: str) -> str:
data_str = str(content)
data_str = data_str.replace("\n", " ")
data_str = data_str.replace("\\n", " ")
data_str = data_str.replace('"', " ")
data_str = data_str.replace("'", " ")
data_str = re.sub(r"[\u0080-\uffff]", " ", data_str)
return data_str
def check_for_updates():
try:
update_response = requests.get(update_url)
update_response.raise_for_status()
latest_version = update_response.text.strip()
if latest_version > current_version:
typing_print(
colored(
f"A new version ({latest_version}) is available! Please visit {download_link} to download the update. Github: https://github.com/Cytranics/LordGPT",
"red",
)
)
# Fetch the changelog
changelog_response = requests.get(changelog_url)
changelog_response.raise_for_status()
changelog = changelog_response.text.strip()
# Display the changelog
typing_print(colored("Changelog:", "yellow"))
typing_print(changelog)
except requests.exceptions.RequestException as e:
typing_print("Error checking for updates:", e)
check_for_updates()
def save_goal(goal):
with open("goals.txt", "a") as f:
f.write(goal + "\n")
def load_goals():
if os.path.exists("goals.txt"):
with open("goals.txt", "r") as f:
# Use a deque to keep only the last 10 lines (i.e., goals) of the file
goals_deque = deque(maxlen=5)
for line in f:
goals_deque.append(line.strip())
return list(goals_deque)
else:
return []
@log_all_functions(logger, log_vars_callback=lambda: locals())
def prompt_user_for_config():
api_key = session.prompt("OPENAI API key:https://platform.openai.com/account/api-keys - Come to our discord and message Cytranic to borrow a key: ")
search_engine_choice = session.prompt("Which search engine do you want to use? (1: Google, 2: SERP): ")
if search_engine_choice == "1":
google_api_key = session.prompt("Please enter your Google API key: ")
google_search_id = session.prompt("Please enter your Google Search ID: ")
search_engine_mode = "GOOGLE"
serp_api_key = None
elif search_engine_choice == "2":
serp_api_key = session.prompt("Please enter your SERP API key: ")
search_engine_mode = "SERP"
google_api_key = None
google_search_id = None
else:
typing_print("Invalid choice. Please choose either '1' for Google or '2' for SERP.")
model = ""
while model not in ["gpt-3.5-turbo", "gpt-4"]:
typing_print("Please select a model:")
typing_print("1. GPT-3.5")
typing_print("2. GPT-4")
model_choice = session.prompt("Choose the number of the model you have access to: ")
if model_choice == "1":
model = "gpt-3.5-turbo"
elif model_choice == "2":
model = "gpt-4"
else:
typing_print("Invalid selection. Please enter 1 or 2.")
debug_code = int(session.prompt("Enable debug.txt in working folder? (1 for Enable, 2 for Disable): ")) == 1
return {
"API_FUNCTION": "OPENAI",
"API_RETRY": 10,
"API_THROTTLE": 10,
"API_TIMEOUT": 90,
"AZURE_URL": None,
"AZURE_API_KEY": None,
"AZURE_MODEL_NAME": None,
"BD_ENABLED": False,
"BD_PASSWORD": None,
"BD_PORT": 22225,
"BD_USERNAME": None,
"DEBUG_CODE": debug_code,
"FREQUENCY_PENALTY": 0.0,
"MAX_CONVERSATION": 5,
"MAX_TOKENS": 800,
"OPENAI_API_KEY": api_key,
"OPENAI_MODEL_NAME": model,
"OPENAI_URL": "https://api.openai.com/v1/chat/completions",
"PRESENCE_PENALTY": 0.0,
"SERP_API": serp_api_key,
"TEMPERATURE": 0.2,
"TOP_P": 0.0,
"SEARCH_ENGINE_MODE": search_engine_mode,
"GOOGLE_API_KEY": google_api_key,
"CUSTOM_SEARCH_ENGINE_ID": google_search_id,
}
def load_config_from_file(config_file):
with open(config_file, "r") as f:
config_data = json.load(f)
return config_data
def load_variables(frozen):
if frozen:
typing_print("Frozen Detected")
if os.path.exists(config_file):
config_data = load_config_from_file(config_file)
else:
config_data = prompt_user_for_config()
typing_print("Configuration saved to config.json, edit the file to change advanced settings")
with open(config_file, "w") as f:
json.dump(config_data, f)
return config_data
else:
load_dotenv(override=True)
return os.environ
def get_variable(env_data, variable_name, default_value=None, variable_type=None):
value = env_data.get(variable_name, default_value)
if variable_type == "int":
return int(value)
elif variable_type == "float":
return float(value)
elif variable_type == "bool":
return value == "True"
return value
frozen = getattr(sys, "frozen", False)
env_data = load_variables(frozen)
api_function = get_variable(env_data, "API_FUNCTION", "OPENAI")
api_retry = get_variable(env_data, "API_RETRY", 10, "int")
api_throttle = get_variable(env_data, "API_THROTTLE", 10, "int")
api_timeout = get_variable(env_data, "API_TIMEOUT", 90, "int")
bd_enabled = get_variable(env_data, "BD_ENABLED", "False", "bool")
bd_password = get_variable(env_data, "BD_PASSWORD", None)
bd_port = get_variable(env_data, "BD_PORT", 22225, "int")
bd_username = get_variable(env_data, "BD_USERNAME", None)
debug_code = True
frequency_penalty = get_variable(env_data, "FREQUENCY_PENALTY", 0.0, "float")
max_characters = get_variable(env_data, "MAX_CHARACTERS", 1000, "int")
max_conversation = get_variable(env_data, "MAX_CONVERSATION", 5, "int")
max_tokens = get_variable(env_data, "MAX_TOKENS", 800, "int")
presence_penalty = get_variable(env_data, "PRESENCE_PENALTY", 0.0, "float")
temperature = get_variable(env_data, "TEMPERATURE", 0.8, "float")
top_p = get_variable(env_data, "TOP_P", 0.0, "float")
search_engine_mode = get_variable(env_data, "SEARCH_ENGINE_MODE", "GOOGLE")
serp_api_key = get_variable(env_data, "SERP_API", None)
google_api_key = get_variable(env_data, "GOOGLE_API_KEY", None)
google_search_id = get_variable(env_data, "CUSTOM_SEARCH_ENGINE_ID", None)
@log_all_functions(logger, log_vars_callback=lambda: locals())
def alternate_api(number):
global api_count
global model
global api_type
global api_url
global api_key
if api_function == "ALTERNATE":
api_count += 1
if number % 2 == 0:
api_url = get_variable(env_data, "AZURE_URL")
api_key = get_variable(env_data, "AZURE_API_KEY")
model = get_variable(env_data, "AZURE_MODEL_NAME")
api_type = "AZURE"
else:
api_url = get_variable(env_data, "OPENAI_URL")
api_key = get_variable(env_data, "OPENAI_API_KEY")
model = get_variable(env_data, "OPENAI_MODEL_NAME")
api_type = "OPENAI"
elif api_function == "AZURE":
api_url = get_variable(env_data, "AZURE_URL")
api_key = get_variable(env_data, "AZURE_API_KEY")
model = get_variable(env_data, "AZURE_MODEL_NAME")
api_type = "AZURE"
elif api_function == "OPENAI":
api_url = get_variable(env_data, "OPENAI_URL")
api_key = get_variable(env_data, "OPENAI_API_KEY")
model = get_variable(env_data, "OPENAI_MODEL_NAME")
api_type = "OPENAI"
else:
raise ValueError("Invalid API_FUNCTION value. Supported values are 'AZURE', 'OPENAI', or 'ALTERNATE'.")
# Typing effect function
# Create JSON message function
@log_all_functions(logger, log_vars_callback=lambda: locals())
def create_json_message(
reasoning_80_words="",
command_string="",
command_argument="",
current_task="",
self_prompt_action="",
system_directive=""
):
json_message = {
"reasoning_80_words": reasoning_80_words,
"cmd_str": command_string,
"cmd_arg": command_argument,
"current_task": current_task,
"self_prompt_action": self_prompt_action,
"sys_directive": system_directive,
}
return json.dumps(json_message)
# Get random user agent function
def get_random_user_agent():
ua = UserAgent()
browsers = ["Firefox", "Chrome", "Safari", "Opera", "Internet Explorer"]
operating_systems = ["Windows", "Macintosh", "Linux", "Android", "iOS"]
browser = random.choice(browsers)
operating_system = random.choice(operating_systems)
try:
user_agent = ua.data_randomize(f"{browser} {ua.random}, {operating_system}") # type: ignore
except:
user_agent = ua.random
return user_agent
def get_random_text_and_color(text_color_dict):
key = random.choice(list(text_color_dict.keys()))
return key, text_color_dict[key]
# endregion
# region ### TEXT PARSER ###
@log_all_functions(logger, log_vars_callback=lambda: locals())
def extract_text(html_content):
soup = BeautifulSoup(html_content, "html.parser")
allowed_tags = ["p", "h1", "h2", "h3", "h4", "h5", "h6", "a", "span", "ul", "li"]
extracted_text = []
for tag in allowed_tags:
elements = soup.find_all(tag)
for element in elements:
extracted_text.append(element.get_text())
cleaned_text = re.sub(r'\n|["\']', "", " ".join(extracted_text))
# Remove spaces greater than 2
cleaned_text = re.sub(r" {2,}", " ", cleaned_text)
return cleaned_text
# endregion
# region ### API QUERY ###
text_color_dict = {
"Reticulating splines..................": "light_blue",
"I am Error............................": "light_blue",
"Preparing to loop like autoGPT........": "light_blue",
"Wasting tokens to make you broke......": "yellow",
"Prompting LordGPT to hallucinate......": "yellow",
"Would you kindly?.....................": "yellow",
"Do a barrel roll!.....................": "green",
"Finish him!...........................": "green",
"Hadouken!.............................": "green",
}
@log_all_functions(logger, log_vars_callback=lambda: locals())
def query_bot(messages, retries=api_retry):
random_text, random_color = get_random_text_and_color(text_color_dict)
time.sleep(api_throttle) # type: ignore
alternate_api(api_count)
with yaspin(text=random_text, color=random_color) as spinner:
for attempt in range(retries): # type: ignore
try:
def create_api_json(messages):
# messages = json.dumps(messages)
json_payload = json.dumps(
{
"model": model,
"messages": messages,
"max_tokens": max_tokens,
"temperature": temperature,
"top_p": top_p,
"frequency_penalty": presence_penalty,
"presence_penalty": presence_penalty
}
)
headers = {
"api-key": api_key,
"Content-Type": "application/json",
"Authorization": f"Bearer {api_key}",
}
return json_payload, headers
json_payload, headers = create_api_json(messages)
# BD PROXY REQUEST
if bd_enabled:
try:
json_utf8 = json_payload.encode("utf-8")
session_id = random.random()
super_proxy_url = "http://%s-session-%s:%[email protected]:%d" % (
bd_username,
session_id,
bd_password,
bd_port,
)
proxy_handler = urllib.request.ProxyHandler(
{
"http": super_proxy_url,
"https": super_proxy_url,
}
)
ssl._create_default_https_context = ssl._create_unverified_context
opener = urllib.request.build_opener(proxy_handler)
req = urllib.request.Request(api_url, data=json_utf8, headers=headers)
# BRIGHT DATA REQUEST
request = opener.open(req, timeout=api_timeout)
uresponse = request.read()
utfresponse = uresponse.decode("utf-8")
botresponse = json.loads(utfresponse)
response_json = botresponse
except Exception as e:
if attempt < retries - 1: # type: ignore
typing_print(f"Error occurred: {str(e)}...Retrying...")
time.sleep(2**attempt)
else:
# STANDARD API REQUEST
if not bd_enabled:
try:
botresponse = requests.request(
"POST",
api_url,
headers=headers,
data=json_payload,
timeout=api_timeout,
) # type: ignore
response_json = botresponse.json()
except ReadTimeout as e:
if attempt < retries - 1: # type: ignore
typing_print(f"ReadTimeout Error occurred: {str(e)}...Retrying...")
time.sleep(2**attempt)
continue
else:
return (
"Error: API Timeout Error",
" ",
" ",
"Starting with the first uncompleted task in the task list",
"I will pickup where I left off and continue with the first uncompleted task",
"Resend your last response"
)
except Exception as e:
typing_print(f"Error occurred: {str(e)}")
return (
"Unknown API Error: Resend response in the correct json format",
" ",
" ",
"Starting with the first uncompleted task in the task list",
"I will respond using the required json format and continue with the first uncompleted task",
"Resend your last response"
)
# Handling error response
if "error" in response_json:
error_message = response_json["error"]["message"]
typing_print(f"Error: {error_message}")
return (
f"API error {error_message}",
" ",
" ",
"Starting with the first uncompleted task in the task list",
"I will respond using the required json format and continue with the first uncompleted task",
"Resend your last response"
)
responseparsed = response_json["choices"][0]["message"]["content"]
try:
responseformatted = json.loads(responseparsed)
except:
alternate_api(api_count)
print("LordGPT Responsed with invalid json, but we will fix on our end.")
fixed_response = create_json_message(responseparsed)
responseformatted = json.loads(fixed_response)
if responseformatted is not None:
if "current_task" in responseformatted:
reasoning = responseformatted["reasoning_80_words"]
command_string = responseformatted["cmd_str"]
command_argument = responseformatted["cmd_arg"]
current_task = responseformatted["current_task"]
self_prompt_action = responseformatted["self_prompt_action"]
system_directive = responseformatted.get("sys_directive", "")
return (
reasoning,
command_string,
command_argument,
current_task,
self_prompt_action,
system_directive
)
else:
return (
"Invalid JSON Format, please use the correct format.",
" ",
" ",
"Starting with the first uncompleted task in the task list",
"I will always respond using the required json format and continue with the first uncompleted task",
"Resend your last response"
)
except Exception as e:
if attempt < retries - 1: # type: ignore
typing_print(f"API Timeout, increase your timeout: {str(e)}...Retrying...")
time.sleep(2**attempt)
else:
typing_print("API Retries reached, insert another coin and try again...")
exit
# endregion
# region ### COMMANDS ###
# region ### Notification ###
def notify_command(reasoning, command_string, command_argument, current_task, self_prompt_action, system_directive=""):
system_directive = sys_directive_handler("notify_command", "sucess")
return create_json_message(
reasoning,
command_string,
command_argument,
current_task,
self_prompt_action,
system_directive
)
#endregion
# region ### GENERATE PDF ###
@log_all_functions(logger, log_vars_callback=lambda: locals())
def convert_html_template_to_pdf(reasoning, command_string, command_argument, current_task, self_prompt_action, system_directive=""):
try:
# Split the command_argument based on the pipe symbol
filename, html_file = command_argument.split("|")
filename = filename.strip()
html_file = html_file.strip()
# Concatenate the working_folder path with the filenames
html_file_path = os.path.join(working_folder, html_file)
output_path = os.path.join(working_folder, filename)
# Check if the provided html_file is an HTML file
if not html_file.lower().endswith(".html"):
response = "Error: Invalid Format. command_argument must be [FILENAME.pdf]|[HTML-TEMPLATE.html] "
system_directive = sys_directive_handler("convert_html_template_to_pdf", "failure")
else:
# Set up PDFKit configuration (replace the path below with the path to your installed wkhtmltopdf)
config = pdfkit.configuration(wkhtmltopdf="/usr/bin/wkhtmltopdf")
# Read the content of the HTML file and pass it to pdfkit
with open(html_file_path, "r") as f:
html_content = f.read()
# Convert the HTML content to a PDF file using PDFKit
pdfkit.from_string(html_content, output_path, configuration=config)
response = f"PDF Created successfully: {filename}"
system_directive = sys_directive_handler("convert_html_template_to_pdf", "success")
except Exception as e:
response = f"Error converting html to PDF: {str(e)}"
system_directive = sys_directive_handler("convert_html_template_to_pdf", "failure")
return create_json_message(
response,
command_string,
command_argument,
current_task,
self_prompt_action,
system_directive
)
# endregion
# region ### SHELL COMMANDS ###
@log_all_functions(logger, log_vars_callback=lambda: locals())
def run_shell_command(reasoning, command_string, command_argument, current_task, self_prompt_action, system_directive=""):
process = subprocess.Popen(
command_argument,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
shell=True,
cwd=working_folder, # Set the working directory here
)
output = b""
error = b""
try:
# Set a timeout value (in seconds) for the command execution
typing_print("Attempting Shell Command, Timeout is 350 seconds...")
timeout_value = 350
output, error = process.communicate(timeout=timeout_value)
except subprocess.TimeoutExpired:
process.kill()
set_global_success(False)
reasoning = "Shell command execution timed out. "
system_directive = sys_directive_handler("run_shell_command", "failure")
return_code = process.returncode
shell_response = ""
output_decoded = output.decode("utf-8", errors="replace")
error_decoded = error.decode("utf-8", errors="replace")
if "mkdir" in command_argument:
if return_code == 0:
set_global_success(True)
shell_response = "Folder created successfully. " + command_argument
elif return_code == 1 and "Folder already exists navigate to folder. " in error_decoded:
set_global_success(True)
shell_response = "Folder already exists. Try switching to folder. " + command_argument
else:
shell_response = f"Error creating folder, research the error: {error_decoded.strip()}"
elif "touch" in command_argument:
if return_code == 0:
set_global_success(True)
shell_response = "File created and saved successfully. " + command_argument
else:
set_global_success(False)
shell_response = f"Error creating file, Research the error: {error_decoded.strip()}"
else:
if return_code == 0:
set_global_success(True)
# Add slicing to limit output length
shell_response = "Shell Command Output: " + f"{output_decoded.strip()}"[:max_characters]
else:
set_global_success(False)
# Add slicing to limit error length
shell_response = f"Shell Command failed, research the error: {error_decoded.strip()}"[:max_characters]
shell_cleaned = json.dumps(shell_response)
shell_response = clean_data(shell_cleaned)
typing_print("Shell Command Output: " + shell_response)
if success == True:
system_directive = sys_directive_handler("run_shell_command", "success")
else:
system_directive = sys_directive_handler("run_shell_command", "failure")
return create_json_message(
reasoning,
command_string,
shell_response,
current_task,
self_prompt_action,
system_directive
)
# endregion
# region ### SAVE RESEARCH ###
@log_all_functions(logger, log_vars_callback=lambda: locals())
def save_research(reasoning, command_string, command_argument, current_task, self_prompt_action, system_directive=""):
# Match the command_argument with the provided regex pattern
match = re.match(r"([^|]+)\|(```[\s\S]*?```)", command_argument)
# Check if triple backticks are not detected in the second position
if not match:
reasoning = "Error: Invalid format: ([TITLE]|[CONTENT]) The content is required to be formatted as a multiline string enclosed within triple backticks (```)."
system_directive = sys_directive_handler("save_research", "failure")
return create_json_message(
reasoning,
command_string,
command_argument,
current_task,
self_prompt_action,
system_directive
)
# Extract the title and content from the matched groups
title = match.group(1).strip()
content = match.group(2).strip()
# Remove the triple backticks, newline characters, and extra spaces from the content
content = content.replace("```", "")
# Get the current datetime
current_time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
# Create the research entry with the datetime, title, and content
research_entry = f"DateTime: {current_time}\nTitle: {title}\nContent: {content}\n\n"
# Save the research to a text file
research_file_path = os.path.join(working_folder, "research.txt")
try:
with open(research_file_path, "a", encoding="utf-8") as f: # Add encoding="utf-8"
f.write(research_entry)
system_directive = sys_directive_handler("save_research", "success")
except FileNotFoundError:
system_directive = sys_directive_handler("save_research", "failure")
return create_json_message(
reasoning,
command_string,
command_argument,
current_task,
self_prompt_action,
system_directive
)
# endregion
# region ### FETCH RESEARCH ###
@log_all_functions(logger, log_vars_callback=lambda: locals())
def fetch_research(reasoning, command_string, command_argument, current_task, self_prompt_action, system_directive=""):
# Fetch the research.txt file from the working_folder
research_file_path = os.path.join(working_folder, "research.txt")
try:
with open(research_file_path, "r", encoding="utf-8") as f:
formatted_research = f.read()
command_argument = clean_data(formatted_research)
system_directive = sys_directive_handler("save_research", "success")
except FileNotFoundError:
reasoning = "Failed to fetch research data, the file doesn't exist. You must save research before you can fetch it."
system_directive = sys_directive_handler("fetch_research", "failure")
return create_json_message(
reasoning,
command_string,
command_argument,
current_task,
self_prompt_action,
system_directive
)
# endregion
# region ### CREATE TASK LIST ###
def task_count(arg):
global task_counter
task_counter += 1
if arg == "create_task_list":
task_counter = 0
@log_all_functions(logger, log_vars_callback=lambda: locals())
def create_task_list(reasoning, command_string, command_argument, current_task, self_prompt_action, system_directive=""):
task_count("reset")
try:
# Check if the command_argument contains triple backticks
match = re.search(r"```[\s\S]{100,}?```", command_argument)
if match:
message_handler(None, command_argument, "task")
task_response = "Task List Updated Successfully!"
system_directive = sys_directive_handler("create_task_list", "success")
else:
task_response = "Error: Task list not formatted as a multistring using triple backticks(```)."
system_directive = sys_directive_handler("create_task_list", "failure")
except Exception as e:
task_response = "Error: Task list not formatted as a multistring using triple backticks(```)."
system_directive = sys_directive_handler("create_task_list", "failure")
return create_json_message(
task_response,
command_string,
command_argument,
current_task,
self_prompt_action,
system_directive
)
# endregion
# region ### FILE OPERATION ###
@log_all_functions(logger, log_vars_callback=lambda: locals())
def file_operation(reasoning, command_string, command_argument, current_task, self_prompt_action, system_directive):
try:
match = re.match(r"([^|]+)\|?(?:(```[\s\S]*?```)?\|)?(.+)", command_argument)
if not match:
sys_directive_handler("file_operation", "failure")
re
return create_json_message(
"Error: Invalid format: The format must be ([FILENAME.ext]|```[CONTENT]```|[FILEOPERATION]) The content is required to be formatted as a multiline string enclosed within triple backticks (```).",
command_string,
command_argument,
current_task,
self_prompt_action,
system_directive
)
file_name, content, operation = match.groups()
if operation != "read" and (not content or not content.startswith("```") or not content.endswith("```")):
sys_directive_handler("file_operation", "failure")
return create_json_message(
"Error: The content is required to be formatted as a multiline string enclosed within triple backticks (```).",
command_string,
command_argument,
current_task,
self_prompt_action,
system_directive
)
content = content.strip("```") if content else None
file_path = os.path.join(working_folder, file_name)
operation_result = ""
try:
if operation == "write":
with open(file_path, "w", encoding='utf-8', errors='replace') as file:
file.write(content)
operation_result = "File Written Successfully!"
elif operation == "read":
with open(file_path, "r", encoding='utf-8', errors='replace') as file: