-
Notifications
You must be signed in to change notification settings - Fork 1
/
ChatTk.py
1088 lines (850 loc) · 42.5 KB
/
ChatTk.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
import tkinter as tk
import tkinter.messagebox as messagebox
from tkinter import filedialog
import asyncio
from openai import AzureOpenAI, AsyncAzureOpenAI
import openai
import os
import io
import threading
import datetime
import json
import urllib
from PIL import Image, ImageTk, ImageGrab
import base64
from dotenv import load_dotenv
#Feature Flags for additional functionality
Flag_DALLE = False
try:
# Loads the following environment variables from the .env file:
#AZURE_OPENAI_API_KEY - Obtain from https://portal.azure.com (Azure OpenAI Service > Keys and Endpoint)
#AZURE_OPENAI_API_BASE - Obtain from https://oai.azure.com/portal (Azure OpenAI Service > Keys and Endpoint)
#DALLE_API_KEY - Obtain from https://oai.azure.com/portal
#DALLE_API_ENDPOINT - Obtain from https://oai.azure.com/portal
load_dotenv()
AZURE_OPENAI_API_KEY = os.environ['AZURE_OPENAI_API_KEY']
AZURE_OPENAI_API_ENDPOINT = os.environ['AZURE_OPENAI_API_ENDPOINT']
AZURE_OPENAI_API_MODEL = os.environ['AZURE_OPENAI_API_MODEL']
AZURE_OPENAI_API_VERSION = os.environ['AZURE_OPENAI_API_VERSION']
if Flag_DALLE:
DALLE_API_KEY = os.environ['DALLE_API_KEY']
DALLE_API_ENDPOINT = os.environ['DALLE_API_ENDPOINT']
DALLE_API_MODEL = os.environ['DALLE_API_MODEL']
except Exception:
# pop up an error message staring the .env file could not be found
messagebox.showerror("Error", "The .env file could not be found. Please ensure the .env file is in the same folder as the ChatAA executable.")
# exit the application
exit()
version = AZURE_OPENAI_API_VERSION
key = AZURE_OPENAI_API_KEY
endpoint = AZURE_OPENAI_API_ENDPOINT
model = AZURE_OPENAI_API_MODEL # customize this for your own model deployment within the Azure OpenAI Service (e.g. "gpt-4", "gpt-4-32k", "gpt-35-turbo")
client = AsyncAzureOpenAI(
azure_endpoint = endpoint,
api_key = key,
api_version = version
)
chatbot_name = "ChatTk"
file_path = ""
icon_path = "icon16ChatTk.ico"
few_shot_examples = []
font_text = "Consolas 11"
# Set variables - https://learn.microsoft.com/en-us/azure/cognitive-services/openai/reference
var_temperature = 0.7 # between 0 and 1
var_top_p=0.95 # between 0 and 1
var_max_tokens = 800 # between 1 and 32,768
var_frequency_penalty = 0 # between -2.0 and 2.0
var_presence_penalty = 0 # between -2.0 and 2.0
var_past_messages_included = 10 # between 1 and 20
global system_message
global system_message_chunk
system_message = "Your name is " + chatbot_name + ". You are a large language model. You are using the " + model + " AI model via the Azure OpenAI Service. Answer as concisely as possible. Knowledge cutoff: October 2023. Current date: "+str(datetime.date.today())
system_message_chunk = [{"role":"system","content":system_message}]
few_shot_chunk = []
chat_history_chunk = []
# Function to get the response from the OpenAI API after the 'Send' button is clicked
def send():
global chat_history_chunk
global chat_history_chunk_image
ask_button.config(state="disabled")
clear_button.config(state="disabled")
add_image_button.config(state="disabled")
# Disable the Remove Image button, if it's there
for widget in root.winfo_children():
if isinstance(widget, tk.Button) and widget["text"] == "Remove Image":
widget.config(state="disabled")
if Flag_DALLE:
dalle_button.config(state="disabled")
# Get the user's prompt from the input box
input_text = input_box.get("1.0", "end")
output_box.configure(state="normal")
output_box.insert("end", "User: " + " "*(len(chatbot_name)-4) + input_text+"\n")
output_box.configure(state="disabled")
output_box.see("end") # Scroll to the bottom of the output box
# Insert the user's prompt into the chat history
# N.B. I have no idea why I need to rstrip('\n') here, but it prevents trailing new line characters from being added to the chat history
if file_path:
if file_path != "CLIPBOARD":
IMAGE_PATH = file_path
def encode_image(image_path):
with open(image_path, "rb") as image_file:
return base64.b64encode(image_file.read()).decode("utf-8")
base64_image = encode_image(IMAGE_PATH)
elif file_path == "CLIPBOARD":
global gpt4o_image
buffered = io.BytesIO()
gpt4o_image.save(buffered, format="PNG")
base64_image = base64.b64encode(buffered.getvalue()).decode("utf-8")
inputdict = {
"role":"user",
"content": [
{"type": "text", "text": input_text.rstrip('\n')},
{"type": "image_url", "image_url": {"url": f"data:image/png;base64,{base64_image}"}}
]
}
chat_history_chunk_image = chat_history_chunk
chat_history_chunk_image.append(inputdict)
inputdict = {
"role":"user",
"content": [
{"type": "text", "text": input_text.rstrip('\n')},
]
}
chat_history_chunk.append(inputdict)
# Clear the input box
input_box.delete("1.0", "end")
# Create a new thread for the API call
api_thread = threading.Thread(target=call_api)
api_thread.start()
# Function to call the OpenAI API in a separate thread to prevent locking-up the application while waiting for the API response
def call_api():
def generate_text():
try:
if file_path:
chat_history = chat_history_chunk_image
else:
chat_history = chat_history_chunk
reply = ""
async def main() -> None:
stream = await client.chat.completions.create(
model=model,
messages=system_message_chunk+few_shot_chunk+chat_history[-var_past_messages_included:],
temperature=var_temperature,
max_tokens=var_max_tokens,
top_p=var_top_p,
frequency_penalty=var_frequency_penalty,
presence_penalty=var_presence_penalty,
stop=None,
stream=True,
)
reply = ""
chatbot_name_displayed=False
async for chunk in stream:
if chunk.choices:
if chatbot_name_displayed == False:
output_box.configure(state="normal")
output_box.insert("end", chatbot_name +": ")
output_box.configure(state="disabled")
chatbot_name_displayed=True
content = chunk.choices[0].delta.content
if content is not None and isinstance(content, str):
output_box.configure(state="normal")
output_box.insert("end", content)
output_box.configure(state="disabled")
output_box.see("end")
reply = reply + content
asyncio.run(main())
output_box.configure(state="normal")
#Insert two new lines after the response
output_box.insert("end", "\n\n")
output_box.configure(state="disabled")
output_box.see("end")
# Insert the chatbot's response into the chat history
contentdict = {"role":"assistant","content":reply}
chat_history_chunk.append(contentdict)
except openai.AuthenticationError as e:
# Handle Authentication error here, e.g. invalid API key
messagebox.showerror("Error", f"OpenAI API returned an Authentication Error: {e}")
except openai.APIConnectionError as e:
# Handle connection error here
messagebox.showerror("Error", f"Failed to connect to OpenAI API: {e}")
except openai.BadRequestError as e:
# Handle connection error here
messagebox.showerror("Error", f"Invalid Request Error: {e}")
except openai.RateLimitError as e:
# Handle rate limit error
messagebox.showerror("Error", f"OpenAI API request exceeded rate limit: {e}")
except openai.InternalServerError as e:
# Handle Service Unavailable error
messagebox.showerror("Error", f"Service Unavailable: {e}")
except openai.APITimeoutError as e:
# Handle request timeout
messagebox.showerror("Error", f"Request timed out: {e}")
except openai.APIError as e:
# Handle API error here, e.g. retry or log
messagebox.showerror("Error", f"OpenAI API returned an API Error: {e}")
except:
# Handles all other exceptions
messagebox.showerror("Error", f"An exception has occured.")
ask_button.config(state="normal")
clear_button.config(state="normal")
add_image_button.config(state="normal")
# Enable the Remove Image button, if it's there
for widget in root.winfo_children():
if isinstance(widget, tk.Button) and widget["text"] == "Remove Image":
widget.config(state="normal")
#remove_image()
if Flag_DALLE:
dalle_button.config(state="normal")
# Create a new thread to run the generate_text function
thread = threading.Thread(target=generate_text)
thread.start()
def dalle_prompt_thread():
ask_button.config(state="disabled")
clear_button.config(state="disabled")
add_image_button.config(state="disabled")
# Disable the Remove Image button, if it's there
for widget in root.winfo_children():
if isinstance(widget, tk.Button) and widget["text"] == "Remove Image":
widget.config(state="disabled")
if Flag_DALLE:
dalle_button.config(state="disabled")
t = threading.Thread(target=dalle_prompt)
t.start()
def dalle_prompt():
global DALLE_API_KEY
global DALLE_API_ENDPOINT
global DALLE_API_MODEL
DALLEclient = AzureOpenAI(
api_version=AZURE_OPENAI_API_VERSION,
azure_endpoint=DALLE_API_ENDPOINT,
api_key=DALLE_API_KEY,
)
response = DALLEclient.images.generate(
model=DALLE_API_MODEL,
prompt='A photo of a car',
size='1024x1024',
n=1
)
image_url = json.loads(response.model_dump_json())['data'][0]['url']
# create a new window to display the image
image_window = tk.Toplevel(root)
image_window.title('DALL·E 3 generated image a car')
image_window.geometry("1024x1024")
# download the image and create a PhotoImage object
image_data = urllib.request.urlopen(image_url).read()
DALLEimage = Image.open(io.BytesIO(image_data))
photo = ImageTk.PhotoImage(DALLEimage)
# create a label to display the image
image_label = tk.Label(image_window, DALLEimage=photo)
image_label.pack()
# update the image label to prevent garbage collection
image_label.image = photo
ask_button.config(state="normal")
clear_button.config(state="normal")
add_image_button.config(state="normal")
# Enable the Remove Image button, if it's there
for widget in root.winfo_children():
if isinstance(widget, tk.Button) and widget["text"] == "Remove Image":
widget.config(state="enabled")
if Flag_DALLE:
dalle_button.config(state="normal")
# Function to clear the chat boxes, and reset the chat history
def clear_chat():
input_box.delete("1.0", "end")
output_box.configure(state="normal")
output_box.delete("1.0", "end")
output_box.configure(state="disabled")
remove_image()
global chat_history_chunk
global system_message_chunk
chat_history_chunk = []
system_message_chunk = [{"role":"system","content":system_message}]
def get_clipboard(event=None):
# Check if ImageGrab.grabclipboard() is an image
if isinstance(ImageGrab.grabclipboard(), Image.Image):
global gpt4o_image
global file_path
# get the clipboard data and assign to gpt4o_image
gpt4o_image = ImageGrab.grabclipboard()
file_path = "CLIPBOARD"
get_image()
def add_image():
global file_path
root = tk.Tk()
root.withdraw() # Hide the main window
file_path = filedialog.askopenfilename(filetypes=[("Image files", "*.jpg *.png")]) # Open the file dialog
if file_path:
global gpt4o_image
gpt4o_image = Image.open(file_path)
get_image()
root.destroy() # Close the Tkinter root window
def get_image(event=None):
try:
if isinstance(gpt4o_image, Image.Image):
# Resize the image proportionally to a height of 67 pixels
base_height = 67
w_percent = (base_height / float(gpt4o_image.size[1]))
w_size = int((float(gpt4o_image.size[0]) * float(w_percent)))
thumbnailimage = gpt4o_image.resize((w_size, base_height), Image.LANCZOS)
# Convert the thumbnail image to a format Tkinter can use
tk_thumbnail = ImageTk.PhotoImage(thumbnailimage)
# Display the thumbnail image in the label
thumbnailimage_label.config(image=tk_thumbnail)
thumbnailimage_label.image = tk_thumbnail
# Repack the thumbnailimage_label
thumbnailimage_label.pack(side="left", padx=6, pady=5)
# When the thumbnail is clicked, create a new window and display the full-size image
def on_thumbnail_click(event):
top = tk.Toplevel()
top.title("Full-size Image")
# Convert the full-size image to a format Tkinter can use
tk_image = ImageTk.PhotoImage(gpt4o_image)
# Display the full-size image in a label in the new window
label = tk.Label(top, image=tk_image)
label.image = tk_image
label.pack()
thumbnailimage_label.bind("<Button-1>", on_thumbnail_click)
# Remove any existing instances of the remove_button
for widget in root.winfo_children():
if isinstance(widget, tk.Button) and widget["text"] == "Remove Image":
widget.pack_forget()
# Add a button to the right of the thumbnail
global remove_button
remove_button = tk.Button(root, text="Remove Image", command=remove_image, height=4, width=12)
remove_button.pack(side="left", padx=6, pady=5)
else:
messagebox.showerror("Error", "No image found in clipboard")
except Exception as e:
messagebox.showerror("Error", str(e))
# Function to remove the image and the button
def remove_image():
global file_path
try:
thumbnailimage_label.config(image=None)
thumbnailimage_label.image = None
thumbnailimage_label.forget()
remove_button.destroy()
except:
pass
finally:
file_path = ""
# Function to handle the "Return" key event
def handle_return(event):
send()
return "break" # Prevents the default behavior of the "Return" key adding a stray carriage return after the input box has been cleared
def open_about_window():
# Create a new window
about_window = tk.Toplevel(root)
about_window.title("About " + chatbot_name)
# Set the icon if the file exists, otherwise use the default icon
if os.path.exists(icon_path):
try:
about_window.iconbitmap(icon_path)
except tk.TclError:
pass
# Set the size of the window to be 250x150
about_window.geometry("250x150")
# Create a Label to display the About message
about_message = "Created by Guy Gregory\[email protected]\nhttps://aka.ms/ChatToolkit"
about_label = tk.Label(about_window, text=about_message, font=font_text)
about_label.pack(side="top", fill="both", expand=True)
# Create a button to cancel and close the window
def cancel_and_close():
# Close the window without saving
about_window.destroy()
cancel_button = tk.Button(about_window, text="Close", command=cancel_and_close)
cancel_button.pack(side="bottom", anchor="center", pady=5)
def open_chatbot_name_window():
# Create a new window
chatbot_name_window = tk.Toplevel(root)
chatbot_name_window.title("Edit chat bot name")
chatbot_name_window.geometry("250x100")
chatbot_name_window.minsize(300, 120) # Set the minimum width to 250 pixels
# Set the icon if the file exists, otherwise use the default icon
if os.path.exists(icon_path):
try:
chatbot_name_window.iconbitmap(icon_path)
except tk.TclError:
pass
# Create a frame to hold the message box
message_box_frame = tk.Frame(chatbot_name_window)
message_box_frame.pack(side="top", fill="both", expand=True)
# configure the grid
root.columnconfigure(0, weight=1)
root.columnconfigure(1, weight=3)
# Chat bot name
global chatbot_name
chatbot_name_label = tk.Label(message_box_frame, text="Chat bot name:", font=font_text)
chatbot_name_label.grid(column=0, row=0, sticky=tk.E, padx=5, pady=5)
chatbot_name_entry = tk.Entry(message_box_frame, font=font_text, width=14)
chatbot_name_entry.grid(column=1, row=0, sticky=tk.W, padx=5, pady=5)
chatbot_name_entry.insert(0, chatbot_name)
# Create a button to save and close the window
def save_and_close():
# Save the system message and close the window
global chatbot_name
global system_message
system_message = system_message.replace(chatbot_name, chatbot_name_entry.get(), 1)
chatbot_name = chatbot_name_entry.get()
root.title(chatbot_name)
chatbot_name_window.destroy()
clear_chat()
save_button = tk.Button(chatbot_name_window, text="Save and close", command=save_and_close)
save_button.pack(side="left", padx=6, pady=5)
# Create a button to cancel and close the window
def cancel_and_close():
# Close the window without saving
chatbot_name_window.destroy()
cancel_button = tk.Button(chatbot_name_window, text="Cancel", command=cancel_and_close)
cancel_button.pack(side="right", padx=16, pady=5)
def open_system_message_window():
# Create a new window
system_message_window = tk.Toplevel(root)
system_message_window.title("Edit system message")
system_message_window.geometry("400x200")
system_message_window.minsize(600, 480) # Set the minimum width to 600 pixels
# Set the icon if the file exists, otherwise use the default icon
if os.path.exists(icon_path):
try:
system_message_window.iconbitmap(icon_path)
except tk.TclError:
pass
# Create a frame to hold the message box and scrollbar
message_box_frame = tk.Frame(system_message_window)
message_box_frame.pack(side="top", fill="both", expand=True)
# Create a text box with the initial value set to system_message
message_box = tk.Text(message_box_frame, wrap="word", font=font_text, height=10)
message_box.insert("end", system_message)
message_box.pack(side="left", fill="both", expand=True)
# Create a vertical scrollbar and attach it to the message_box
scrollbar = tk.Scrollbar(message_box_frame, orient="vertical", command=message_box.yview)
scrollbar.pack(side="right", fill="y")
message_box.config(yscrollcommand=scrollbar.set)
# Create a button to save and close the window
def save_and_close():
# Save the system message and close the window
global system_message
system_message = message_box.get("1.0", "end-1c")
system_message_window.destroy()
clear_chat()
save_button = tk.Button(system_message_window, text="Save and close", command=save_and_close)
save_button.pack(side="left", padx=6, pady=5)
# Create a button to cancel and close the window
def cancel_and_close():
# Close the window without saving
system_message_window.destroy()
cancel_button = tk.Button(system_message_window, text="Cancel", command=cancel_and_close)
cancel_button.pack(side="right", padx=16, pady=5)
def open_api_options_window():
# Create a new window
api_options_window = tk.Toplevel(root)
api_options_window.title("Edit API Options")
api_options_window.geometry("400x200")
api_options_window.minsize(600, 480) # Set the minimum width to 600 pixels
# Set the icon if the file exists, otherwise use the default icon
if os.path.exists(icon_path):
try:
api_options_window.iconbitmap(icon_path)
except tk.TclError:
pass
# Create a frame to hold the message box
message_box_frame = tk.Frame(api_options_window)
message_box_frame.pack(side="top", fill="both", expand=True)
# configure the grid
root.columnconfigure(0, weight=1)
root.columnconfigure(1, weight=3)
# API base URL
api_base_label = tk.Label(message_box_frame, text="API base URL:", font=font_text)
api_base_label.grid(column=0, row=0, sticky=tk.E, padx=5, pady=5)
api_base_entry = tk.Entry(message_box_frame, font=font_text, width=42)
api_base_entry.grid(column=1, row=0, sticky=tk.W, padx=5, pady=5)
api_base_entry.insert(0, endpoint)
# API key
api_key_label = tk.Label(message_box_frame, text="API key:", font=font_text)
api_key_label.grid(column=0, row=1, sticky=tk.E, padx=5, pady=5)
api_key_entry = tk.Entry(message_box_frame, show="*", font=font_text, width=32)
api_key_entry.grid(column=1, row=1, sticky=tk.W, padx=5, pady=5)
api_key_entry.insert(0, key)
# Create a button to show/hide the API key
show_hide_button = tk.Button(message_box_frame, text="Show/hide", command=lambda: toggle_show(api_key_entry))
show_hide_button.grid(column=1, row=1, sticky=tk.E, padx=5)
def toggle_show(entry_widget):
if entry_widget.cget("show") == "*":
entry_widget.configure(show="")
else:
entry_widget.configure(show="*")
# API version
api_version_label = tk.Label(message_box_frame, text="API version:", font=font_text)
api_version_label.grid(column=0, row=3, sticky=tk.E, padx=5, pady=5)
api_version_entry = tk.Entry(message_box_frame, font=font_text)
api_version_entry.grid(column=1, row=3, sticky=tk.W, padx=5, pady=5)
api_version_entry.insert(0, version)
# Model deployment name
model_label = tk.Label(message_box_frame, text="Model deployment name:", font=font_text)
model_label.grid(column=0, row=4, sticky=tk.E, padx=5, pady=5)
model_entry = tk.Entry(message_box_frame, font=font_text)
model_entry.grid(column=1, row=4, sticky=tk.W, padx=5, pady=5)
model_entry.insert(0, model)
# Max tokens
max_tokens_label = tk.Label(message_box_frame, text="Max tokens:", font=font_text)
max_tokens_label.grid(column=0, row=5, sticky=tk.E, padx=5, pady=5)
max_tokens_spinbox = tk.Spinbox(message_box_frame, from_=16, to=32768, increment=100, font=font_text, width=5)
max_tokens_spinbox.grid(column=1, row=5, sticky=tk.W, padx=5, pady=5)
max_tokens_spinbox.delete(0, tk.END)
max_tokens_spinbox.insert(0, var_max_tokens)
# Temperature
temperature_label = tk.Label(message_box_frame, text="Temperature:", font=font_text)
temperature_label.grid(column=0, row=6, sticky=tk.E, padx=5, pady=5)
temperature_slider = tk.Scale(message_box_frame, from_=0, to=1, resolution=0.01, orient=tk.HORIZONTAL, length=165, showvalue=1)
temperature_slider.grid(column=1, row=6, sticky=tk.W, padx=2)
temperature_slider.set(var_temperature)
# Top p
top_p_label = tk.Label(message_box_frame, text="Top p:", font=font_text)
top_p_label.grid(column=0, row=7, sticky=tk.E, padx=5, pady=5)
top_p_slider = tk.Scale(message_box_frame, from_=0, to=1, resolution=0.01, orient=tk.HORIZONTAL, length=165, showvalue=1)
top_p_slider.grid(column=1, row=7, sticky=tk.W, padx=2)
top_p_slider.set(var_top_p)
# Frequency penalty
frequency_penalty_label = tk.Label(message_box_frame, text="Frequency penalty:", font=font_text)
frequency_penalty_label.grid(column=0, row=8, sticky=tk.E, padx=5, pady=5)
frequency_penalty_slider = tk.Scale(message_box_frame, from_=-2, to=2, resolution=0.01, orient=tk.HORIZONTAL, length=165, showvalue=1)
frequency_penalty_slider.grid(column=1, row=8, sticky=tk.W, padx=2)
frequency_penalty_slider.set(var_frequency_penalty)
# Presence penalty
presence_penalty_label = tk.Label(message_box_frame, text="Presence penalty:", font=font_text)
presence_penalty_label.grid(column=0, row=9, sticky=tk.E, padx=5, pady=5)
presence_penalty_slider = tk.Scale(message_box_frame, from_=-2, to=2, resolution=0.01, orient=tk.HORIZONTAL, length=165, showvalue=1)
presence_penalty_slider.grid(column=1, row=9, sticky=tk.W, padx=2)
presence_penalty_slider.set(var_presence_penalty)
# Past messages
past_messages_label = tk.Label(message_box_frame, text="Past messages included:", font=font_text)
past_messages_label.grid(column=0, row=10, sticky=tk.E, padx=5, pady=5)
past_messages_slider = tk.Scale(message_box_frame, from_=1, to=20, resolution=1, orient=tk.HORIZONTAL, length=165, showvalue=1)
past_messages_slider.grid(column=1, row=10, sticky=tk.W, padx=2)
past_messages_slider.set(var_past_messages_included)
# Create a button to save and close the window
def save_and_close():
global base
global key
global version
# Save the system message and close the window
base = api_base_entry.get()
key = api_key_entry.get()
#openai.api_type = api_type_entry.get()
version = api_version_entry.get()
global model
global system_message
global var_temperature
global var_top_p
global var_max_tokens
global var_frequency_penalty
global var_presence_penalty
global var_past_messages_included
system_message = system_message.replace(model, model_entry.get(), 1)
model = model_entry.get()
var_temperature=temperature_slider.get()
var_top_p=top_p_slider.get()
var_frequency_penalty=frequency_penalty_slider.get()
var_presence_penalty=presence_penalty_slider.get()
var_max_tokens=int(max_tokens_spinbox.get())
var_past_messages_included=int(past_messages_slider.get())
api_options_window.destroy()
clear_chat()
save_button = tk.Button(api_options_window, text="Save and close", command=save_and_close)
save_button.pack(side="left", padx=6, pady=5)
# Create a button to reset the API options to the default values
def reset_api_options():
temperature_slider.set(0.7)
top_p_slider.set(0.95)
max_tokens_spinbox.delete(0, tk.END); max_tokens_spinbox.insert(0, 800)
frequency_penalty_slider.set(0)
presence_penalty_slider.set(0)
past_messages_slider.set(10)
reset_api_options_button = tk.Button(api_options_window, text="Reset to defaults", command=reset_api_options)
reset_api_options_button.pack(side="left", padx=97, pady=5)
# Create a button to cancel and close the window
def cancel_and_close():
# Close the window without saving
api_options_window.destroy()
cancel_button = tk.Button(api_options_window, text="Cancel", command=cancel_and_close)
cancel_button.pack(side="left", padx=82, pady=5)
# Create a function which allows the user to pick a .json file to import the API options from
def open_import_template():
# Create a file dialog to select the .json file
template_file_path = filedialog.askopenfilename(initialdir=os.getcwd(), title="Select a file", filetypes=(("JSON files", "*.json"), ("All files", "*.*")))
if template_file_path != "":
# Try to open the .json file and load the data, but catch any errors and display a message box
try:
# Open the .json file and load the data
with open(template_file_path, "r", encoding="utf-8") as file:
data = json.load(file)
clear_chat()
global model
global system_message
global var_temperature
global var_top_p
global var_max_tokens
global var_frequency_penalty
global var_presence_penalty
global chat_history_chunk
global system_message_chunk
global chatbot_name
global few_shot_examples
global var_past_messages_included
# Set the model deployment name
model = data["chatParameters"]["deploymentName"]
# Set the system message
system_message = data["systemPrompt"]
few_shot_jsondata = data["fewShotExamples"]
# Iterate over the list and modify the key 'userInput' to 'user'
few_shot_examples = []
for item in few_shot_jsondata:
modified_item = {'user': item['userInput'], 'assistant': item['chatbotResponse']}
few_shot_examples.append(modified_item)
update_few_shot_chunk()
system_message_chunk = [{"role":"system","content":system_message}]
# Set the API options
var_temperature = data["chatParameters"]["temperature"]
var_top_p = data["chatParameters"]["topProbablities"]
var_max_tokens = data["chatParameters"]["maxResponseLength"]
var_frequency_penalty = data["chatParameters"]["frequencyPenalty"]
var_presence_penalty = data["chatParameters"]["presencePenalty"]
var_past_messages_included = data["chatParameters"]["pastMessagesToInclude"]
# Set the chat bot name to the name of the .json file (without the extension)
chatbot_name = os.path.basename(template_file_path).split(".")[0]
root.title(chatbot_name)
except Exception as e:
messagebox.showerror("Error", "An error occurred while trying to import the API options from the selected template file.\n\n" + str(e))
# Create a function which takes the System Message and API Options and exports the data to a .json file, using the chat bot name as the file name, allowing the user to choose the save location with a file dialog
def open_export_template():
# Change the format of the few_shot_examples to match the format of the template
few_shot_jsondata = []
for item in few_shot_examples:
modified_item = {'userInput': item['user'], 'chatbotResponse': item['assistant']}
few_shot_jsondata.append(modified_item)
# Create a file dialog to select the save location
save_file_path = filedialog.asksaveasfilename(initialdir=os.getcwd(), title="Select a file", filetypes=(("JSON files", "*.json"), ("All files", "*.*")), initialfile=chatbot_name + ".json")
if save_file_path != "":
# Try to save the .json file, but catch any errors and display a message box
try:
# Create a dictionary containing the System Message and API Options
data = {
"systemPrompt": system_message,
"fewShotExamples": few_shot_jsondata,
"chatParameters": {
"deploymentName": model,
"temperature": var_temperature,
"topProbablities": var_top_p,
"maxResponseLength": var_max_tokens,
"frequencyPenalty": var_frequency_penalty,
"presencePenalty": var_presence_penalty,
"stopSequences": None,
"pastMessagesToInclude":10
}
}
# Save the .json file
with open(save_file_path, "w", encoding="utf-8") as file:
json.dump(data, file, indent=4, ensure_ascii=False)
# Display a message box to confirm the file was saved successfully
messagebox.showinfo("Success", "The API options were successfully exported to the selected template file.")
except Exception as e:
messagebox.showerror("Error", "An error occurred while trying to export the API options to the selected template file.\n\n" + str(e))
def open_few_shot_window():
# Create a new window
global few_shot_window
few_shot_window = tk.Toplevel(root)
few_shot_window.transient(root)
few_shot_window.title("Few shot examples")
container = tk.Frame(few_shot_window)
canvas = tk.Canvas(container, width=600, height=715)
scrollbar = tk.Scrollbar(container, orient="vertical", command=canvas.yview)
global scrollable_frame
scrollable_frame = tk.Frame(canvas, width=600, height=715)
scrollable_frame.bind(
"<Configure>",
lambda e: canvas.configure(
scrollregion=canvas.bbox("all")
)
)
canvas.create_window((0, 0), window=scrollable_frame, anchor="nw")
canvas.configure(yscrollcommand=scrollbar.set)
create_widgets()
container.pack()
canvas.pack(side="left", fill="both", expand=True)
scrollbar.pack(side="right", fill="y")
save_button = tk.Button(few_shot_window, text="Save and close", command=fs_save_and_close)
save_button.pack(side="left", padx=6, pady=5)
cancel_button = tk.Button(few_shot_window, text="Cancel", command=fs_cancel_and_close)
cancel_button.pack(side="right", padx=16, pady=5)
def add_example():
check_for_empty_examples()
if breakFlag==False:
update_few_shot_examples_from_UI()
else:
return
update_few_shot_examples_from_UI()
# Add a new example to the list
few_shot_examples.append({"user": "", "assistant": ""})
# Destroy all existing widgets
for widget in scrollable_frame.winfo_children():
widget.destroy()
# Recreate all few_shot_example widgets from scratch using the updated list
create_widgets()
def create_widgets():
# Function to recreate all few_shot_example widgets from scratch using the updated list
i = 0
for example in few_shot_examples:
# Create a label for the user input
user_input_label = tk.Label(scrollable_frame, text="User:")
user_input_label.grid(row=(i*5), column=0, sticky="W")
# Create a text box for the user input
user_input = tk.Text(scrollable_frame, font=font_text, width=72, height=4, wrap="word")
user_input.insert("1.0", example["user"])
user_input.grid(row=(i*5)+1, column=0)
# Create a vertical scrollbar and attach it to the user_input text box
user_input_scrollbar = tk.Scrollbar(scrollable_frame, orient="vertical", command=user_input.yview)
user_input_scrollbar.grid(row=(i*5)+1, column=1, sticky="NS")
user_input["yscrollcommand"] = user_input_scrollbar.set
# Create a label for the assistant response
chatbot_response_label = tk.Label(scrollable_frame, text="Assistant:")
chatbot_response_label.grid(row=(i*5)+2, column=0, sticky="W")
# Create a text box for the chatbot response
chatbot_response = tk.Text(scrollable_frame, font=font_text, width=72, height=4, wrap="word")
chatbot_response.insert("1.0", example["assistant"])
chatbot_response.grid(row=(i*5)+3, column=0)
# Create a vertical scrollbar and attach it to the chatbot_response text box
chatbot_response_scrollbar = tk.Scrollbar(scrollable_frame, orient="vertical", command=chatbot_response.yview)
chatbot_response_scrollbar.grid(row=(i*5)+3, column=1, sticky="NS")
chatbot_response["yscrollcommand"] = chatbot_response_scrollbar.set
# Create a blank label to separate the examples
blank_label = tk.Label(scrollable_frame, text=" ")
blank_label.grid(row=(i*5)+4, column=0)
# Create a delete button for the example
delete_button = tk.Button(scrollable_frame, text="🗑️", command=lambda i=i: delete_example(i))
delete_button.grid(row=(i*5), column=0, sticky="E")
i += 1
# Create a add button for the example, which is left-aligned within the cell
add_button = tk.Button(scrollable_frame, text="Add an example", command=add_example)
add_button.grid(row=(i*5)+5, column=0, sticky="W")
def check_for_empty_examples():
global breakFlag
breakFlag=False
for widget in scrollable_frame.winfo_children():
if widget.widgetName=="text":
if widget.get("1.0", "end-1c")=="":
messagebox.showwarning(parent=few_shot_window, title="Missing Entry", message="Please complete the text in all items or delete incomplete pairs before proceeding.")
#messagebox.showinfo(parent=few_shot_window, title="Info", message="This is a non-modal messagebox.")
breakFlag=True
break
def update_few_shot_examples_from_UI():
global few_shot_examples
saved_text=[]
for widget in scrollable_frame.winfo_children():
if widget.widgetName=="text":
saved_text.append(widget.get("1.0", "end-1c"))
saved_chat=[]
for index, text_element in enumerate(saved_text):
if index % 2 == 0:
saved_chat.append({"user": text_element})
else:
#saved_chat.append({"assistant": text_element})
saved_chat[-1]["assistant"]=text_element
few_shot_examples=saved_chat
def delete_example(index):
# Remove the example from the list
few_shot_examples.pop(index)
# Destroy all existing widgets
for widget in scrollable_frame.winfo_children():
widget.destroy()
# Recreate all few_shot_example widgets from scratch using the updated list
create_widgets()
def update_few_shot_chunk():
global few_shot_chunk
few_shot_chunk = []
for item in few_shot_examples:
few_shot_chunk.append({"role": "user", "content": item["user"]})
few_shot_chunk.append({"role": "assistant", "content": item["assistant"]})
# Create a button to save and close the window
def fs_save_and_close():
check_for_empty_examples()
if breakFlag==False:
update_few_shot_examples_from_UI()
update_few_shot_chunk()
few_shot_window.destroy()
else:
return
# Create a button to cancel and close the window
def fs_cancel_and_close():
# Close the window without saving
few_shot_window.destroy()
# Create the GUI root window