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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
|
# File 'lib/slack/smart-bot/commands/general/ai/open_ai/open_ai_chat.rb', line 6
def open_ai_chat(message, delete_history, type, model: "", tag: "", description: "", files: [])
message.strip!
get_personal_settings()
user = Thread.current[:user].dup
user_name = user.name
team_id = user.team_id
team_id_user = Thread.current[:team_id_user]
success = true
if !defined?(@chat_gpt_default_model)
if config.key?(:ai) and config[:ai].key?(:open_ai) and config[:ai][:open_ai].key?(:chat_gpt) and
config[:ai][:open_ai][:chat_gpt].key?(:model)
@chat_gpt_default_model = config[:ai][:open_ai][:chat_gpt][:model]
else
@chat_gpt_default_model = ""
end
end
if model != "" and !@open_ai_models.include?(model)
open_ai_models("", just_models: true) if @open_ai_models.empty?
model_selected = @open_ai_models.select { |m| m.include?(model) }
model = model_selected[0] if model_selected.size == 1
end
@active_chat_gpt_sessions[team_id_user] ||= {}
if delete_history
@active_chat_gpt_sessions[team_id_user][Thread.current[:dest]] = ""
session_name = ""
end
if @active_chat_gpt_sessions[team_id_user].key?(Thread.current[:thread_ts]) and Thread.current[:thread_ts] != "" session_name = @active_chat_gpt_sessions[team_id_user][Thread.current[:thread_ts]]
elsif @active_chat_gpt_sessions[team_id_user].key?(Thread.current[:dest])
if type == :temporary
session_name = ""
@active_chat_gpt_sessions[team_id_user][Thread.current[:dest]] = ""
else
session_name = @active_chat_gpt_sessions[team_id_user][Thread.current[:dest]]
end
else
session_name = ""
@active_chat_gpt_sessions[team_id_user][Thread.current[:dest]] = ""
end
if @open_ai.key?(team_id_user) and @open_ai[team_id_user].key?(:chat_gpt) and @open_ai[team_id_user][:chat_gpt].key?(:sessions) and
@open_ai[team_id_user][:chat_gpt][:sessions].key?(session_name) and @open_ai[team_id_user][:chat_gpt][:sessions][session_name].key?(:collaborators)
collaborators_saved = @open_ai[team_id_user][:chat_gpt][:sessions][session_name][:collaborators]
else
collaborators_saved = []
end
if type == :start or type == :continue or type == :clean
session_name = message
@active_chat_gpt_sessions[team_id_user] ||= {}
@active_chat_gpt_sessions[team_id_user][Thread.current[:thread_ts]] = session_name
@active_chat_gpt_sessions[team_id_user][Thread.current[:dest]] = session_name
message = ""
get_openai_sessions(session_name)
@open_ai[team_id_user] ||= {}
@open_ai[team_id_user][:chat_gpt] ||= {}
@open_ai[team_id_user][:chat_gpt][:sessions] ||= {}
if !@open_ai[team_id_user][:chat_gpt][:sessions].key?(session_name) and
(type == :continue or type == :clean)
respond "*ChatGPT*: I'm sorry, but I couldn't find a session named *#{session_name}*."
return
end
if !@open_ai[team_id_user][:chat_gpt][:sessions].key?(session_name)
@open_ai[team_id_user][:chat_gpt][:sessions][session_name] = {
team_creator: team_id,
user_creator: user_name,
started: Time.now.strftime("%Y-%m-%d %H:%M:%S"),
last_activity: Time.now.strftime("%Y-%m-%d %H:%M:%S"),
collaborators: [],
num_prompts: 0,
model: model,
copy_of_session: "",
copy_of_team: "",
copy_of_user: "",
users_copying: [],
temp_copies: 0,
own_temp_copies: 0,
public: false,
shared: [],
description: description,
tag: tag.downcase,
live_content: [],
static_content: [],
authorizations: {},
}
else @open_ai[team_id_user][:chat_gpt][:sessions][session_name][:model] = model if model != ""
num_prompts = @open_ai[team_id_user][:chat_gpt][:sessions][session_name][:num_prompts]
unless type == :clean
collaborators_txt = ""
if @open_ai[team_id_user][:chat_gpt][:sessions][session_name][:collaborators].size > 0
collaborators = @open_ai[team_id_user][:chat_gpt][:sessions][session_name][:collaborators].map do |team_user|
team_user.split("_")[1..-1].join("_")
end
collaborators_txt = ":busts_in_silhouette: Collaborators: `#{collaborators.join("`, `")}`\n"
@open_ai[team_id_user][:chat_gpt][:sessions][session_name][:collaborators].each do |team_id_user_collaborator|
@chat_gpt_collaborating[team_id_user_collaborator] ||= {}
@chat_gpt_collaborating[team_id_user_collaborator][Thread.current[:thread_ts]] ||= { team_creator: team_id, user_creator: user.name, session_name: session_name }
@listening[team_id_user_collaborator] ||= {}
@listening[team_id_user_collaborator][Thread.current[:thread_ts]] = Time.now
end
end
if num_prompts > 0
respond "*ChatGPT*: I just loaded *#{session_name}*.\n#{collaborators_txt}There are *#{num_prompts} prompts* in this session.\nThis was the *last prompt* from the session:\n"
else
respond "*ChatGPT*: I just loaded *#{session_name}*.\n#{collaborators_txt}There are *no prompts* in this session."
end
content = @ai_gpt[team_id_user][session_name]
index_last_prompt = content.rindex { |c| c[:role] == "user" and c[:content].size == 1 and c[:content][0][:type] == "text" }
index_last_context = content.rindex { |c| c[:role] == "system" and c[:content].size == 1 and c[:content][0][:type] == "text" }
if index_last_context
last_context = "\n:robot_face: *User>* #{content[index_last_context][:content][0][:text]}\n"
else
last_context = ""
end
if !@open_ai[team_id_user][:chat_gpt][:sessions][session_name][:live_content].nil? and
@open_ai[team_id_user][:chat_gpt][:sessions][session_name][:live_content].size > 0
live_content = "\n:globe_with_meridians: *Live content*:\n\t\t - `#{@open_ai[team_id_user][:chat_gpt][:sessions][session_name][:live_content].join("`\n\t\t - `")}`"
else
live_content = ""
end
if !@open_ai[team_id_user][:chat_gpt][:sessions][session_name][:static_content].nil? and
@open_ai[team_id_user][:chat_gpt][:sessions][session_name][:static_content].size > 0
static_content = "\n:pushpin: *Static content*:\n\t\t - `#{@open_ai[team_id_user][:chat_gpt][:sessions][session_name][:static_content].join("`\n\t\t - `")}`"
if Thread.current[:dest][0] != "D"
@open_ai[team_id_user][:chat_gpt][:sessions][session_name][:static_content].each do |cont|
channel_hist = cont.scan(/\AHistory of <#(\w+)>\Z/im).flatten[0]
if channel_hist != Thread.current[:dest]
respond ":information_source: I'm sorry this session is trying to load the history of <##{channel_hist}>, but you can only load the history of the channel where you are currently talking or in a DM with me."
return
end
end
end
else
static_content = ""
end
if !@open_ai[team_id_user][:chat_gpt][:sessions][session_name][:authorizations].nil? and
@open_ai[team_id_user][:chat_gpt][:sessions][session_name][:authorizations].size > 0
auth = "\n:lock: *Authorizations:*\n"
@open_ai[team_id_user][:chat_gpt][:sessions][session_name][:authorizations].each do |host, |
auth += "\t\t - `#{host}`: `#{.keys.join("`, `")}`\n"
end
else
auth = ""
end
if index_last_prompt.nil?
respond "#{last_context}No prompts found.\n#{live_content}#{static_content}#{auth}" unless delete_history
else
last_prompt = ""
content[index_last_prompt..-1].each do |c|
if c[:role] == "user" and c[:content].size == 1 and c[:content][0][:type] == "text"
if c[:content][0].key?(:clean_text)
if @open_ai[team_id_user][:chat_gpt][:sessions][session_name][:static_content].nil? or
!@open_ai[team_id_user][:chat_gpt][:sessions][session_name][:static_content].include?(c[:content][0][:clean_text])
last_prompt += ":runner: *User>* #{transform_to_slack_markdown(c[:content][0][:clean_text])}\n"
end
else
last_prompt += ":runner: *User>* #{transform_to_slack_markdown(c[:content][0][:text])}\n"
end
elsif c[:role] == "user" and c[:content].size == 1 and c[:content][0][:type] != "text"
last_prompt += ":runner: *User>* Attached file type #{c[:content][0][:type]}\n"
elsif c[:role] == "assistant" and c[:content].size == 1 and c[:content][0][:type] == "text"
last_prompt += ":speech_balloon: *ChatGPT>* #{transform_to_slack_markdown(c[:content][0][:text])}\n"
end
end
respond last_prompt + last_context + live_content + static_content + auth
end
end
end
if Thread.current[:on_thread] and
(Thread.current[:thread_ts] == Thread.current[:ts] or
(@open_ai[team_id_user][:chat_gpt][:sessions].key?(session_name) and
@open_ai[team_id_user][:chat_gpt][:sessions][session_name].key?(:thread_ts) and
@open_ai[team_id_user][:chat_gpt][:sessions][session_name][:thread_ts].include?(Thread.current[:thread_ts])))
react :running, Thread.current[:thread_ts]
@listening[team_id_user] ||= {}
@listening[team_id_user][Thread.current[:thread_ts]] = Time.now
@open_ai[team_id_user][:chat_gpt][:sessions][session_name][:thread_ts] ||= []
@open_ai[team_id_user][:chat_gpt][:sessions][session_name][:thread_ts] << Thread.current[:thread_ts]
@listening[:threads][Thread.current[:thread_ts]] = Thread.current[:dest]
else
@active_chat_gpt_sessions[team_id_user][Thread.current[:dest]] = session_name
end
@open_ai[team_id_user][:chat_gpt][:sessions][session_name][:description] = description if description != ""
@open_ai[team_id_user][:chat_gpt][:sessions][session_name][:tag] = tag.downcase if tag != ""
open_ai_chat_use_model(model, dont_save_stats: true) if model != ""
elsif type == :temporary and
(!@chat_gpt_collaborating.key?(team_id_user) or !@chat_gpt_collaborating[team_id_user].key?(Thread.current[:thread_ts]))
@open_ai[team_id_user] ||= {}
@open_ai[team_id_user][:chat_gpt] ||= {}
@open_ai[team_id_user][:chat_gpt][:sessions] ||= {}
if Thread.current[:on_thread] and
(Thread.current[:thread_ts] == Thread.current[:ts] or
(@open_ai[team_id_user][:chat_gpt][:sessions].key?("") and @open_ai[team_id_user][:chat_gpt][:sessions][""].key?(:thread_ts) and
@open_ai[team_id_user][:chat_gpt][:sessions][""][:thread_ts].include?(Thread.current[:thread_ts])))
@listening[team_id_user] ||= {}
@listening[team_id_user][Thread.current[:thread_ts]] = Time.now
@listening[:threads][Thread.current[:thread_ts]] = Thread.current[:dest]
react :running if Thread.current[:thread_ts] == Thread.current[:ts]
@open_ai[team_id_user][:chat_gpt][:sessions][""] ||= {}
@open_ai[team_id_user][:chat_gpt][:sessions][""][:thread_ts] ||= []
@open_ai[team_id_user][:chat_gpt][:sessions][""][:thread_ts] << Thread.current[:thread_ts]
@active_chat_gpt_sessions[team_id_user] ||= {}
@active_chat_gpt_sessions[team_id_user][Thread.current[:thread_ts]] ||= ""
end
end
if delete_history and type != :clean and @open_ai.key?(team_id_user) and @open_ai[team_id_user].key?(:chat_gpt) and @open_ai[team_id_user][:chat_gpt].key?(:sessions) and
@open_ai[team_id_user][:chat_gpt][:sessions].key?(session_name)
if session_name == "" and type == :temporary
@open_ai[team_id_user][:chat_gpt][:sessions][session_name][:collaborators] = []
@open_ai[team_id_user][:chat_gpt][:sessions][session_name][:num_prompts] = 0
@open_ai[team_id_user][:chat_gpt][:sessions][session_name][:copy_of_session] = ""
@open_ai[team_id_user][:chat_gpt][:sessions][session_name][:copy_of_team] = ""
@open_ai[team_id_user][:chat_gpt][:sessions][session_name][:copy_of_user] = ""
end
@open_ai[team_id_user][:chat_gpt][:sessions][session_name][:live_content] = []
@open_ai[team_id_user][:chat_gpt][:sessions][session_name][:static_content] = []
@open_ai[team_id_user][:chat_gpt][:sessions][session_name][:authorizations] = {}
end
if @chat_gpt_collaborating.key?(team_id_user) and @chat_gpt_collaborating[team_id_user].key?(Thread.current[:thread_ts])
team_creator = @chat_gpt_collaborating[team_id_user][Thread.current[:thread_ts]][:team_creator]
user_creator = @chat_gpt_collaborating[team_id_user][Thread.current[:thread_ts]][:user_creator]
session_name = @chat_gpt_collaborating[team_id_user][Thread.current[:thread_ts]][:session_name]
collaborator = true
else
team_creator = team_id
user_creator = user_name
collaborator = false
end
team_id_user_creator = team_creator + "_" + user_creator
unless type != :temporary and
(!@open_ai.key?(team_id_user_creator) or !@open_ai[team_id_user_creator].key?(:chat_gpt) or !@open_ai[team_id_user_creator][:chat_gpt].key?(:sessions) or
!@open_ai[team_id_user_creator][:chat_gpt][:sessions].key?(session_name) or
(@open_ai[team_id_user_creator][:chat_gpt][:sessions].key?(session_name) and !collaborator and user_creator != user.name))
subtype = ""
if type == :clean
save_stats(:open_ai_chat_clean_session)
elsif message.match?(/\A\s*set\s+context\s+(.+)\s*\Z/i)
subtype = :set_context
save_stats(:open_ai_chat_set_context)
elsif message.match(/\A\s*add\s+live\s+(resource|content|feed|doc)s?\s+(.+)\s*\Z/im)
subtype = :add_live_content
save_stats(:open_ai_chat_add_live_content)
elsif message.match(/\A\s*add\s+(static\s+)?(resource|content|doc)s?\s+(.+)\s*\Z/im)
subtype = :add_static_content
save_stats(:open_ai_chat_add_static_content)
elsif message.match(/\A\s*add\s+history\s+(channel\s+)?<#(\w+)\|.*>\s*\Z/im)
subtype = :add_history_channel
save_stats(:open_ai_chat_add_history_channel)
elsif message.match(/\A\s*delete\s+live\s+(resource|content|feed|doc)s?\s+(.+)\s*\Z/im)
subtype = :delete_live_content
save_stats(:open_ai_chat_delete_live_content)
elsif message.match(/\A\s*delete\s+(static\s+)?(resource|content|doc)s?\s+(.+)\s*\Z/im)
subtype = :delete_static_content
save_stats(:open_ai_chat_delete_static_content)
elsif message.match(/\A\s*delete\s+history\s+(channel\s+)?<#(\w+)\|.*>\s*\Z/im)
subtype = :delete_history_channel
save_stats(:open_ai_chat_delete_history_channel)
elsif message.match(/\A\s*add\s+authorization\s+([^\s]+)\s+([^\s]+)\s+(.+)\s*\Z/im)
subtype = :add_authorization
save_stats(:open_ai_chat_add_authorization)
elsif message.match(/\A\s*delete\s+authorization\s+([^\s]+)\s+([^\s]+)\s*\Z/im)
subtype = :delete_authorization
save_stats(:open_ai_chat_delete_authorization)
else
save_stats(__method__)
end
@open_ai[team_id_user_creator][:chat_gpt][:sessions][session_name][:last_activity] = Time.now.strftime("%Y-%m-%d %H:%M:%S") unless session_name == ""
@ai_open_ai, message_connect = SlackSmartBot::AI::OpenAI.connect(@ai_open_ai, config, @personal_settings, reconnect: delete_history, service: :chat_gpt)
respond message_connect if message_connect
if !@ai_open_ai[team_id_user_creator].nil? and !@ai_open_ai[team_id_user_creator][:chat_gpt][:client].nil?
@ai_gpt[team_id_user_creator] ||= {}
@ai_gpt[team_id_user_creator][session_name] ||= []
if delete_history or !@open_ai.key?(team_id_user_creator) or !@open_ai[team_id_user_creator].key?(:chat_gpt) or
!@open_ai[team_id_user_creator][:chat_gpt].key?(:sessions) or
!@open_ai[team_id_user_creator][:chat_gpt][:sessions].key?(session_name) or
!@open_ai[team_id_user_creator][:chat_gpt][:sessions][session_name].key?(:model) or
!@open_ai[team_id_user_creator][:chat_gpt][:sessions][session_name].key?(:num_prompts)
if delete_history and session_name == "" && @open_ai.key?(team_id_user_creator) && @open_ai[team_id_user_creator].key?(:chat_gpt) &&
@open_ai[team_id_user_creator][:chat_gpt].key?(:sessions) && @open_ai[team_id_user_creator][:chat_gpt][:sessions].key?("") &&
@open_ai[team_id_user_creator][:chat_gpt][:sessions][""].key?(:thread_ts)
@open_ai[team_id_user_creator][:chat_gpt][:sessions][""][:thread_ts].each do |thread_ts|
if thread_ts != Thread.current[:thread_ts] && @listening[:threads].key?(thread_ts)
unreact :running, thread_ts, channel: @listening[:threads][thread_ts]
message_chatgpt = ":information_source: I'm sorry, but I'm no longer listening to this thread since you started a new temporary session."
respond message_chatgpt, @listening[:threads][thread_ts], thread_ts: thread_ts
@listening[team_id_user_creator].delete(thread_ts)
@listening[:threads].delete(thread_ts)
collaborators_saved.each do |team_id_user_collaborator|
if @listening.key?(team_id_user_collaborator)
@listening[team_id_user_collaborator].delete(thread_ts)
end
if @chat_gpt_collaborating.key?(team_id_user_collaborator) && @chat_gpt_collaborating[team_id_user_collaborator].key?(thread_ts)
@chat_gpt_collaborating[team_id_user_collaborator].delete(thread_ts)
end
end
end
end
end
@open_ai[team_id_user_creator] ||= {}
@open_ai[team_id_user_creator][:chat_gpt] ||= {}
@open_ai[team_id_user_creator][:chat_gpt][:sessions] ||= {}
@open_ai[team_id_user_creator][:chat_gpt][:sessions][session_name] ||= {}
@open_ai[team_id_user_creator][:chat_gpt][:sessions][session_name][:model] = model
@open_ai[team_id_user_creator][:chat_gpt][:sessions][session_name][:num_prompts] = 0
end
if message == "" and session_name == "" @ai_gpt[team_id_user_creator][session_name] = []
respond "*ChatGPT*: Let's start a new temporary conversation. Ask me anything."
open_ai_chat_use_model(model, dont_save_stats: true) if model != ""
@open_ai[team_id_user_creator][:chat_gpt][:sessions][session_name][:live_content] = []
@open_ai[team_id_user_creator][:chat_gpt][:sessions][session_name][:static_content] = []
@open_ai[team_id_user_creator][:chat_gpt][:sessions][session_name][:authorizations] = {}
else
treated = false
react :speech_balloon
begin
urls_messages = []
get_openai_sessions(session_name, team_id: team_creator, user_name: user_creator)
if delete_history
prompts = []
if type == :temporary
@ai_gpt[team_id_user_creator][session_name] = []
else
@ai_gpt[team_id_user_creator][session_name].each do |c|
if (c[:role] == "user" and c[:content].size == 1 and c[:content][0][:type] == "text" and c[:content][0].key?(:clean_text) and
@open_ai[team_id_user_creator][:chat_gpt][:sessions][session_name][:static_content].include?(c[:content][0][:clean_text])) or
c[:role] == "system"
prompts << c
end
end
end
@ai_gpt[team_id_user_creator][session_name] = prompts
end
if @open_ai.key?(team_id_user_creator) and @open_ai[team_id_user_creator].key?(:chat_gpt) and @open_ai[team_id_user_creator][:chat_gpt].key?(:sessions) and
@open_ai[team_id_user_creator][:chat_gpt][:sessions].key?(session_name) and @open_ai[team_id_user_creator][:chat_gpt][:sessions][session_name].key?(:model)
if model == ""
model = @open_ai[team_id_user_creator][:chat_gpt][:sessions][session_name][:model].to_s
else
@open_ai[team_id_user_creator][:chat_gpt][:sessions][session_name][:model] = model
end
else
model = ""
end
model = @ai_open_ai[team_id_user_creator].chat_gpt.model if model.empty?
max_num_tokens = 8000 @open_ai_model_info ||= {}
if !@open_ai_model_info.key?(model)
ai_models_conn, message_conn = SlackSmartBot::AI::OpenAI.connect({}, config, {}, service: :models)
models = ai_models_conn[team_id_user_creator].models
unless models.nil? or models.client.nil? or message_conn.to_s != ""
@open_ai_model_info[model] ||= SlackSmartBot::AI::OpenAI.models(models.client, models, model, return_response: true)
end
end
if @open_ai_model_info.key?(model) and @open_ai_model_info[model].key?(:max_input_tokens)
max_num_tokens = @open_ai_model_info[model][:max_input_tokens].to_i
elsif @open_ai_model_info.key?(model) and @open_ai_model_info[model].key?(:max_tokens)
max_num_tokens = @open_ai_model_info[model][:max_tokens].to_i
end
if message.match?(/\A\s*resend\s+prompt\s*\z/i) and !@ai_gpt[team_id_user_creator][session_name].empty?
files_attached = []
system_prompt = @ai_gpt[team_id_user_creator][session_name].pop if @ai_gpt[team_id_user_creator][session_name].last[:role] == "system"
@ai_gpt[team_id_user_creator][session_name].pop if @ai_gpt[team_id_user_creator][session_name].last[:role] == "assistant"
while @ai_gpt[team_id_user_creator][session_name].last[:role] == "user" and
@ai_gpt[team_id_user_creator][session_name].last[:content].first[:type] == "image_url"
files_attached << @ai_gpt[team_id_user_creator][session_name].last[:content].first
@ai_gpt[team_id_user_creator][session_name].pop
end
if @ai_gpt[team_id_user_creator][session_name].last[:role] == "user" and
@ai_gpt[team_id_user_creator][session_name].last[:content].first[:type] == "text"
last_prompt = @ai_gpt[team_id_user_creator][session_name].pop
if last_prompt[:content].first.key?(:clean_text) and
(@open_ai[team_id_user_creator][:chat_gpt][:sessions][session_name][:static_content].nil? or
!@open_ai[team_id_user_creator][:chat_gpt][:sessions][session_name][:static_content].include?(last_prompt[:content].first[:clean_text]))
message = last_prompt[:content].first[:clean_text]
else
message = last_prompt[:content].first[:text]
end
respond ":information_source: Last ChatGPT response was removed from history.\nPrompt resent: `#{message}`"
end
elsif subtype == :set_context
context = message.match(/\A\s*set\s+context\s+(.+)\s*\Z/i)[1]
@ai_gpt[team_id_user_creator][session_name] << { role: "system", content: [{ type: "text", text: context }] }
respond ":information_source: Context set to: `#{context}`"
treated = true
elsif message.match(/\A\s*add\s+live\s+(resource|content|feed|doc)s?\s+(.+)\s*\Z/im)
opts = $2.to_s
opts.gsub!("!http", "http")
urls = opts.scan(/https?:\/\/[^\s\/$.?#].[^\s]*/)
@open_ai[team_id_user_creator][:chat_gpt][:sessions][session_name][:live_content] ||= []
copy_of_user = @open_ai[team_id_user_creator][:chat_gpt][:sessions][session_name][:copy_of_user]
if copy_of_user.to_s != "" and copy_of_user != user_name
team_id_user_orig = @open_ai[team_id_user_creator][:chat_gpt][:sessions][session_name][:copy_of_team] + "_" +
@open_ai[team_id_user_creator][:chat_gpt][:sessions][session_name][:copy_of_user]
copy_of_session = @open_ai[team_id_user_creator][:chat_gpt][:sessions][session_name][:copy_of_session]
auth_user_orig = @open_ai[team_id_user_orig][:chat_gpt][:sessions][copy_of_session][:authorizations]
not_allowed = []
urls.each do |url|
host = URI.parse(url).host
if auth_user_orig.key?(host)
not_allowed << url
end
end
if not_allowed.size > 0
respond ":warning: You are not allowed to add the following URLs because they are part of the authorizations of the user that created the session:\n\t\t - `#{not_allowed.join("`\n\t\t - `")}`"
urls -= not_allowed
end
end
if urls.size > 0
urls.each do |url|
@open_ai[team_id_user_creator][:chat_gpt][:sessions][session_name][:live_content] << url
end
@open_ai[team_id_user_creator][:chat_gpt][:sessions][session_name][:live_content].uniq!
respond ":globe_with_meridians: Live content added:\n\t\t - `#{urls.join("`\n\t\t - `")}`\nEvery time you send a new prompt, it will use the latest version of the resource.\nCall `delete live content URL1 URL99` to remove them."
end
treated = true
elsif message.match(/\A\s*add\s+(static\s+)?(resource|content|doc)s?\s+(.+)\s*\Z/im)
opts = $3.to_s
opts.gsub!("!http", "http")
urls = opts.scan(/https?:\/\/[^\s\/$.?#].[^\s]*/)
@open_ai[team_id_user_creator][:chat_gpt][:sessions][session_name][:static_content] ||= []
copy_of_user = @open_ai[team_id_user_creator][:chat_gpt][:sessions][session_name][:copy_of_user]
if copy_of_user.to_s != "" and copy_of_user != user_name
team_id_user_orig = @open_ai[team_id_user_creator][:chat_gpt][:sessions][session_name][:copy_of_team] + "_" +
@open_ai[team_id_user_creator][:chat_gpt][:sessions][session_name][:copy_of_user]
copy_of_session = @open_ai[team_id_user_creator][:chat_gpt][:sessions][session_name][:copy_of_session]
auth_user_orig = @open_ai[team_id_user_orig][:chat_gpt][:sessions][copy_of_session][:authorizations]
not_allowed = []
urls.each do |url|
host = URI.parse(url).host
if auth_user_orig.key?(host)
not_allowed << url
end
end
if not_allowed.size > 0
respond ":warning: You are not allowed to add the following URLs because they are part of the authorizations of the user that created the session:\n\t\t - `#{not_allowed.join("`\n\t\t - `")}`"
urls -= not_allowed
end
end
if urls.size > 0
authorizations = get_authorizations(session_name, team_id_user_creator)
threads = []
urls.uniq.each do |url|
@open_ai[team_id_user_creator][:chat_gpt][:sessions][session_name][:static_content] << url
threads << Thread.new do
text, url_message = download_http_content(url, authorizations, team_id_user_creator, session_name)
@ai_gpt[team_id_user_creator][session_name] << { role: "user", content: [{ type: "text", text: text, clean_text: url }] }
end
end
threads.each(&:join)
@open_ai[team_id_user_creator][:chat_gpt][:sessions][session_name][:static_content].uniq!
update_openai_sessions(session_name, team_id: team_creator, user_name: user_creator) unless session_name == ""
respond ":pushpin: Static content added:\n\t\t - `#{urls.join("`\n\t\t - `")}`\nCall `delete static content URL1 URL99` to remove them."
end
treated = true
elsif message.match(/\A\s*add\s+history\s+(channel\s+)?<#(\w+)\|.*>\s*\Z/im)
channel_history = $2.to_s
if Thread.current[:dest][0] == "D" or Thread.current[:dest] == channel_history
members_channel_history = get_channel_members(channel_history)
if members_channel_history.include?(config.nick_id) and members_channel_history.include?(config.nick_id_granular)
if Thread.current[:dest][0] == "D"
if !members_channel_history.include?(user.id)
respond ":warning: You are not a member of the channel <##{channel_history}>."
end
end
@history_still_running ||= false
if @history_still_running
respond "Due to Slack API rate limit, when getting history of a channel this command is limited. Waiting for other command to finish."
num_times = 0
while @history_still_running and num_times < 30
num_times += 1
sleep 1
end
if @history_still_running
respond "Sorry, Another command is still running after 30 seconds. Please try again later."
end
end
unless @history_still_running
@history_still_running = true
from = Time.now - 60 * 60 * 24 * 180
to = Time.now
respond "Adding the history of the channel from #{from.strftime("%Y-%m-%d")}. Take in consideration that this could take a while."
hist = []
num_times = 0
while hist.empty? and num_times < 6
client_granular.conversations_history(channel: channel_history, limit: 1000, oldest: from.to_f, latest: to.to_f) do |response|
hist << response.messages
end
hist.flatten!
num_times += 1
if hist.empty?
if num_times == 1
respond "It seems like the history of the channel is empty. It could be the Slack API rate limit. I'll try again for one minute."
end
sleep 10
end
end
messages = {} act_users = {}
act_threads = {}
hist.each do |hist_message|
if Time.at(hist_message.ts.to_f) >= from
year_month = Time.at(hist_message.ts.to_f).strftime("%Y-%m")
messages[year_month] ||= []
if hist_message.key?("thread_ts")
thread_ts_message = hist_message.thread_ts
replies = client_granular.conversations_replies(channel: channel_history, ts: thread_ts_message) sleep 0.5 messages_replies = ["Thread Started about last message:"]
act_threads[hist_message.ts] = replies.messages.size
replies.messages.each_with_index do |msgrepl, i|
act_users[msgrepl.user] ||= 0
act_users[msgrepl.user] += 1
messages_replies << "<@#{msgrepl.user}> (#{Time.at(msgrepl.ts.to_f)}) wrote:> #{msgrepl.text}" if i > 0
end
messages_replies << "Thread ended."
messages[year_month] += messages_replies.reverse end
act_users[hist_message.user] ||= 0
act_users[hist_message.user] += 1
url_to_message = "https://#{client.team.domain}.slack.com/archives/#{channel_history}/#{hist_message.ts}"
messages[year_month] << "<@#{hist_message.user}> (#{Time.at(hist_message.ts.to_f)}) (link to the message: #{url_to_message}) wrote:> #{hist_message.text}"
end
end
@history_still_running = false
messages.each do |year_month, msgs|
messages[year_month] = msgs.reverse end
if messages.empty?
message_history = ":warning: No messages found on the channel <##{channel_history}> from the past 6 months."
message_history += "\n\nIt could be the Slack API rate limit. Please try again in a while."
respond message_history
else
messages = messages.sort_by { |k, v| k }.to_h
num_tokens = 0
prompts_check = @ai_gpt[team_id_user_creator][session_name].deep_copy
prompts_check_text = prompts_check.map { |c| c[:content].map { |cont| cont[:text] }.join("\n") }.join("\n")
enc = Tiktoken.encoding_for_model("gpt-4") text_to_check = nil
num_tokens = 0
removed_months = []
while text_to_check.nil? or num_tokens > (max_num_tokens - 1000)
if num_tokens > (max_num_tokens - 1000)
removed_months << messages.keys.first
messages.shift
end
text_to_check = messages.values.flatten.join("\n") + prompts_check_text
num_tokens = enc.encode(text_to_check.to_s).length
end
if messages.empty?
message_history = ":warning: The history of the channel exceeds the limit of tokens allowed."
if removed_months.size > 0
message_history += "\n\n:The following months were removed because the total number of ChatGPT tokens exceeded the limit of the model:\n\t\t - `#{removed_months.join("`\n\t\t - `")}`"
end
else
history_text = "This is the history of conversations on the Slack channel <##{channel_history}>:\n\n#{messages.values.flatten.join("\n")}"
@open_ai[team_id_user_creator][:chat_gpt][:sessions][session_name][:static_content] ||= []
@open_ai[team_id_user_creator][:chat_gpt][:sessions][session_name][:static_content] << "History of <##{channel_history}>"
@ai_gpt[team_id_user_creator][session_name] << { role: "user", content: [{ type: "text", text: history_text, clean_text: "History of <##{channel_history}>" }] }
@open_ai[team_id_user_creator][:chat_gpt][:sessions][session_name][:static_content].uniq!
update_openai_sessions(session_name, team_id: team_creator, user_name: user_creator) unless session_name == ""
message_history = ":scroll: History of the channel <##{channel_history}> from the past 6 months added to the session.\nCall `delete history <##{channel_history}>` to delete it."
if removed_months.size > 0
message_history += "\n\n:warning: The following months were removed because the total number of tokens exceeded the limit:\n\t\t - `#{removed_months.join("`\n\t\t - `")}`"
end
message_history += "\n\nThe history of that channel will be used as part of the prompts for the next responses."
message_history += "\n\nThe first message added is from #{messages.keys.first}."
message_history += "\n\t\tTotal number of messages added: #{messages.values.flatten.size - act_threads.size}."
message_history += "\n\t\tNumber of threads added: #{act_threads.size}."
message_history += "\n\t\tNumber of messages on threads added: #{act_threads.values.sum}." unless removed_months.size > 0
respond message_history
end
end
end
else
respond ":warning: <@#{config.nick_id}> and <@#{config.nick_id_granular}> need to be members of the channel <##{channel_history}> to be able to add its history. Please add them to the channel and try again."
end
else
respond ":warning: You can only add the history of a Slack channel where you are or on a DM with me."
end
treated = true
elsif message.match(/\A\s*delete\s+live\s+(resource|content|feed|doc)s?\s+(.+)\s*\Z/im)
opts = $2.to_s
opts.gsub!("!http", "http")
urls = opts.scan(/https?:\/\/[^\s\/$.?#].[^\s]*/)
@open_ai[team_id_user_creator][:chat_gpt][:sessions][session_name][:live_content] ||= []
not_found = []
urls.each do |url|
unless @open_ai[team_id_user_creator][:chat_gpt][:sessions][session_name][:live_content].delete(url)
not_found << url
end
end
message_live_content = []
message_live_content << "Live content removed: `#{(urls - not_found).join("`, `")}`." if (urls - not_found).size > 0
message_live_content << "Not found: `#{not_found.join("`, `")}`." if not_found.size > 0
respond ":globe_with_meridians: #{message_live_content.join("\n")}"
treated = true
elsif message.match(/\A\s*delete\s+(static\s+)?(resource|content|doc)s?\s+(.+)\s*\Z/im)
opts = $3.to_s
opts.gsub!("!http", "http")
urls = opts.scan(/https?:\/\/[^\s\/$.?#].[^\s]*/)
@open_ai[team_id_user_creator][:chat_gpt][:sessions][session_name][:static_content] ||= []
not_found = []
urls.each do |url|
unless @open_ai[team_id_user_creator][:chat_gpt][:sessions][session_name][:static_content].delete(url)
not_found << url
end
@ai_gpt[team_id_user_creator][session_name].each do |prompt|
prompt[:content].each do |content|
if content[:type] == "text" and content[:clean_text] == url
@ai_gpt[team_id_user_creator][session_name].delete(prompt)
end
end
end
end
update_openai_sessions(session_name, team_id: team_creator, user_name: user_creator) unless session_name == ""
message_static_content = []
message_static_content << "Static content removed: `#{(urls - not_found).join("`, `")}`." if (urls - not_found).size > 0
message_static_content << "Not found: `#{not_found.join("`, `")}`." if not_found.size > 0
respond ":pushpin: #{message_static_content.join("\n")}"
treated = true
elsif message.match(/\A\s*delete\s+history\s+(channel\s+)?<#(\w+)\|.*>\s*\Z/im)
channel_history = $2.to_s
@open_ai[team_id_user_creator][:chat_gpt][:sessions][session_name][:static_content] ||= []
@ai_gpt[team_id_user_creator][session_name].each do |prompt|
prompt[:content].each do |content|
if content[:type] == "text" and content[:clean_text] == "History of <##{channel_history}>"
@ai_gpt[team_id_user_creator][session_name].delete(prompt)
end
end
end
@open_ai[team_id_user_creator][:chat_gpt][:sessions][session_name][:static_content].delete_if { |url| url == "History of <##{channel_history}>" }
update_openai_sessions(session_name, team_id: team_creator, user_name: user_creator) unless session_name == ""
respond ":scroll: History of the channel <##{channel_history}> removed from the session."
treated = true
elsif message.match(/\A\s*add\s+authorization\s+([^\s]+)\s+([^\s]+)\s+(.+)\s*\Z/im)
host = $1.to_s
= $2.to_s
value = $3.to_s
host.gsub!(/\Ahttps?:\/\//, "")
@open_ai[team_id_user_creator][:chat_gpt][:sessions][session_name][:authorizations] ||= {}
@open_ai[team_id_user_creator][:chat_gpt][:sessions][session_name][:authorizations][host] ||= {}
@open_ai[team_id_user_creator][:chat_gpt][:sessions][session_name][:authorizations][host][] = value
message_sec = [":key: Authorization header added: `#{}` for host `#{host}`."]
message_sec << "Call `delete authorization HOST HEADER` to remove it."
message_sec << "This authorization will be used only for this session."
unless type == :temporary
message_sec << "If you share this session, they will be able to use the authorization but will not be able to see the authorization value."
end
respond message_sec.join("\n")
treated = true
elsif message.match(/\A\s*delete\s+authorization\s+([^\s]+)\s+([^\s]+)\s*\Z/im)
host = $1.to_s
= $2.to_s
host.gsub!(/\Ahttps?:\/\//, "")
if @open_ai[team_id_user_creator][:chat_gpt][:sessions][session_name][:authorizations].nil? or
@open_ai[team_id_user_creator][:chat_gpt][:sessions][session_name][:authorizations][host].nil? or
@open_ai[team_id_user_creator][:chat_gpt][:sessions][session_name][:authorizations][host][].nil?
respond ":key: Authorization header not found: `#{}` for host `#{host}`."
else
@open_ai[team_id_user_creator][:chat_gpt][:sessions][session_name][:authorizations] ||= {}
@open_ai[team_id_user_creator][:chat_gpt][:sessions][session_name][:authorizations][host] ||= {}
@open_ai[team_id_user_creator][:chat_gpt][:sessions][session_name][:authorizations][host].delete()
respond ":key: Authorization header deleted: `#{}` for host `#{host}`."
end
treated = true
end
unless treated
num_folder_docs = 0
if message == ""
res = ""
prompts ||= []
else
restricted = false
files_attached ||= []
if !files.nil?
files.each do |file|
http2 = NiceHttp.new(host: "https://files.slack.com", headers: { "Authorization" => "Bearer #{config.token}" })
res = http2.get(file.url_private_download)
if res[:'content-type'].to_s.include?("image")
require "base64"
image_type = res[:'content-type'].split("/")[1]
data = "data:image/#{image_type};base64,#{Base64.strict_encode64(res.body)}"
files_attached << { type: "image_url", image_url: { url: data } }
else
message = "#{message}\n\n#{res.data}"
end
http2.close
end
end
@open_ai[team_id_user_creator][:chat_gpt][:sessions][session_name][:num_prompts] += 1
urls = message.scan(/!(https?:\/\/[\S]+)/).flatten
if urls.size > 0 and @open_ai[team_id_user_creator][:chat_gpt][:sessions][session_name][:copy_of_user] != user_name
team_id_user_orig = @open_ai[team_id_user_creator][:chat_gpt][:sessions][session_name][:copy_of_team] + "_" +
@open_ai[team_id_user_creator][:chat_gpt][:sessions][session_name][:copy_of_user]
copy_of_session = @open_ai[team_id_user_creator][:chat_gpt][:sessions][session_name][:copy_of_session]
if @open_ai.key?(team_id_user_orig) and @open_ai[team_id_user_orig].key?(:chat_gpt) and
@open_ai[team_id_user_orig][:chat_gpt].key?(:sessions) and @open_ai[team_id_user_orig][:chat_gpt][:sessions].key?(copy_of_session) and
!@open_ai[team_id_user_orig][:chat_gpt][:sessions][copy_of_session].key?(:authorizations)
auth_user_orig = @open_ai[team_id_user_orig][:chat_gpt][:sessions][copy_of_session][:authorizations]
else
auth_user_orig = {}
end
not_allowed = []
urls.each do |url|
host = URI.parse(url).host
if auth_user_orig.key?(host)
not_allowed << url
end
end
if not_allowed.size > 0
respond ":warning: You are not allowed to add the following URLs because they are part of the authorizations of the user that created the session:\n\t\t - `#{not_allowed.join("`\n\t\t - `")}`"
urls -= not_allowed
end
end
if !@open_ai[team_id_user_creator][:chat_gpt][:sessions][session_name][:live_content].nil?
urls += @open_ai[team_id_user_creator][:chat_gpt][:sessions][session_name][:live_content]
end
clean_message = message.dup
authorizations = get_authorizations(session_name, team_id_user_creator)
threads = []
texts = []
urls.uniq.each do |url|
threads << Thread.new do
text, url_message = download_http_content(url, authorizations, team_id_user_creator, session_name)
urls_messages << url_message if url_message != ""
texts << text
end
end
threads.each(&:join)
urls.uniq.each do |url|
message.gsub!("!#{url}", "")
end
texts.each do |text|
message += "\n #{text}\n"
end
if urls.empty?
@ai_gpt[team_id_user_creator][session_name] << { role: "user", content: [{ type: "text", text: message }] }
else
@ai_gpt[team_id_user_creator][session_name] << { role: "user", content: [{ type: "text", text: message, clean_text: clean_message }] }
end
files_attached.each do |file|
@ai_gpt[team_id_user_creator][session_name] << { role: "user", content: [file] }
end
prompts = @ai_gpt[team_id_user_creator][session_name].deep_copy
prompts.each do |prompt|
prompt[:content].each do |content|
content.delete(:clean_text)
end
end
if @open_ai[team_id_user_creator][:chat_gpt][:sessions][session_name][:copy_of_session] == ""
path_to_session_folder = "#{config.path}/openai/#{team_creator}/#{user_creator}/#{session_name}"
term_to_avoid = session_name
else
copy_of_team = @open_ai[team_id_user_creator][:chat_gpt][:sessions][session_name][:copy_of_team]
copy_of_user = @open_ai[team_id_user_creator][:chat_gpt][:sessions][session_name][:copy_of_user]
term_to_avoid = @open_ai[team_id_user_creator][:chat_gpt][:sessions][session_name][:copy_of_session]
path_to_session_folder = "#{config.path}/openai/#{copy_of_team}/#{copy_of_user}/"
path_to_session_folder += @open_ai[team_id_user_creator][:chat_gpt][:sessions][session_name][:copy_of_session].to_s
end
if Dir.exist?(path_to_session_folder)
if !File.exist?("#{path_to_session_folder}/chatgpt_prompts.json")
docs_folder_prompts = []
enc = Tiktoken.encoding_for_model("gpt-4") ["#{path_to_session_folder}/docs_folder/include/**/*", "#{path_to_session_folder}/docs_folder/filter/**/*"].each do |folder|
Dir.glob(folder).each do |file|
next if File.directory?(file)
file_content = File.read(file)
num_tokens = enc.encode(file_content.to_s).length
docs_folder_prompts << {
role: "user",
content: [
{ type: "text", text: file_content, include_file: file.include?("/docs_folder/include/"), num_tokens: num_tokens, clean_text: file },
],
}
end
end
File.open("#{path_to_session_folder}/chatgpt_prompts.json", "w") do |f|
f.write(docs_folder_prompts.to_json)
end
end
if File.exist?("#{path_to_session_folder}/chatgpt_prompts.json")
all_sentences = ""
prompts.each do |prompt|
if prompt[:role] == "user" and prompt[:content].size == 1 and prompt[:content][0][:type] == "text"
all_sentences += prompt[:content][0][:text] + " "
end
end
list_avoid = ["use", "set", "bash", term_to_avoid]
keywords = get_keywords(all_sentences, list_avoid: list_avoid)
file_content = File.read("#{path_to_session_folder}/chatgpt_prompts.json")
json_data = JSON.parse(file_content, symbolize_names: true)
keywords_num_docs = {}
keywords.delete_if do |k|
num_found = 0
json_data.each do |entry|
num_found += 1 if entry[:content][0][:text].match?(/#{k}/i) and !entry[:content][0][:clean_text].to_s.match?(/#{k}/i)
end
keywords_num_docs[k] = num_found
num_found > (json_data.size / 2)
end
data_num_keywords = {}
json_data.each do |entry|
num_found = 0
total_occurrences = 0
keywords.each do |k|
num_found += 1 if entry[:content][0][:text].match?(/#{k}/i)
total_occurrences += entry[:content][0][:text].scan(/#{k}/i).size
end
entry[:content][0][:total_occurrences] = total_occurrences
data_num_keywords[num_found] ||= []
data_num_keywords[num_found] << entry
end
data_num_keywords.delete(0)
data_num_keywords = data_num_keywords.sort_by { |k, v| k }.reverse.to_h
data_num_keywords.each do |k, v|
v.sort_by! { |entry| entry[:content][0][:total_occurrences] }.reverse!
end
if data_num_keywords.values.flatten.uniq.size > (json_data.size / 2) and data_num_keywords.keys.size > 1 and
data_num_keywords.key?(1) and (data_num_keywords.values.flatten.uniq.size - data_num_keywords[1].size) >= 10
data_num_keywords.delete(1)
end
filtered_data = data_num_keywords.values.flatten.uniq
json_data.each do |entry|
if entry[:content][0][:include_file]
filtered_data << entry
end
end
filtered_data.sort_by! { |entry| entry[:content][0][:include_file] ? 0 : 1 }
filtered_data.each do |entry|
entry[:content].each do |content_block|
content_block.delete(:include_file)
content_block.delete(:total_occurrences)
end
end
filtered_data.uniq!
enc = Tiktoken.encoding_for_model("gpt-4") prompts_orig = prompts.deep_copy
prompts = filtered_data + prompts
content = ""
prompts.each do |prompt|
content += prompt[:content][0][:text] if prompt.key?(:content) and prompt[:content][0].key?(:text)
end
num_tokens = enc.encode(content.to_s).length
respond ":information_source: The number of tokens in the prompt including all filtered docs is *#{num_tokens}*.\n\tWe will remove docs to ensure we don't reach the max num of allowed tokens for this ChatGPT model." if num_tokens > max_num_tokens
if num_tokens > (max_num_tokens - 1000) while num_tokens > (max_num_tokens - 1000) and filtered_data.size > 0
filtered_data.pop
prompts = filtered_data + prompts_orig
content = ""
num_tokens = 0
prompts.each do |prompt|
if prompt[:content][0].key?(:num_tokens) and prompt[:content][0][:num_tokens] > 0
num_tokens += prompt[:content][0][:num_tokens]
else
if prompt.key?(:content) and prompt[:content][0].key?(:text)
content += prompt[:content][0][:text]
end
end
end
num_tokens += enc.encode(content.to_s).length if content != ""
end
end
num_folder_docs = filtered_data.size
end
prompts.each do |entry|
entry[:content].each do |content_block|
content_block.delete(:num_tokens)
end
end
end
if @chat_gpt_default_model != model and File.exist?("#{config.path}/openai/restricted_models.yaml")
restricted_models = YAML.load_file("#{config.path}/openai/restricted_models.yaml")
if restricted_models.key?(model) and !restricted_models[model].include?(team_id_user_creator) and !restricted_models[model].include?(user_creator)
respond "You don't have access to this model: #{model}. You can request access to an admin user."
restricted = true
end
end
if !restricted
success, res = SlackSmartBot::AI::OpenAI.send_gpt_chat(@ai_open_ai[team_id_user_creator][:chat_gpt][:client], model, prompts, @ai_open_ai[team_id_user_creator].chat_gpt)
if success
@ai_gpt[team_id_user_creator][session_name] << { role: "assistant", content: [{ type: "text", text: res }] }
@ai_gpt[team_id_user_creator][session_name] << system_prompt if system_prompt
end
end
end
unless restricted
enc = Tiktoken.encoding_for_model("gpt-4") content = ""
prompts.each do |prompt|
content += prompt[:content][0][:text] if prompt.key?(:content) and prompt[:content][0].key?(:text)
end
num_tokens = enc.encode(content.to_s).length
if num_tokens > max_num_tokens and type != :clean
message_max_tokens = ":warning: The total number of tokens in the prompt is #{num_tokens}, which is greater than the maximum number of tokens allowed for the model (#{max_num_tokens})."
message_max_tokens += "\nTry to be more concrete writing your prompt. The number of docs attached according to your prompt was #{num_folder_docs}\n" if num_folder_docs > 0
respond message_max_tokens
end
if session_name == ""
temp_session_name = @ai_gpt[team_id_user_creator][""].first.content.first.text.to_s[0..35] res_slack_mkd = transform_to_slack_markdown(res.to_s.strip)
if num_folder_docs > 0
docs_message = "\n:notebook_with_decorative_cover: *#{num_folder_docs} documents* were added for this prompt (keywords: _#{keywords.sort[0..9].join(", ")}#{" ..." if keywords.size > 10}_)\n\n"
else
docs_message = ""
end
obj_id = @ai_gpt[team_id_user_creator][""].first.object_id
respond "*ChatGPT* Temporary session: _<#{temp_session_name.gsub("\n", " ").gsub("`", " ")}...>_ (#{obj_id}) model: #{model} num_tokens: #{num_tokens}#{docs_message}\n#{res_slack_mkd}", split: false
if res.to_s.strip == ""
respond "It seems like GPT is not responding. Please try again later or use another model, as it might be overloaded."
end
if config.encrypt
Thread.current[:encrypted] ||= []
Thread.current[:encrypted] << message
end
elsif res.to_s.strip == ""
res = "\nAll prompts were removed from session." if delete_history
respond "*ChatGPT* Session _<#{session_name}>_ model: #{model}#{res}"
respond "It seems like GPT is not responding. Please try again later or use another model, as it might be overloaded." if message != ""
else
res_slack_mkd = transform_to_slack_markdown(res.to_s.strip)
if num_folder_docs > 0
docs_message = "\n:open_file_folder: #{num_folder_docs} documents from the folder were added to the prompts."
else
docs_message = ""
end
respond "*ChatGPT* Session _<#{session_name}>_ model: #{model} num_tokens: #{num_tokens}#{docs_message}\n#{res_slack_mkd}", split: false
end
if urls_messages.size > 0
respond urls_messages.join("\n")
end
end
end
update_openai_sessions(session_name, team_id: team_creator, user_name: user_creator) unless session_name == "" or !success or restricted
rescue => exception
respond "*ChatGPT*: Sorry, I'm having some problems. OpenAI probably is not available. Please try again later."
@logger.warn exception
end
unreact :speech_balloon
end
end
end
end
|