-
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Companion
executable file
·2161 lines (1779 loc) · 80.1 KB
/
Companion
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
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Companion
# 2024 Copyright © Robert APM Darin
# All rights reserved unconditionally.
# ***** IMPORTANT:
# This program uses ADMINISTRATOR priviledges.
# Forum and thread support is a strange approach. Threads are treated like channels,
# with a few extra bits. Webhooks, slowdown mode, edits, even the way message are sent
# into the thread is effected. Activitieshave to be tested and is it is a thread, most
# of the time, you have to pull the parent channel. Webhooks and slowdown mode, in
# particular, do NOT have separate functionalities of a channel, even though discord
# treats them like a channel.
### *** At some point, I'm going to really have to rewrite this. The forum/thread detection
### code is a stinking hot mess and scattered everywhere.
# TODO list:
# Figure out how to handle channel config setting across diferent servers.
# Listed in order of when the service was added.
# added openai
# added ollama
# added together.ai
# added cohere
# --> Not in a specific order, add support for the following engines:
# anthropic
# DeepInfra https://deepinfra.com/pricing
# google.ai (genini)
# huggingface
# perplexity.ai
# fireworks.ai
# OctoML AI
# Vertex AI
# AI21labs
# Deep Infra
# Azure
# Anyscale
# Replicate
# octo.ai
# openrouter.ai
# Special USER commands:
# %http Read URLs, YouTube transcripts, and PDFs
# %yttags Get YouTube video tage, if there are any.
# %Forget
# Developer/Admin only:
# %PurgeRequests
# %CheckBot
# Needed functionality
# Purge memory that are older then X days automatically
# Wanted features:
# Imposter detection - completed
# Auto slow mode - completed
# Anti raid/nuke
# Ticket management
# Anti nudity verification for images.
# URL check (abuseIPDB) verifications.
# Disable 3rd party logging.
import warnings
warnings.filterwarnings('ignore')
import logging
logging.basicConfig(level=logging.CRITICAL)
logger=logging.getLogger('transformers')
logger.setLevel(logging.CRITICAL)
logger.handlers=[]
import sys
import os
import io
import copy
import itertools
import datetime
import time
import json
import random
import string
import concurrent.futures
import threading
import urllib.request
import requests
import re
import asyncio
import discord
import profanity_check as pc
import pdfplumber
import ollama
import tiktoken
import openai
import together
import cohere
import youtube_transcript_api
import imagehash
from discord.ext import commands, tasks
from transformers import AutoTokenizer
from googleapiclient.discovery import build
from PIL import Image
from io import BytesIO
# Active version
Version="0.0.0.0.850"
# The running name of the program. Must be global and NEVER changing.
RunningName=sys.argv[0]
# Persona base folder. This is where all personas are stored.
CompanionBase='/home/Companion'
CompanionStorage=f'{CompanionBase}/Personas'
MemoryStorage=f'{CompanionBase}/Servers/Memory'
LoggingStorage=f'{CompanionBase}/Servers/Logs'
ConfigStorage=f'{CompanionBase}/Servers/Config'
# For anagram solver
AnagramWordList="/home/Companion/AnagramSolver.txt"
# This is a list of domains that are scams, frauds, or malitiouc. It is exists, it is read and message that
# have links listed are removed. Requires the persona text file as well for responses.
CompanionScamURLS='/home/Companion/Companion.scam-urls'
CompanionAutoFilter='/home/Companion/Companion.autofilter'
# Global lock for managing sequential access to the AI api and file safety.
ResponseLock=threading.Lock()
ResponseTimeout=60
DeleteLock=threading.Lock()
DeleteTimeout=60
DisectLock=threading.Lock()
DisectTimeout=60
LoggingLock=threading.Lock()
LoggingTimeout=60
BabbleLock=threading.Lock()
BabbleTimeout=300
# Constants For auto slowmode. Needs to be dymanic in the future
SLOW_MODE_DURATION = 3 # Seconds for individual slow mode
SLOW_MODE_COOLDOWN = 307 # 5 minutes/7 secords cooldown for slow mode adjustments
# Dictionary to store the last slow mode change time for each channel
last_slow_mode_change = {}
# For counting active users per chanel
active_users={}
# This is required for the bot to work properly.
intents=discord.Intents.all()
intents.presences=True
intents.messages=True
intents.message_content=True
intents.members=True
intents.guilds=True
# Create a Discord client
client=discord.Client(intents=intents)
### Really need to make these files on disk and not global memory lists, for
### sharding/multi process management.
# List to store pending requests
request_list=[]
# List to stowre timed messages for deletion
delete_list=[]
###
### General file tools
###
# Cheap mkdir
def mkdir(fn):
if not os.path.exists(fn):
os.makedirs(fn,exist_ok=True)
# Helper function to download and load an image from a URL
def LoadImageURL(url):
response=requests.get(url)
img=Image.open(BytesIO(response.content))
return img
# Read file into buffer
def ReadFile(fn,binary=False):
if os.path.exists(fn):
if binary:
cf=open(fn,'rb')
buffer=cf.read()
cf.close()
else:
cf=open(fn,'r')
buffer=cf.read().strip()
cf.close()
else:
buffer=None
return buffer
# Write file to disk
def WriteFile(fn,data):
cf=open(fn,'w')
cf.write(data)
cf.close()
# Pick one line from a file as a response
def ReadFile2List(fname,ForceLower=False):
# Something broke. Keep the responses in character
responses=ReadFile(fname).strip().split('\n')
while '' in responses:
responses.remove('')
if ForceLower==True:
responses=[item.lower() for item in responses]
return responses
# Pick a random response from a filew
# Something broke. Keep the responses in character
def PickRandomResponse(fname):
responses=ReadFile2List(fname)
selected_response=random.choice(responses)
if selected_response.startswith('{[(*') and selected_response.endswith('*)]}'):
buffer=ReadFile(selected_response[4:-4].strip()).strip()
return buffer
return selected_response
###
### Random support functions
###
# Check a string for numbers only.
def NumberOnly(s):
# Replace common look-alikes with their numeric equivalents
look_alike_replacements={
'I': '1', # Uppercase 'i' as '1'
'l': '1', # Lowercase 'L' as '1'
'O': '0', # Uppercase 'O' as '0'
}
# Replace look-alikes in the input string
for look_alike, digit in look_alike_replacements.items():
s=s.replace(look_alike, digit)
s=s.strip().replace(' ','')
# Define valid characters, including look-alikes and numeric equivalents
valid_chars=set("0123456789.,") # Regular digits, comma, and period
look_alike_chars=set("٠١٢٣٤٥٦٧٨٩") # Arabic-Indic digits
full_width_digits=set("0123456789") # Full-width digits
# Combine all valid characters into one set
valid_chars.update(look_alike_chars)
valid_chars.update(full_width_digits)
# Check each character in the string
for char in s:
if char not in valid_chars:
return False
# Basic number validation: ensure the string isn't just commas or periods
if s.replace(",", "").replace(".", "").isdigit():
return True
return False
# Leet list deritives for trying to get someone's age.
lside=['ask','how','is','are','your','you','when','whens','what','whats','wut','wuts','was','tell','ur','u','r']
rside=['over','old','young','under','teen','tween','tweenie','born','date','year','yr','age','birth','birthed','birthdate','birthday','bday','bd','born']
# Building the leet derivitives. This was a royal pain in the ass, but by doing so, if any user trying to
# bypass the edit detection can be persumed to have malicious intent.
def BuildDerivitives(word):
substitutions={
'a': ['@','4'],
'e': ['3'],
'o': ['0'],
'l': ['1', '|', '!', 'i'],
'i': ['1', 'l', '|', '!', 'l'],
's': ['z', '$', '5'],
't': ['7', '+']
}
# Start the list
dList=[ word ]
# Forward in loop
for x in range(len(word)):
xword=list(word)
if xword[x] in substitutions.keys():
cList=substitutions[xword[x]]
for y in range(len(cList)):
xword[x]=cList[y]
nword=''.join(xword)
if nword not in dList:
dList.append(nword)
# Forward reset at beginning
xword=list(word)
for x in range(len(word)):
if xword[x] in substitutions.keys():
cList=substitutions[xword[x]]
for y in range(len(cList)):
xword[x]=cList[y]
nword=''.join(xword)
if nword not in dList:
dList.append(nword)
# Backwards
xword=list(word)
for x in range(len(word)-1,-1,-1):
if xword[x] in substitutions.keys():
cList=substitutions[xword[x]]
for y in range(len(cList)):
xword[x]=cList[y]
nword=''.join(xword)
if nword not in dList:
dList.append(nword)
# return the list of words back to user
return dList
def BuildLeetList(side):
leetlist=[]
for i in range(len(side)):
leet=BuildDerivitives(side[i])
for j in range(len(leet)):
if leet[j] not in leetlist:
leetlist.append(leet[j])
return leetlist
# Strip pucnctuation.
def StripPunctuation(text):
# Define punctuation and high ASCII characters
punctuation=string.punctuation
high_ascii_chars=''.join(chr(i) for i in range(128, 256))
# Create a translation table to map all punctuation and high ASCII characters to spaces
translation_table=str.maketrans({**dict.fromkeys(punctuation, ' '), **dict.fromkeys(high_ascii_chars, ' ')})
# Replace punctuation and high ASCII characters with spaces in the text
cleaned_text=text.translate(translation_table)
return cleaned_text
# Json filter
# Filter end of line and hard spaces
def jsonFilter(s,FilterSpace=True):
d=s.replace("\\n","").replace("\\t","").replace("\\r","")
if FilterSpace==True:
filterText='\t\r\n \u00A0'
else:
filterText='\t\r\n\u00A0'
for c in filterText:
d=d.replace(c,'')
return(d)
# Break input into a word list for steering.
def GetWordList(text):
words=text.lower().split() # Split the string by spaces
return [word for word in words if word] # Filter out empty strings (including spaces)
###
### Direct Companion functions
###
# Read the token file into a token dictionary.
def ReadTokens(gid=None):
tokens={}
if gid==None:
tfile=RunningName+'.tokens'
else:
tfile=f"{ConfigStorage}/{gid}/{gid}.tokens"
if os.path.exists(tfile):
try:
tokens=json.loads(jsonFilter(ReadFile(tfile)))
except Exception as err:
ErrorLog("Error token file is not in JSON format. Please see README.md for new layout")
sys.exit(1)
else:
ErrorLog(f"Missing token file: {tfile}")
sys.exit(1)
if gid==None and 'Discord' not in tokens:
ErrorLog("The MUST be a Discord API reference in the tokens file")
sys.exit(1)
return tokens
# Raw dump. For diagnostics purposes to see the actual return response from the AI model.
def RawLog(text):
if LoggingLock.acquire(timeout=LoggingTimeout):
try:
mkdir(LoggingStorage)
fn=f'{LoggingStorage}/RAWDUMP.log'
fh=open(fn,'w')
fh.write(text)
fh.close()
except:
pass
LoggingLock.release()
# Logging
def WriteLog(gid,uid,channel,text):
if LoggingLock.acquire(timeout=LoggingTimeout):
try:
txt=text.replace('\n','\\n').replace('\r','\\r')
time=(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f'))
s=f'{time} {uid} {channel} {txt}\n'
dn=f'{LoggingStorage}/{gid}'
mkdir(dn)
fn=f'{dn}/{channel}.log'
fh=open(fn,'a+')
fh.write(s)
fh.close()
except Exception as err:
print(f'LOG Broke: {err}')
pass
LoggingLock.release()
# Log errors
def ErrorLog(text):
if LoggingLock.acquire(timeout=LoggingTimeout):
try:
txt=text.replace('\n','\\n').replace('\r','\\r')
time=(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f'))
s=f'{time} {txt}\n'
mkdir(LoggingStorage)
fn=LoggingStorage+'/Errors.log'
fh=open(fn,'a+')
fh.write(s)
fh.close()
# print to console
print(txt)
except:
pass
LoggingLock.release()
# Needed for OpenAI as there are limits with the number of "tokens" that can be processed in a single
# request. HuggingFace=Ollama, Together.AI -> NOT OpenAI.
def MaintainTokenLimit(Tokens,orgmessages,max_tokens=128000,engine='openai',model="gpt-4o",encoding=None,HuggingFace=False):
def count_tokens():
# Calculate current tokens in the message list
if engine=='openai': #not HuggingFace:
current_tokens=sum(len(enc.encode(message["content"])) for message in messages)
elif engine=='cohere':
current_tokens=sum(len(co.tokenize(text=message["content"],model=model,offline=False).tokens) for message in messages)
else:
current_tokens=0
for message in messages:
# current_tokens=len(enc(message["content"], add_special_tokens=False)["input_ids"])
current_tokens=int(len(message["content"])/4)
return current_tokens
if engine=='openai': #not HuggingFace:
if encoding!=None:
enc=tiktoken.get_encoding(encoding)
else:
enc=tiktoken.get_encoding(tiktoken.model.MODEL_TO_ENCODING[model])
elif engine=='cohere':
co=cohere.ClientV2(api_key=Tokens['Cohere'])
# else:
# Gated, needs env HF_HUB_READ_TOKEN
# enc=AutoTokenizer.from_pretrained(encoding)
# Make a separate working copy of the original messages.
messages=orgmessages.copy()
try:
current_tokens=count_tokens()
old_tokens=current_tokens
if max_tokens==0:
return messages
# While tokens exceed the limit, remove elements
while current_tokens > max_tokens:
for i in range(len(messages) - 1):
if i < len(messages) - 1:
if messages[i]['role'].lower()=="user" and messages[i+1]['role'].lower()=="assistant":
# Remove the pair (two items)
messages.pop(i)
messages.pop(i)
break
elif messages[i]['role'].lower()=="user" and messages[i+1]['role'].lower()=="user":
# Remove only one item if two adjacent items are user/user
messages.pop(i)
break
# Recalculate current tokens after removal
current_tokens=count_tokens()
# Check for the situation that we can't reduce the number of tokens.
if old_tokens==current_tokens and current_tokens>max_tokens:
return None
old_tokens=current_tokens
except Exception as err:
ErrorLog(f"MaintainTokens: {sys.exc_info()[-1].tb_lineno}/{err}")
return None
return messages
# Get "steering" prompts, if there are any
# Steering files are a way of providing reinforcement to a pattern or paticular question/response designed
# to maintain the persona. Often times this may be used to enforce platform TOS/AUP.
# While we can dive into the nuances on unbiased AI material, we'll just skip to the finality: NOTHING IS
# UNBIASED. This will NEVER change simply because of how we learn, develop, and grow both as a family and
# societal structure. Bias is AUTOMATIC.
# The steering principles demonstrated here are much like we go through as children. The txt file will have
# the question repeated multiple times, with multiple acceptable responses. This practice is virtually
# identical to how we learn as children.
def GetSteering(bot,input_text):
wordlist=GetWordList(StripPunctuation(input_text))
if wordlist==None or wordlist==[]:
return None
SteerDir=f"{CompanionStorage}/{bot['BotName']}/Steering"
try:
for word in wordlist:
if os.path.isdir(SteerDir+'/'+word):
SteerDir+='/'+word
elif os.path.isfile(SteerDir+'/'+word+'.txt'):
prompts=ReadFile(SteerDir+'/'+word+'.txt').strip().split('\n')
return prompts
except Exception as err:
ErrorLog(f"Steering: {sys.exc_info()[-1].tb_lineno}/{err}")
# No txt file found. No prompts available
return None
# Read channel list and set bot persona
def GetCompanionPersona(gid,channel,nsfw=False,Welcome=False):
# Get the list of channels and the bot name that is allowed in a given channel
cfg=f"{ConfigStorage}/{gid}/{gid}.cfg"
if not os.path.exists(cfg):
print(f'NO configuration: {cfg}')
return None
try:
Config=json.loads(jsonFilter(ReadFile(cfg)))
except Exception as err:
ErrorLog(f"{cfg} damaged: {sys.exc_info()[-1].tb_lineno}/{err}")
return None
if 'Channels' not in Config:
Config['Channels']={}
bot=Config.copy()
# Welcome should really be Default. If more then one bot it listed, comma separated, one one random,
# and vwerify that it has a welcome file.
if Welcome==True:
bot['BotName']=Config['Welcome']
bot['Channel']=None
else:
Channels=Config['Channels']
bot['Channel']=channel
if channel in Channels:
bot['BotName']=Channels[channel]
bot['ResponseAllowed']='Yes'
else:
bot['BotName']=Config['Default']
bot['ResponseAllowed']='No'
# Sort out loading a persona by channel and NSFW possibilities.
# possibilities are that a persona can be:
# 1. global (SFW)
# 2. global, NSFW
# 3. channel, (SFW)
# 4. channel, NSFW
# System Role
# Test channel NSFW
BotSystem=f"{CompanionStorage}/{bot['BotName']}/{bot['BotName']}.{channel}.system.nsfw"
if nsfw and os.path.exists(BotSystem):
bot['System']=BotSystem
else:
# Test channel SFW
BotSystem=f"{CompanionStorage}/{bot['BotName']}/{bot['BotName']}.{channel}.system"
if os.path.exists(BotSystem):
bot['System']=BotSystem
else:
# Test global NSFW
BotSystem=f"{CompanionStorage}/{bot['BotName']}/{bot['BotName']}.system.nsfw"
if nsfw and os.path.exists(BotSystem):
bot['System']=BotSystem
else:
# global SFW
bot['System']=f"{CompanionStorage}/{bot['BotName']}/{bot['BotName']}.system"
# Persona file
# Test channel NSFW
BotPersona=f"{CompanionStorage}/{bot['BotName']}/{bot['BotName']}.{channel}.persona.nsfw"
if nsfw and os.path.exists(BotPersona):
bot['Persona']=BotPersona
else:
# Test channel SFW
BotPersona=f"{CompanionStorage}/{bot['BotName']}/{bot['BotName']}.{channel}.persona"
if os.path.exists(BotPersona):
bot['Persona']=BotPersona
else:
# Test global NSFW
BotPersona=f"{CompanionStorage}/{bot['BotName']}/{bot['BotName']}.persona.nsfw"
if nsfw and os.path.exists(BotPersona):
bot['Persona']=BotPersona
else:
# global SFW
bot['Persona']=f"{CompanionStorage}/{bot['BotName']}/{bot['BotName']}.persona"
bot['Welcome']=f"{CompanionStorage}/{bot['BotName']}/{bot['BotName']}.welcome"
bot['Vulgarity']=f"{CompanionStorage}/{bot['BotName']}/{bot['BotName']}.vulgarity"
bot['ScamURLS']=f"{CompanionStorage}/{bot['BotName']}/{bot['BotName']}.scamurls"
bot['AutoFilter']=f"{CompanionStorage}/{bot['BotName']}/{bot['BotName']}.autofilter"
bot['AgeExploit']=f"{CompanionStorage}/{bot['BotName']}/{bot['BotName']}.ageexploit"
bot['TooMuchInformation']=f"{CompanionStorage}/{bot['BotName']}/{bot['BotName']}.tmi"
bot['Broken']=f"{CompanionStorage}/{bot['BotName']}/{bot['BotName']}.broke"
bot['URLBroken']=f"{CompanionStorage}/{bot['BotName']}/{bot['BotName']}.urlbroke"
bot['YTtags']=f"{CompanionStorage}/{bot['BotName']}/{bot['BotName']}.yttags"
bot['noYTtags']=f"{CompanionStorage}/{bot['BotName']}/{bot['BotName']}.noyttags"
# Load bot config file. Channel CFg always has priority.
settings={}
try:
bcfg=f"{ConfigStorage}/{gid}/{bot['BotName']}.{channel}.cfg"
if os.path.exists(bcfg):
settings=json.loads(jsonFilter(ReadFile(bcfg)))
else:
bcfg=f"{ConfigStorage}/{gid}/{bot['BotName']}.cfg"
if os.path.exists(bcfg):
settings=json.loads(jsonFilter(ReadFile(bcfg)))
except Exception as err:
ErrorLog(f"{bcfg} damaged: {sys.exc_info()[-1].tb_lineno}/{err}")
# Merge the persona settings into the controlling dictionary
if settings!={}:
bot|=settings
# Run through some sanity checks.
if 'AutoLogging' not in bot:
bot['AutoLogging']='yes'
if 'AutoModeration' not in bot:
bot['AutoModeration']='yes'
if 'AllowBot' not in bot:
bot['AllowBot']='no'
if 'Engine' not in bot:
bot['Engine']="openai"
if 'Model' not in bot:
bot['Model']="gpt-4o-mini"
if 'FreqPenality' not in bot:
bot['FreqPenality']=0.67
else:
if type(bot['FreqPenality'])!=float:
bot['FreqPenality']=float(bot['FreqPenality'])
if 'Temperature' not in bot:
bot['Temperature']=0.37
else:
if type(bot['Temperature'])!=float:
bot['Temperature']=float(bot['Temperature'])
if 'AllowVulgarity' not in bot:
bot['AllowVulgarity']='No'
if 'DeveloperUID' not in bot:
bot['DeveloperUID']=0
else:
if type(bot['DeveloperUID'])!=int:
bot['DeveloperUID']=int(bot['DeveloperUID'])
if 'MaxMemory' not in bot:
bot['MaxMemory']=100
else:
if type(bot['MaxMemory'])!=int:
bot['MaxMemory']=int(bot['MaxMemory'])
# return the current bot
return bot
# This function handle the actual responses.
def GetBabble(message,text):
try:
# The "uid" and "channel" are used to load the persona and store the memory to
# disk. At this point, we don't have any global variables.
# EXTEND to: GuildID/ChannelID:NSFW/MessageID/UID/input
dataline=text.split('/')
gid=message.guild.id
uid=dataline[0]
channel,cnsfw=dataline[1].split(':')
nsfw=(cnsfw=='T')
input_text=str(dataline[2:]).replace("'","\'").replace('"',"'")
# Don't remember this request. does NOT bypass logging
ForgetThisMessage=False
if text.strip().startswith('%#>'):
ForgetThisMessage=True
input_text=input_text[3:]
# Load the persona and memory files
# NSFW not allowed in threads directly, so find parent channel
# Question: Do we take info of NSFW state or force verify? Currebt is face value
bot=None
if isinstance(message.channel,discord.Thread):
pchannel=str(message.channel.parent)
bot=GetCompanionPersona(gid,pchannel,nsfw) # message.channel.parent.nsfw
else:
bot=GetCompanionPersona(gid,channel,nsfw)
persona=[]
mList=[]
# Read system role from system tag file
# { "role": "system", "content": ""}
if os.path.exists(bot['System']):
buff=ReadFile(bot['System']).replace('\n','\\n').replace("'","\'").replace('"',"'").strip()
sysList=[ '{'+ f'"role": "system", "content": "{buff}"' +'}' ]
else:
sysList=[]
# Read the persona file
if os.path.exists(bot['Persona']):
pfList=ReadFile(bot['Persona']).strip().split('\n')
else:
pfList=[]
pList=sysList+pfList
# Load memory files, if one exists.
dn=f"{MemoryStorage}/{gid}/{bot['BotName']}"
mkdir(dn)
fn=f"{dn}/{bot['BotName']}.{uid}.{channel}.memory"
if os.path.exists(fn):
mList=ReadFile(fn).strip().split('\n')
pList+=mList
# Build the complete persona list
for s in pList:
try:
persona.append(json.loads(s))
except:
ErrorLog(f"Broke: {sys.exc_info()[-1].tb_lineno}/{s}")
# Look for a "steering" file. Should be last to ensurew its not chopped of.
sList=GetSteering(bot,input_text)
if sList!=None:
pList+=sList
# Add user input
memU={ "role": "user", "content": input_text }
persona.append(memU)
# Process API for the request
el=list(bot['Engine'].split(',')) # Engine list
ec=len(el) # Engine list length
tl=list(bot['MaxTokens'].split(',')) # Max Tokens list
mt=len(tl) # Max Tokens list length
# Encoding alwayys takes priority over modem
if 'Encoding' in bot:
ml=list(bot['Encoding'].split(',')) # Model list
mc=len(ml) # Model list length
else:
ml=list(bot['Model'].split(',')) # Model list
mc=len(ml) # Model list length
# The number of models MUST equal the number of engines. 1 model per engine
if ec!=mc!=mt:
ErrorLog(f"Broke GB ((models/Encoding)!=engines!=MaxTokens): {sys.exc_info()[-1].tb_lineno}/{err}")
return PickRandomResponse(bot['Broken'])
# Run through the engins/models until we have a response.
response=None
ecounter=0
while response==None and ecounter<ec:
cbot=copy.deepcopy(bot) # Make a copy
cbot['Engine']=el[ecounter]
cbot['MaxTokens']=int(tl[ecounter])
# Encoding or Model
if 'Encoding' in cbot:
cbot['Encoding']=ml[ecounter]
else:
cbot['Model']=ml[ecounter]
response=GetAIResponse(gid,persona,cbot)
if response==None:
ecounter+=1
else:
break
# check to see if we got a response
if response==None or response=='':
return PickRandomResponse(bot['Broken'])
# Save "memory" to disk
memA={ "role": "assistant", "content": response }
mList.append(json.dumps(memU))
mList.append(json.dumps(memA))
# Keep memory at a limited amount. The *2 is because we are saving user and AI responses.
if bot['MaxMemory']>0 and memA['content']!=None and not ForgetThisMessage:
if len(mList)>(bot['MaxMemory']*2):
mList=mList[2:]
fh=open(fn,'w')
for i in mList:
fh.write(i+'\n')
fh.close()
# Return the AI response
return response
except Exception as err:
ErrorLog(f"Broke GB: {sys.exc_info()[-1].tb_lineno}/{err}")
return PickRandomResponse(bot['Broken'])
# Handles the persona as a synchronous call. I chose this approach for symplicity and adaptability.
async def HandleOneMessage(request):
global request_list
with concurrent.futures.ThreadPoolExecutor() as pool:
try:
input_text=request['input']
guild=client.get_guild(request['gid'])
channel=await guild.fetch_channel(request['cid'])
message=await channel.fetch_message(request['mid'])
uid=str(message.author.id)
author=str(message.author.mention)
channel=str(message.channel)
# NSFW not allowed in threads, so find parent channel
bot=None
if isinstance(message.channel,discord.Thread):
pchannel=message.channel.parent
bot=GetCompanionPersona(guild.id,str(pchannel),pchannel.nsfw)
nsfw=str(pchannel.nsfw)[0]
# WTAF? Really? bots have to join a thread...
if not message.channel.me:
await message.channel.join()
else:
bot=GetCompanionPersona(guild.id,str(message.channel),message.channel.nsfw)
nsfw=str(message.channel.nsfw)[0]
if bot==None:
return
# Convert boolean to str as a passing argument.
print('U',guild.id,nsfw,uid,message.author,message.channel,len(message.content))
# Handle any vulgarity
if bot['AutoModeration'].lower()!='no' \
and os.path.exists(bot['Vulgarity']) \
and bot['AllowVulgarity'].lower()=='no' \
and not nsfw=='T':
if bool(pc.predict([ input_text ]))==True:
await ModeratorNotify(bot,message.guild,f"{message.author.name}/{message.author.id} chastized for vulgarity in {message.channel.name}")
await send_response(bot,message,PickRandomResponse(bot['Vulgarity']),delete=57)
try: # delete the offending message
await message.delete()
except:
pass
return
else:
istr=f"{uid}/{channel}:{nsfw}/{input_text}"
response=await client.loop.run_in_executor(pool, GetBabble,message, istr)
else:
istr=f"{uid}/{channel}:{nsfw}/{input_text}"
response=await client.loop.run_in_executor(pool, GetBabble,message, istr)
print('B',guild.id,client.user.id,bot['BotName'],message.channel,len(response))
# Check to see if we actually got a response
if response!=None and response.lower().strip()!="none":
# Handle webhooks for response
await send_response(bot,message,response)
else:
# Communication with AI failed. Put message back in queue
if ResponseLock.acquire(timeout=ResponseTimeout):
msg={}
msg['input']=input_text
msg['gid']=guild.id
msg['cid']=message.channel.id
msg['mid']=message.id
request_list.append(msg)
ResponseLock.release()
else:
ErrorLog("Lock failed Reput Message")
except Exception as err:
ErrorLog(f"Broken HandleOneMessage: {sys.exc_info()[-1].tb_lineno}/{err}")
###
### AI handlers (Optimized)
###
# General AI Call Handler
def GetAIResponse(gid,persona,bot):
print(gid,bot.get('Model'), bot.get('Encoding'))
provider=bot.get('Engine').lower()
try:
# Default connection timeout
tout=bot.get('Timeout', 60)
mt=bot.get('MaxTokens', 16000 if provider=='OpenAI' else 4096)
if provider=='ollama' and mt==0:
mt=2048
model=bot.get('Model')
encoding=bot.get('Encoding')
seed=bot.get('Seed', 0)
# Provider-specific handling
Tokens=ReadTokens(gid)
# Adjust persona based on token limit
WorkingPersona=MaintainTokenLimit(Tokens, persona, max_tokens=mt, engine=provider, model=model, encoding=encoding, HuggingFace=(provider != 'openai'))
if WorkingPersona is None:
return PickRandomResponse(bot['TooMuchInformation'])
if provider=='openai':
clientAI=openai.OpenAI(api_key=Tokens['OpenAI'])
completion=clientAI.chat.completions.create(
model=model,
frequency_penalty=bot['FreqPenality'],
temperature=bot['Temperature'],
messages=WorkingPersona,
timeout=tout
)
clientAI.close()
elif provider=='togetherai':
clientAI=together.Together(api_key=Tokens['TogetherAI'], timeout=tout)
completion=clientAI.chat.completions.create(
model=model,
frequency_penalty=bot['FreqPenality'],
temperature=bot['Temperature'],
messages=WorkingPersona,
stream=False
)
elif provider=='cohere':
co=cohere.ClientV2(api_key=Tokens['Cohere'], timeout=tout)
completion=co.chat(
model=model,
frequency_penalty=bot['FreqPenality'],