forked from dminGod/CallGPT
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathchat_gpt.html
More file actions
966 lines (721 loc) · 34.5 KB
/
chat_gpt.html
File metadata and controls
966 lines (721 loc) · 34.5 KB
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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>CallGPT</title>
<!-- JQuery to make JavaScript a little simpler -->
<script src="https://code.jquery.com/jquery-3.6.3.min.js" integrity="sha256-pvPw+upLPUjgMXY0G+8O0xUf+/Im1MZjXxxgOcBQBXU=" crossorigin="anonymous"></script>
<script src="https://code.jquery.com/ui/1.13.2/jquery-ui.min.js"></script>
<!-- Bootstrap for styling and UI -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/css/bootstrap.min.css" />
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="https://code.jquery.com/ui/1.13.2/themes/base/jquery-ui.css">
</head>
<body>
<!-- Page Container div - start -->
<div class="container">
<!-- Top header start -->
<div class="row top-header">
<div class="col-lg-2">
<h3><span class="you">☎ Call</span><span class="chatgpt">GPT</span></h3>
</div>
<div class="col-lg-5 top_menu">
<!-- <span class="menu_item">Settings</span> -->
</div>
<div class="col-lg-4 status_message">
<div class="" id="status_message">.</div>
</div>
<div class="col-lg-2">
<input type="password" id="openai_key" class="form-control" placeholder="API key goes here" />
</div>
</div>
<!-- Top header end -->
<div class="row">
<!-- Left Section, Chatbox, tech selection, send button - start -->
<div class="col-lg-9">
<input type="text" id="chat_box" class="form-control" placeholder="Enter text here -- ctrl/command + enter to send the message" />
<div class="row tech_selection">
<div class="col-lg-9 topic">
<!-- Change the value="xxx" and the label like Golang -->
<span><input type="radio" name="topic" value="" checked="checked" /> Nothing </span>
<span><input type="radio" name="topic" data="other" custom_prefix="Give a quotation related to " value="inspirational_quote" /> Quote </span>
<span><input type="radio" name="topic" data="technology" value="python" /> Python </span>
<span><input type="radio" name="topic" data="technology" value="golang" /> Golang </span>
<span><input type="radio" name="topic" data="technology" value="regular expressions" /> RegEx </span>
<span><input type="radio" name="topic" data="technology" value="javascript" /> JavaScript </span>
<span><input type="radio" name="topic" data="technology" value="postgres" /> Postgres </span>
<!-- Change the value="xxx" and the label like Golang -->
<br/>
<small class="text pull_left"> 💡 You can just change this 👆🏻 in the HTML to suit your stack</small>
</div>
<div class="col-lg-3">
<button class="btn btn-primary" id="send_button">Send</button>
</div>
<div id="tabs">
<ul>
<li><a href="#tabs-1">Chatbox</a></li>
<li><a href="#tabs-2">Media Content</a></li>
</ul>
<div id="tabs-1">
<!-- Chat box - start -->
<div class="row">
<div class="col-lg-12" id="chat_response"></div>
</div>
<!-- Chat box - end -->
</div>
<div id="tabs-2">
<!-- Media Tab - start -->
<div class="row">
<div class="col-lg-12" id="media_tab"></div>
</div>
<!-- Media Tab - end -->
</div>
</div>
</div>
</div>
<!-- Left Section, Chatbox, tech selection, send button - end -->
<!-- Right Section, Settings and Usage stats - start -->
<div class="col-lg-3 right_section">
<!-- API Related Settings - start-->
<div class="api_settings right_panel">
<h6>API Settings: <span class="min_max">Show / Hide</span></h6>
<div class="wrapper">
<div class="right_single_setting">
Model Name: <br/>
<select id="model_name">
<option value="gpt-3.5-turbo">GPT 3.5 Turbo</option>
<option value="gpt-3.5-turbo-0301">GPT 3.5 Turbo-0301</option>
</select>
<br/>
</div>
<div class="right_single_setting">
Temprature: <span id="gpt_temprature_value">0.5</span> <small class="text pull_right">higher = more creative</small> <br/>
<input type="range" class="form-range" min="0" max="1" step="0.05" id="gpt_temprature">
</div>
<div class="right_single_setting">
Number of responses: <span id="n_gens">1</span> <small class="text pull_right">How many replies</small> <br/>
<input type="range" class="form-range" min="1" max="5" step="1" id="num_gens" value="1" />
</div>
<div class="right_single_setting">
<input type="checkbox" id="enable_max_tokens" /> Max Tokens: <span id="max_tokens">1</span> <small class="text pull_right">Max response tokens</small> <br/>
<input type="range" class="form-range" min="1" max="4096" step="10" id="num_tokens" value="4096" />
</div>
</div>
</div>
<!-- API Related Settings - end-->
<!-- API Usage - start-->
<div class="usage_reference right_panel">
<h6>API Usage Stats: <span class="min_max">Show / Hide</span></h6>
<div class="wrapper">
<b>Last Call:</b> <br/>
<span class="token_count_labels">Time taken: </span> <span id="last_time_taken">0</span> <br/>
<span class="token_count_labels">Prompt tokens: </span> <span id="prompt_tokens">0</span> <br/>
<span class="token_count_labels">Completion tokens: </span> <span id="completion_tokens">0</span> <br/>
<span class="token_count_labels"><b>Last call total:</b> </span> <span id="total_tokens">0</span> <br/>
<hr/>
<b>This Session:</b> <br/>
<span class="token_count_labels">Avg response time: </span> <span id="avg_time_taken">0</span> <br/>
<span class="token_count_labels">Prompt tokens: </span> <span id="total_prompt_tokens">0</span> <br/>
<span class="token_count_labels">Completion tokens: </span> <span id="total_completion_tokens">0</span> <br/>
<span class="token_count_labels"><b>Session total : </b></span> <span id="total_session_tokens">0</span> </b> <br/>
</div>
</div>
<!-- API Usage - end -->
<!-- API Usage - start-->
<div class="bot_plugins right_panel">
<h6>Chatbot actions available: <span class="min_max">Show / Hide</span></h6>
<div class="wrapper">
These are the things that this ChatBot can do. You can add your own actions too. See the docs for
more details.
<br/>
<div class="chat_actions_available_list">
</div>
</div>
</div>
<!-- API Usage - end -->
</div>
<!-- Right Section, Settings and Usage stats - end -->
</div><!-- row div - end -->
</div> <!-- Page Container div - end -->
<!---
--------------------------------------------------------------
Modify these Custom JavaScript functions
--------------------------------------------------------------
-->
<script type="text/javascript">
// This is a list of the functions that the bot can call:
var custom_functions = {
"___changeBackground": {
// What function to call when GPT sends this command:
call_function: myCustomBgFunction,
// This is a name that the user will see as a heading:
action_name: "Change Background color",
// User description -- what to show to the user to describe this action:
user_description: "Change the background color of this page",
// Explanation to give to ChatGPT as to what this function does, so
// it can decide to call it when the user requests it:
// Eg: "Change the background color of the page, use values valid for jquery css in the parameter"
func_explanation: "Change the background color of the page, use values valid for jquery css in the parameter",
// Example of how the user will request this feature:
user_request_pattern: "change the background color to {color name}",
// Name and parameter pattern:
// This text is only used to tell ChatGPT how to call your function:
func_name_param_pattern : '___changeBackground({color name})'
},
"___changeText": {
// What function to call when GPT sends this command:
call_function: myCustomTextFunction,
// This is a name that the user will see as a heading:
action_name: "Change text color",
// User description -- what to show to the user to describe this action:
user_description: "Change the text color of this page",
// Explanation to give to ChatGPT as to what this function does, so
// it can decide to call it when the user requests it:
// Eg: "Change the background color of the page, use values valid for jquery css in the parameter"
func_explanation: "Change the text color of the page, use values valid for jquery css in the parameter",
// Example of how the user will request this feature:
user_request_pattern: "change the text color to {color name} or change the page text color to {color name}",
// This text is only used to tell ChatGPT how to call your function:
func_name_param_pattern : '___changeText({color name})'
},
"___myHNTopItems": {
// What function to call when GPT sends this command:
call_function: myHNTopItems,
// This is a name that the user will see as a heading:
action_name: "Top Hacker News stories",
// User description -- what to show to the user to describe this action:
user_description: "Fetch the top stories from Hacker News - by default 10 are shown, you can ask for upto 100.",
// Explanation to give to ChatGPT as to what this function does, so
// it can decide to call it when the user requests it:
// Eg: "Change the background color of the page, use values valid for jquery css in the parameter"
func_explanation: "The function will fetch the top number of stories requested by the user, 10 if not specified and upto 100 if requested.",
// Example of how the user will request this feature:
user_request_pattern: "get me the top {number} stories from hn or get me the top {number} hackernews or fetch hn top {number} stories",
// This text is only used to tell ChatGPT how to call your function:
func_name_param_pattern : '___myHNTopItems({number of stories})'
},
"___searchDuckDuckGo": {
// What function to call when GPT sends this command:
call_function: searchDuckDuckGoImages,
// This is a name that the user will see as a heading:
action_name: "DuckDuckGo Image Search",
// User description -- what to show to the user to describe this action:
user_description: "Search for images with a query and optionally specify how many images should be retuned.",
func_explanation: "This function searches DuckDuckGo for images and returns the first 10 images by default, or upto 100 if specified.",
user_request_pattern: "search for images for {query} or search duckduckgo for {query} images and return {number} images or show me {number} images for {query} or show me {number} images for {query}",
}
}
// These are the actual functions that will be called when GPT sends the command:
// the params will be split and passed to the function as an array:
// Change the page background color example:
function myCustomBgFunction(params) {
console.log("Got request to change the color, params are: ", params)
// Replace the starting and ending " with nothing:
params = params.replace(/^"|"$/g, "");
// We got a reference as rgb(0-255, 0-255, 0-255) so we need to convert it to hex:
if (params.includes("rgb")) {
// Extract the numbers values:
var rgb = params.match(/\d+/g);
// Convert to hex:
params = "#" + ((1 << 24) + (parseInt(rgb[0]) << 16) + (parseInt(rgb[1]) << 8) + parseInt(rgb[2])).toString(16).slice(1);
}
$("body").css("background-color", params);
}
// Change the text color:
// Change the page text color example:
function myCustomTextFunction(params) {
console.log("Got request to change the text color, params are: ", params)
// Replace the starting and ending " with nothing:
params = params.replace(/^"|"$/g, "");
// We got a reference as rgb(0-255, 0-255, 0-255) so we need to convert it to hex:
if (params.includes("rgb")) {
// Extract the numbers values:
var rgb = params.match(/\d+/g);
// Convert to hex:
params = "#" + ((1 << 24) + (parseInt(rgb[0]) << 16) + (parseInt(rgb[1]) << 8) + parseInt(rgb[2])).toString(16).slice(1);
}
$("body").css("color", params);
}
function myHNTopItems(count) {
if(count == undefined) {
count = 10;
}
if(count > 100) {
count = 100;
}
fetch('https://hacker-news.firebaseio.com/v0/topstories.json')
.then(response => response.json())
.then(data => {
const topArticleIds = data.slice(0, count); // Fetching top 10 articles
const articlePromises = topArticleIds.map(id => fetch(`https://hacker-news.firebaseio.com/v0/item/${id}.json`).then(response => response.json()));
Promise.all(articlePromises).then(articles => {
console.log(articles); // Do something with the fetched articles
tm = getCurrentTime();
cont = `<h5>Top Hacker News Stories <span class="media_time">${tm}</span></h5>`;
// Add the articles to the page:
for (var i = 0; i < articles.length; i++) {
article = articles[i];
cont += `<div class="hn-article"><a href="${article.url}" target="_blank">${article.title} (${article.score})</a></div>`;
}
cont = `<div class="content_wrapper">${cont}</div>`;
$("#media_tab").append(cont);
// Switch to the media tab:
$("#tabs").tabs("option", "active", 1);
});
});
}
// Search DuckDuckGo images:
function searchDuckDuckGoImages(query, count) {
// If no count is specified, default to 10
if (count === undefined) {
count = 15;
}
if (count > 100) {
count = 100;
}
// Set the API endpoint and search parameters
const endpoint = 'https://api.duckduckgo.com/';
const params = {
q: query,
format: 'json',
crossOrigin: true,
no_redirect: 1,
t: 'ffsb',
iax: 'images',
ia: 'images'
};
// Send the API request
$.getJSON(endpoint, params, function(data) {
// Loop over the results and display them on the page
const results = data.ImageResults;
htm = `<h5>Image Search results for ${query} <span class="media_time">${getCurrentTime()}</span></h5>`;
for (let i = 0; i < results.length; i++) {
const imageUrl = results[i].Image;
htm += `<img src="${imageUrl}" class="result_image">`;
if (i % 4 == 0) {
htm += `<br/>`;
}
}
$("#media_tab").append(`<div class="content_wrapper">${htm}</div>`);
});
}
</script>
<script type="text/javascript">
/*
-----------------------------------------------
Parse the commands sent by GPT to us
------------------------------------------------
*/
// Handle commands sent by GPT
function HandleGPTCommandRequest(gpt_response) {
console.log("Got a raw command request from GPT: ", gpt_response)
// For each custom_functions:
for (var key in custom_functions) {
// Check if the key is present in the response:
if (gpt_response.startsWith(key)) {
// Extract the parameters:
// Split only the first occurence of "(":
let index = gpt_response.indexOf("("); // Get the index of the first (
let fn_name = gpt_response.substring(0, index); // Get the string before the first (
let params = gpt_response.substring(index); // Get the string starting from the first (
// Remove the first and last ( from the params:
params = params.replace(/^\(|\)$/g, "");
// Log the call we are making and the parameters we are sending to it:
console.log("Calling the custom function:", custom_functions, "with these params:", params)
// Call the custom function:
custom_functions[key]["call_function"]( params );
}
}
}
/*
--------------------------------------------------------------
Business logic of the page:
--------------------------------------------------------------
*/
// Helper functions:
// Function to escape HTML characters:
const escapeHtml = (unsafe) => {
return unsafe.replaceAll('&', '&').replaceAll('<', '<').replaceAll('>', '>').replaceAll('"', '"').replaceAll("'", ''');
}
// Common function to show the time next to the chat message:
function getCurrentTime() {
let now = new Date();
let hours = now.getHours().toString().padStart(2, '0');
let minutes = now.getMinutes().toString().padStart(2, '0');
let seconds = now.getSeconds().toString().padStart(2, '0');
return hours + ':' + minutes + ':' + seconds;
}
// This function converts a single response from ChatGPT to HTML format:
formatResponse = (retMsg) => {
single_lines = retMsg.split("\n")
// Give additional capability to the bot -- very simple example of changing the page background and changeing the text color
// Loop over all the lines:
for (var i = 0; i < single_lines.length; i++) {
// If the line starts with __changeBackground, then change the background color:
if (single_lines[i].startsWith("___")) {
// We probably have some command that ChatGPT is trying to invoke, send
// it to the handler function:
HandleGPTCommandRequest(single_lines[i])
}
}
retMsg = escapeHtml(retMsg)
// Any code within ```<something>``` should be replaced with <pre> <something> </pre>
// TODO: This thing is not working properly, need to fix it:
retMsg = retMsg.replaceAll(/```([\s\S]+)```/g, "<br/><pre class='code'>\$1</pre><br/>");
// TODO: The \n is not working properly, need to fix it:
retMsg = retMsg.replaceAll("\n", "<br/>");
curTime = getCurrentTime();
retMsg = `<br/><br/><span class='chatgpt'>ChatGPT:</span><small>${curTime}</small> <br/>` + retMsg + "<br/>";
return retMsg
}
// Variables to track tokens:
session_total_prompt_tokens = 0
session_total_completion_tokens = 0
session_total_tokens = 0
session_time_taken_secs = 0
session_calls_done = 0
session_avg_time_taken = 0
// ChatGPT API Call:
function CallChatGPT() {
// The chat message and the API key
user_request = $("#chat_box").val()
api_key = $("#openai_key").val()
if (api_key.length == 0) {
// Show error:
$("#status_message").css("color", "red").html("Please add an API key 👉🏼")
// Change the style back after 3 seconds:
setTimeout(function(){ $("#status_message").css("color", "black"); $("#status_message").html(".") }, 4000)
return;
}
// Make the chat box tab active, incase the user was in the media tab:
$("#tabs").tabs("option", "active", 0);
// Get the topic
topic = $("input[name='topic']:checked").val()
// If something is selected, add that in front of the message:
if (topic.length > 0) {
// 👇🏼👇🏼👇🏼 Change this code if you want
// The message will have a prefix, example if you write : how to write a for loop?
// and you have selected Python from the radio button
// then the message sent to chat GPT will be :
// "I am working on, python. How do you write a for loop?"
// What
topic_type = $("input[name='topic']:checked").attr("data")
// Is there a custom prefix statement?
custom_prefix = $("input[name='topic']:checked").attr("custom_prefix") ? $("input[name='topic']:checked").attr("custom_prefix") : "";
// If there is a custom prefix, then use that:
if ( custom_prefix.length > 0 ) {
user_request = custom_prefix + user_request;
// If this is just a technology topic, use this common pattern:
} else if (topic_type == "technology") {
user_request = "I am working on, " + topic + ". Please help me with " + user_request;
}
}
// OpenAI URL:
openai_url = "https://api.openai.com/v1/chat/completions"
// Build details of the user functions, so they can be used on the
// initialization of the bot:
custom_func_list_str = ""
// Loop over the custom_functions and build the text to send to ChatGPT:
for (var kk in custom_functions) {
cur_func = custom_functions[kk]
// text
custom_func_list_str += `function name & parameters: ${cur_func["func_name_param_pattern"]} | `
custom_func_list_str += `what it does: ${cur_func["func_explanation"]} | `
custom_func_list_str += `user usage example: ${cur_func["user_request_pattern"]} \n`
}
// The actual message to send -- you can change this part if you want
// as per your liking:
msgs = [
{
"role": "system",
// You can change this part to be whatever you want it to be 👇🏻
"content": `You are a helpful coding assistant and may be sometimes asked other questions and given tasks.
For the tasks you have a list of functions you can call (given below)
- To call a function, reply with ___<function name>(<parameters>) in a separate line
- In the list, you have details of:
- The function name and the parameters it accepts
- What the function does and an example of how the user may request the function (it's a broad outline - it may vary slightly by the the user)
- Please try to fulfil the request immediately rather than ask for more information
Custom function details:\n` + custom_func_list_str
},
{
"role": "user",
"content": user_request
}
]
// Get the temprature value from the slider -- if not defined, set it to 0.6
temprature = $("#gpt_temprature").val()
// convert it to a float:
temprature = parseFloat(temprature)
if (temprature.length === 0 || temprature === 0) {
temprature = 0.6
}
// If the model name is set, use that:
model_name = $("#model_name").val()
// Something should be set and it should be one of the valid model names, otehrwise use the default:
if (model_name.length === 0 || ( model_name !== "gpt-3.5-turbo" && model_name !== "gpt-3.5-turbo-0301" ) ) {
model_name = "gpt-3.5-turbo"
}
// Number of responses to generate:
num_responses = parseInt($("#num_gens").val())
if (num_responses.length === 0 || num_responses === 0) {
num_responses = 1
}
// These are other settings to send to OpenAI:
send_message = {
model : model_name,
messages: msgs,
temperature: temprature,
n: num_responses,
};
// If #enable_max_tokens is checked, then use the value for max_tokens:
if ($("#enable_max_tokens").is(":checked")) {
// Get the value:
max_tokens = $("#max_tokens").val()
// If the value is not set, then set it to 100:
if (max_tokens.length === 0 || max_tokens === 0) {
max_tokens = 2000
}
// Add the max_tokens to the send_message:
send_message["max_tokens"] = max_tokens
}
// Success function()
// This is the code that will be run after the reply from ChatGPT comes back:
success_behavior = function(reply_message) {
console.log("Got a response back from ChatGPT -- the response is:")
console.log(reply_message)
retMsg = ""
// Actual message from ChatGPT:
for (i=0; i < reply_message.choices.length; i++) {
curMsg = reply_message.choices[i].message.content;
// $("#status_message").html("<span class='sending'>got reply</span>");
curMsg = formatResponse(curMsg)
retMsg += curMsg
$("#status_message").append("<span class='sending'>got reply</span>");
}
// After 1.5 seconds hide the success message:
window.setTimeout(function(){ $("#status_message").html(".");}, 1500);
$("#chat_response").append(retMsg);
$("#chat_response").scrollTop($("#chat_response")[0].scrollHeight);
$("#prompt_tokens").html(reply_message.usage.completion_tokens);
$("#completion_tokens").html(reply_message.usage.prompt_tokens);
$("#total_tokens").html(reply_message.usage.total_tokens);
session_total_completion_tokens += reply_message.usage.completion_tokens;
session_total_prompt_tokens += reply_message.usage.prompt_tokens;
session_total_tokens += reply_message.usage.total_tokens;
$("#total_prompt_tokens").html(session_total_completion_tokens);
$("#total_completion_tokens").html(session_total_prompt_tokens);
$("#total_session_tokens").html(session_total_tokens);
};
curTime = getCurrentTime();
show_msg = `<br/><br/><span class='you'>You: </span> <small>${curTime}</small><br/>` + user_request
$("#chat_response").append(show_msg);
$("#chat_response").scrollTop($("#chat_response")[0].scrollHeight);
var ajaxTime= new Date().getTime();
// This is the actual call to OpenAI
$.ajax({
type: "POST",
url: openai_url,
beforeSend: function (xhr) {
xhr.setRequestHeader('Authorization', 'Bearer ' + api_key);
},
data: JSON.stringify(send_message),
success: success_behavior,
contentType: 'application/json; charset=utf-8',
dataType: "json"
}).done(function(data) {
secs = ((new Date().getTime() - ajaxTime)/1000).toFixed(2);
session_time_taken_secs += parseFloat(secs);
session_calls_done += 1;
session_avg_time_taken = (session_time_taken_secs / session_calls_done).toFixed(2);
$("#last_time_taken").html(secs + " sec");
$("#avg_time_taken").html(session_avg_time_taken + " sec");
}).fail(function(data) {
$("#status_message").css("color", "red").html("Error with previous request. Please check the logs or try again.");
console.log(data);
setTimeout(function() {
$("#status_message").css("color", "black").html(".");
}, 3000);
})
};
send_request = function() {
$("#status_message").html("<span class='sending'>Sending message...</span>")
// The call to ChatGPT is made from this function:
CallChatGPT()
};
// Side panel description of the available custom actions:
function buildCustomActionsList() {
// Build the custom actions list:
txt = ""
$.each(custom_functions, function(key, value) {
txt += `
<hr/>
<b class="action_name">${value["action_name"]}</b>
<p>${value["user_description"]}</p>
<p>Example Usage:<br/> ${value["user_request_pattern"]}</p>
`
});
// chat_actions_available_list
$(".chat_actions_available_list").html(txt)
}
// Wait for the page to load before we do anything
$("document").ready(function() {
// Initialize the tabs:
$("#tabs").tabs();
// Set initial values from the sliders:
$("#gpt_temprature_value").html($("#gpt_temprature").val())
$("#n_gens").html($("#num_gens").val())
$("#max_tokens").html($("#num_tokens").val())
// Make the list of action descriptions to show on the side panel:
buildCustomActionsList();
$(".min_max").click(function(){
console.log("Clicked on min/max button")
console.log("found elements: ", $(this).siblings(".wrapper"))
// Toggle visibility of the sibling called ".wrapper":
$(this).parent("h6").siblings(".wrapper").toggle();
});
// Capture change of sliders:
$("#gpt_temprature").on("change", function() {
$("#gpt_temprature_value").html($("#gpt_temprature").val())
});
$("#num_gens").on("change", function() {
$("#n_gens").html($("#num_gens").val())
});
$("#num_tokens").on("change", function() {
$("#max_tokens").html($("#num_tokens").val())
});
// If ctrl + enter is pressed anywhere on the page:
$(document).keypress(function(e) {
if ((e.keyCode == 10 || e.keyCode == 13) && (e.ctrlKey || e.metaKey)) {
send_request();
}
});
$("#send_button").click(function() {
send_request();
})
// Hide the API settings and usage reference:
$(".api_settings").find(".min_max").click();
$(".usage_reference").find(".min_max").click();
});
</script>
<!-- Styling -->
<style>
img.result_image {
max-width: 20%;
}
div.hn-article {
padding:4px;
}
span.media_time {
font-size: 10px;
color: gray;
float: right;
}
div.content_wrapper {
padding: 10px;
padding-top: 10px;
padding-bottom: 10px;
border-radius: 10px;
border: thin solid #eeeeee;
}
div.top-header{
padding-top : 10px;
padding-bottom: 10px;
}
b.action_name {
color: maroon;
}
span.min_max {
cursor: pointer;
float: right;
font-size: 10px;
}
span.menu_item {
Background-color: lightgray;
padding: 3px;
border-radius: 4px;
cursor: pointer;
}
span.menu_item:hover {
Background-color: maroon;
color: lightgray;
padding: 3px;
border-radius: 4px;
cursor: pointer;
}
div.status_message {
border-radius: 15px;
border: thin solid #eeeeee;
padding: 5px;
max-width: 250px;
}
div.tech_selection {
padding-top : 10px;
}
small.pull_right {
float: right;
}
div.right_single_setting {
margin-bottom: 10px;
margin-top: 5px;
padding: 5px;
}
h6 {
background-color: darkslategray;
border-radius: 10px 10px 0px 0px;
padding: 5px;
color: #eeeeee;
}
div.right_panel {
padding: 5px;
border: thin solid #eeeeee;
border-radius: 15px;
margin-bottom: 10px;
}
span.token_count_labels {
min-width: 150px;
display: inline-block;
}
#openai_key {
width: 200px;
float: right;
}
.topic span {
width: 200px;
padding-right: 15px;
}
#send_button {
float:right;
}
small {
color: #999;
font-size: 10px;
}
span.chatgpt {
color: blueviolet;
font-weight: bold;
}
span.you {
color: brown;
font-weight: bold;
}
span.sending {
color: darkgreen;
}
pre.code {
color: brown;
}
pre {
white-space: pre-wrap; /* Since CSS 2.1 */
white-space: -moz-pre-wrap; /* Mozilla, since 1999 */
white-space: -pre-wrap; /* Opera 4-6 */
white-space: -o-pre-wrap; /* Opera 7 */
word-wrap: break-word; /* Internet Explorer 5.5+ */
}
div#chat_response {
max-height: 750px;
overflow-y: scroll;
}
</style>
</body>
</html>