-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.R
1430 lines (1247 loc) · 39.5 KB
/
server.R
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
source("global.R")
source("testing.R")
############################## APP ###################################################################
# Define server logic required to draw a histogram
#' The application server-side
#'
#' @param input,output,session Internal parameters for {shiny}.
#' DO NOT REMOVE.
#' @import shiny
#' @noRd
app_server <- function(input, output, session) {
#____________________________________________________________________________
# 1. General UI, observers, etc.
#____________________________________________________________________________
# increase max input file size
options(shiny.maxRequestSize = 10 * 1024^2) # 10MB
pdf(NULL) #otherwise, base R plots sometimes do not show.
# load demo data when clicked
observeEvent(input$demo_prompt, {
req(input$select_data)
if (input$demo_prompt != demos_mpg[1]) {
updateTextInput(
session,
"input_text",
value = input$demo_prompt
)
} else { # if not mpg data, reset
updateTextInput(
session,
"input_text",
value = "",
placeholder =
"Upload a file or use demo data. Then just ask questions or request analyses in plain English. For general questions, briefly explain the data first, especially the relevant columns. See examples above. If unsuccessful, try again with the same request or ask differently. Code works correctly some of the time. To use voice input, click Settings."
)
}
})
observeEvent(input$user_file, {
updateSelectInput(
session,
"select_data",
selected = uploaded_data
)
}, ignoreInit = TRUE, once = TRUE)
observe({
shinyjs::hideElement(id = "load_message")
})
#____________________________________________________________________________
# 2. Voice narration
#____________________________________________________________________________
# had to use this. Otherwise, the checkbox returns to false
# when the popup is closed and opened again.
use_voice <- reactive({
use_voice <- FALSE #default
tem <- is.null(input$use_voice_button)
if(!is.null(input$use_voice)) {
use_voice <- input$use_voice
}
return(use_voice)
})
# Use voice input?
# output$use_heyshiny <- renderUI({
# req(use_voice())
# tagList(
# heyshiny::useHeyshiny(language = "en-US"), # configure the heyshiny
# heyshiny::speechInput(
# inputId = "hey_cmd",
# command = "hey cox *msg" # hey cox is more sensitive than 'hi bot'
# ), # set the input
# )
# })
# read the speech input
observeEvent(input$hey_cmd, {
speech <- input$hey_cmd
# message(speech)
showNotification(speech)
if (input$tabs == "Home") {
if (grepl("^continue", speech)) {
speech <- paste0(
input$input_text, # current prompt
". ", # add . and space.
gsub("^continue", "", speech) # remove the continue
)
}
updateTextInput(
session,
"input_text",
value = speech
)
} else if (input$tabs == "Ask") {
speech <- paste0(
input$input_text, # current prompt
". ", # add . and space.
gsub("^continue", "", speech) # remove the continue
)
updateTextInput(
session,
"ask_question",
value = speech
)
}
})
#____________________________________________________________________________
# 3. Loading data
#____________________________________________________________________________
# uploaded data
user_data <- reactive({
req(input$user_file)
in_file <- input$user_file
in_file <- in_file$datapath
req(!is.null(in_file))
isolate({
file_type <- "read_excel"
# Excel file ---------------
if(grepl("xls$|xlsx$", in_file, ignore.case = TRUE)) {
df <- readxl::read_excel(in_file)
df <- as.data.frame(df)
} else {
#CSV --------------------
df <- read.csv(in_file)
file_type <- "read.csv"
# Tab-delimited file ----------
if (ncol(df) == 2) {
df <- read.table(
in_file,
sep = "\t",
header = TRUE
)
file_type <- "read.table"
}
}
# clean column names
df <- df %>% janitor::clean_names()
return(
list(
df = df,
file_type = file_type
)
)
})
})
# showing the current dataset. Warning if no data is uploaded.
output$selected_dataset <- renderText({
req(input$submit_button)
# when submit is clicked, but no data is uploaded.
if(input$select_data == uploaded_data) {
if(is.null(input$user_file)) {
txt <- "No file uploaded! Please Reset and upload your data first."
} else {
txt <- "Dataset: uploaded."
}
} else {
txt <- paste0("Dataset: ", input$select_data)
}
return(txt)
})
output$data_upload_ui <- renderUI({
# Hide this input box after the first run.
req(input$submit_button == 0)
fileInput(
inputId = "user_file",
label = "File Upload",
accept = c(
"text/csv",
"text/comma-separated-values",
"text/tab-separated-values",
"text/plain",
".csv",
".tsv",
".txt",
".xls",
".xlsx"
)
)
})
output$demo_data_ui <- renderUI({
# Hide this input box after the first run.
req(input$submit_button == 0)
selectInput(
inputId = "select_data",
label = "Data",
choices = datasets,
selected = "attitude",
multiple = FALSE,
selectize = FALSE
)
})
output$prompt_ui <- renderUI({
req(input$select_data)
# hide after data is uploaded
req(is.null(input$user_file))
if (input$select_data == "mpg") {
selectInput(
inputId = "demo_prompt",
choices = demos_mpg,
label = "Example requests:"
)
} else if (input$select_data == no_data) {
selectInput(
inputId = "demo_prompt",
choices = demos_no_data,
label = "Example requests:"
)
} else if (input$select_data == "diamonds") {
selectInput(
inputId = "demo_prompt",
choices = demos_diamond,
label = "Example requests:"
)
} else if (input$select_data == rna_seq) {
selectInput(
inputId = "demo_prompt",
choices = demos_rna_seq,
label = "Example requests:"
)
}
else {
return(NULL)
}
})
#____________________________________________________________________________
# 4. API key management
#____________________________________________________________________________
# pop up modal for Settings
observeEvent(input$api_button, {
shiny::showModal(
shiny::modalDialog(
size = "l", easyClose=TRUE,
footer = modalButton("Confirm"),
tagList(
fluidRow(
column(
width = 4,
sliderInput(
inputId = "temperature",
label = "Sampling temperature",
min = 0,
max = 1,
value = sample_temp(),
step = .1,
round = FALSE,
width = "100%"
)
),
column(
width = 8,
p("This important parameter controls the AI's behavior in choosing
among possible answers. A higher sampling temperature tells the AI
to take more risks, producing more diverse and creative
solutions when the same request is repeated. A lower temperature
(such as 0) results in more conservative and well-defined solutions,
but less variety when repeated.
"),
)
),
hr(),
h4("Use your own API key"),
h5("We pay a small fee to use the AI for every request.
If you use this AI Bot regularly,
please take a few minutes to create your own API key: "),
tags$ul(
tags$li(
"Create a personal account at",
a(
"OpenAI.",
href = "https://openai.com/api/",
target = "_blank"
)
),
tags$li("After logging in, click \"Personal\" from top right."),
tags$li(
"Click \"Manage Account\" and then \"Billing\",
where you can add \"Payment methods\" and set \"Usage
limits\". $5 per month is more than enough."
),
tags$li(
"Click \"API keys\" to create a new key,
which can be copied and pasted below."
),
),
textInput(
inputId = "api_key_openAI",
label = h5("Paste your API key from OpenAI:"),
value = NULL,
placeholder = "sk-..... (51 characters)"
),
textInput(
inputId = "api_key_gemini",
label = h5("Paste your API key from Google Gemini:"),
value = NULL,
placeholder = "..... (39 characters)"
),
uiOutput("valid_key"),
uiOutput("save_api_ui"),
verbatimTextOutput("session_api_source_openAI"),
verbatimTextOutput("session_api_source_gemini"),
hr(),
fluidRow(
column(
width = 6,
checkboxInput(
inputId = "use_voice",
label = strong("Enable voice narration"),
value = use_voice()
)
),
column(
width = 6,
# this causes the use_voice() to refresh twice,
# triggering the permission seeking in Chrome.
# Don't know why, but this works. I'm a stable genius.
actionButton("use_voice_button", strong("Seek mic permission"))
)
),
h5("First select the checkbox and then seek
permission to use the microphone. Your browser should have a popup
window. Otherwise, check the both ends of the URL bar for a
blocked icon, which
could be clicked to grant permission. If successful, you will see
a red dot on top of the tab in Chrome.
Voice narration can be used in both the Main and the
Ask Me Anything tabs by just saying \"Hey Cox ...\"
in honor of the statistician David Cox.
If not satisfied, try again to overwrite.
To continue, say \"Hey Cox Continue ...\""),
),
hr(),
fluidRow(
column(
width = 4,
checkboxInput(
inputId = "numeric_as_factor",
label = strong("Treat as factors"),
value = convert_to_factor()
),
tippy::tippy_this(
elementId = "numeric_as_factor",
tooltip = "Treat the columns that looks like a category
as a category. This applies to columns that contain numbers
but have very few unique values. ",
theme = "light-border"
)
),
column(
width = 4,
numericInput(
inputId = "max_levels_factor",
label = "Max levels",
value = max_levels_factor(),
min = 5,
max = 50,
step = 1
),
tippy::tippy_this(
elementId = "max_levels_factor",
tooltip = "To convert a numeric column as category,
the column must have no more than this number of unique values.",
theme = "light-border"
)
),
column(
width = 4,
numericInput(
inputId = "max_proptortion_factor",
label = "Max proportion",
value = max_proptortion_factor(),
min = 0.05,
max = 0.5,
step = 0.1
),
tippy::tippy_this(
elementId = "max_proptortion_factor",
tooltip = "To convert a numeric column as category,
the number of unique values in a column must not exceed
more this proportion of the total number of rows.",
theme = "light-border"
)
)
),
h5("Some columns contains numbers but should be treated
as categorical values or factors. For example, we sometimes
use 1 to label success and 0 for failure.
If this is selected, using the default setting, a column
is treated as categories when the number of unique values
is less than or equal to 12, and less than 10% of the total rows."
),
hr(),
fluidRow(
column(
width = 4,
checkboxInput(
inputId = "contribute_data",
label = "Help us enhance AI Bot",
value = contribute_data()
)
),
column(
width = 8,
h5("Save your requests and the structure of your data
such as column names and data types, not the data itself.
We can learn from users about creative ways to use AI.
And we can try to improve unsuccessful attempts. ")
)
),
)
)
})
# api key for the session
api_key_session <- reactive({
api_key_openAI <- api_key_global_openAI
api_key_gemini <- api_key_global_gemini
session_key_source <- key_source
if(!is.null(input$api_key_openAI)) {
key1 <- input$api_key_openAI
key1 <- clean_api_key(key1)
if (validate_api_key_openAI(key1)) {
api_key_openAI <- key1
session_key_source <- "pasted!"
}
}
if(!is.null(input$api_key_gemini)){
key2 <- input$api_key_gemini
if(validate_api_key_gemini(key2)){
api_key_gemini <- key2
session_key_source <- "pasted!"
}
}
return(
list(
api_key_openAI = api_key_openAI,
api_key_gemini = api_key_gemini,
key_source = session_key_source
)
)
})
output$session_api_source_openAI <- renderText({
txt <- api_key_session()$api_key_openAI
# The following is essential for correctly getting the
# environment variable on Linux
tem <- Sys.getenv("OPEN_API_KEY")
paste0(
"Current OpenAI API key: ",
substr(txt, 1, 4),
".....",
substr(txt, nchar(txt) - 4, nchar(txt)),
" (",
api_key_session()$key_source,
")"
)
})
output$session_api_source_gemini <- renderText({
txt <- api_key_session()$api_key_gemini
paste0(
"Current Gemini API key: ",
substr(txt, 1, 4),
".....",
substr(txt, nchar(txt) - 4, nchar(txt)),
" (",
api_key_session()$key_source,
")"
)
})
output$save_api_ui <- renderUI({
req(input$api_key_openAI)
# only show this when running locally.
req(!file.exists(on_server))
req(validate_api_key_openAI(input$api_key_openAI))
tagList(
actionButton(
inputId = "save_api_button",
label = "Save key file for next time."
),
tippy::tippy_this(
elementId = "save_api_button",
tooltip = "Save to a local file,
so that you do not have to copy and paste next time.",
theme = "light-border"
)
)
})
output$valid_key <- renderUI({
req(input$api_key_openAI)
if(validate_api_key_openAI(input$api_key_openAI)) {
h4(
"Key looks good. Just close this window.",
style = "color:blue"
)
} else {
h4(
"That does not look like a valid key!",
style = "color:red"
)
}
})
# only save the key, if the app is running locally.
observeEvent(input$save_api_button, {
req(input$save_api_button)
req(input$api_key_openAI)
writeLines(input$api_key_openAI, "api_key_openAI.txt")
writeLines(input$api_key_gemini, "api_key_gemini.txt")
})
# only save the key, if the app is running locally.
observeEvent(input$submit_button, {
# if too short, do not send.
if (nchar(input$input_text) < min_query_length) {
showNotification(
paste(
"Request is too short! Should be more than ",
min_query_length,
" characters."
),
duration = 10
)
}
# if too short, do not send.
if (nchar(input$input_text) > max_query_length) {
showNotification(
paste(
"Request is too long! Should be less than ",
max_query_length,
" characters."
),
duration = 10
)
}
})
#____________________________________________________________________________
# 5. Send API Request, handle API errors
#____________________________________________________________________________
sample_temp <- reactive({
temperature <- default_temperature #default
if (!is.null(input$temperature)) {
temperature <- input$temperature
}
return(temperature)
})
openAI_prompt <- reactive({
req(input$submit_button)
req(input$select_data)
prep_input(input$input_text, input$select_data, current_data())
})
openAI_response <- reactive({
req(input$submit_button)
isolate({ # so that it will not respond to text, until submitted
req(input$input_text)
prepared_request <- openAI_prompt()
req(prepared_request)
# when submit is clicked, but no data is uploaded.
if(input$select_data == uploaded_data) {
req(user_data())
}
shinybusy::show_modal_spinner(
spin = "semipolar",
text = paste0("... Please wait, processing ...\n",
prepared_request # sample(jokes, 1)
),
color = "#000000"
)
start_time <- Sys.time()
#START HERE#
#print(prepared_request)
#print(api_key_session()$api_key_openAI)
chat <- function(input_message){
user_input <- list(list(role = "user", content = input_message))
base_url <- "https://api.openai.com/v1/chat/completions"
api_key_openAI <- api_key_session()$api_key_openAI
body <- list(model = language_model,
messages = user_input,
max_tokens = 200,
temperature = sample_temp())
req <- request(base_url)
resp <-
req |>
req_auth_bearer_token(token = api_key_openAI) |>
req_headers("Content-Type" = "application/json") |>
req_body_json(body) |>
req_retry(max_tries = 4) |>
req_throttle(rate = 15) |>
req_perform()
openai_chat_response <- resp |> resp_body_json(simplifyVector = TRUE)
#print(openai_chat_response) #shows more details of the result
#print(openai_chat_response$choices$message$content)
return(openai_chat_response)
}
#response <- chat(prepared_request)
#print(response)
#print(response$choices$message$content) #actual result
# Send to openAI
tryCatch(
response <- chat(prepared_request),
error = function(e) {
# remove spinner, show message for 5s, & reload
shinybusy::remove_modal_spinner()
shiny::showModal(api_error_modal)
Sys.sleep(8)
session$reload()
list(
error_value = -1,
message = capture.output(print(e$message)),
error_status = TRUE
)
}
)
error_api <- FALSE
# if error returns true, otherwise
# that slot does not exist, returning false.
# or be NULL
error_api <- tryCatch(
!is.null(response$error_status),
error = function(e) {
return(TRUE)
}
)
error_message <- NULL
if(error_api) {
cmd <- NULL
response <- NULL
error_message <- response$message
} else {
cmd <- response$choices$message$content
}
api_time <- difftime(
Sys.time(),
start_time,
units = "secs"
)[[1]]
if(0) {
# if more than 10 requests, slow down. Only on the server.
if(counter$requests > 20 && file.exists(on_server)) {
Sys.sleep(counter$requests / 5 + runif(1, 0, 5))
}
if(counter$requests > 50 && file.exists(on_server)) {
Sys.sleep(counter$requests / 10 + runif(1, 0, 10))
}
}
if(counter$requests > 100 && file.exists(on_server)) {
Sys.sleep(counter$requests / 40 + runif(1, 0, 40))
}
shinybusy::remove_modal_spinner()
# update usage via global reactive value
counter$tokens <- counter$tokens + response$usage$completion_tokens
counter$requests <- counter$requests + 1
counter$time <- round(api_time, 0)
counter$tokens_current <- response$usage$completion_tokens
return(
list(
cmd = cmd,
response = response,
time = round(api_time, 0),
error = error_api,
error_message = error_message
)
)
})
})
# a modal shows api connection error
api_error_modal <- shiny::modalDialog(
title = "API connection error!",
# tags$h4(response$message, style = "color:red"),
tags$h4("Is the API key is correct?", style = "color:red"),
tags$h4("How about the WiFi?", style = "color:red"),
tags$h4("Maybe the openAI.com website is taking forever to respond.", style = "color:red"),
tags$h5("If you keep having trouble, send us an email.", style = "color:red"),
tags$h4(
"Auto-reset ...",
style = "color:blue; text-align:right"
),
easyClose = TRUE,
size = "s"
)
# show a warning message when reached 10c, 20c, 30c ...
observeEvent(input$submit_button, {
req(file.exists(on_server))
req(!openAI_response()$error)
cost_session <- round(counter$tokens * 2e-3, 0)
if (cost_session %% 20 == 0 & cost_session != 0) {
shiny::showModal(
shiny::modalDialog(
size = "s",
easyClose = TRUE,
h4(
paste0(
"Cumulative API Cost reached ",
cost_session,
"¢"
)
),
h4("Slow down. Please try to use your own API key.")
)
)
}
})
output$openAI <- renderText({
req(openAI_response()$cmd)
res <- logs$raw
# Replace multiple newlines with just one.
#res <- gsub("\n+", "\n", res)
# Replace empty lines, [ ]{0, }--> zero or more space
#res <- gsub("^[ ]{0, }\n", "", res)
res <- gsub("```", "", res)
})
# Defining & initializing the reactiveValues object
logs <- reactiveValues(
id = 0, # 1, 2, 3, id for code chunk
code = "", # cumulative code
raw = "", # cumulative original code for print out
last_code = "", # last code for Rmarkdown
code_history = list() # keep all code chunks
)
observeEvent(input$submit_button, {
logs$id <- logs$id + 1
# if not continue
if(!input$continue) {
logs$code <- openAI_response()$cmd
logs$raw <- openAI_response()$response$choices$message$content
# remove one or more blank lines in the beginning.
logs$raw <- gsub("^\n+", "", logs$raw)
logs$last_code <- ""
} else { # if continue
logs$last_code <- logs$code # last code
logs$code <- paste(
logs$code,
"\n",
"#-------------------------------",
openAI_response()$cmd
)
logs$raw <- paste(
logs$raw,
"\n\n#-------------------------\n",
gsub("^\n+", "", openAI_response()$response$choices[1, 1])
)
}
# A list holds current request
current_code <- list(
id = logs$id,
code = logs$code,
raw = logs$raw, # for print
prompt = input$input_text,
error = code_error(),
rmd = Rmd_chunk()
)
logs$code_history <- append(logs$code_history, list(current_code))
choices <- 1:length(logs$code_history)
names(choices) <- paste0("Chunk #", choices)
# update chunk choices
updateSelectInput(
inputId = "selected_chunk",
label = "AI generated code:",
choices = choices,
selected = logs$id
)
# turn off continue button
updateCheckboxInput(
session = session,
inputId = "continue",
label = "Continue from this chunk",
value = FALSE
)
})
# change code when past code is selected.
observeEvent(input$selected_chunk, {
#req(run_result())
id <- as.integer(input$selected_chunk)
logs$code <- logs$code_history[[id]]$code
logs$raw <- logs$code_history[[id]]$raw
updateTextInput(
session,
"input_text",
value = logs$code_history[[id]]$prompt
)
})
output$usage <- renderText({
req(input$submit_button != 0 || input$ask_button != 0)
paste0(
"R",
counter$requests, ": ",
counter$tokens_current,
" tokens, ",
counter$time,
" second(s)"
)
})
output$total_cost <- renderText({
if(input$submit_button == 0 & input$ask_button == 0) {
return("The generative-AI Bot uses OpenAI, which charges 2¢ per 1000 tokens/words
from user's accounts. Non-UMich users
should use your own accounts by entering their KEYs in the \'Settings\'.")
} else {
#req(openAI_response()$cmd)
paste0(
"Cumulative API Cost: ",
sprintf("%5.1f", counter$tokens * 2e-3),
"¢"
)
}
})
output$temperature <- renderText({
req(openAI_response()$cmd)
paste0(
"Temperature: ",
sample_temp()
)
})
output$retry_on_error <- renderText({
req(code_error())
if(code_error()) {
"Error! Try again or change the request."
}
})
# Defining & initializing the reactiveValues object
counter <- reactiveValues(
tokens = 0, # cumulative tokens
requests = 0, # cumulative requests
tokens_current = 0, # tokens for current query
time = 0 # response time for current
)
#____________________________________________________________________________
# 6. Run the code, shows plots, code, and errors
#____________________________________________________________________________
# stores the results after running the generated code.
# return error indicator and message
# Note that the code is run three times!!!!!
# Sometimes returns NULL, even when code runs fine. Especially when
# a base R plot is generated.
run_result <- reactive({
req(logs$code)
req(input$submit_button != 0)
withProgress(message = "Running the code ...", {
incProgress(0.4)
tryCatch(
eval(
parse(
text = clean_cmd(
logs$code,
input$select_data
)
)
),
error = function(e) {
list(
error_value = -1,
message = capture.output(print(e$message)),
error_status = TRUE
)
}
)
})
})
# Error when run the generated code?
code_error <- reactive({
error_status <- FALSE
req(input$submit_button != 0)
# if error returns true, otherwise
# that slot does not exist, returning false.
# or be NULL
try( # if you do not 'try', the entire app quits! :-)
if (is.list(run_result())) {
req(!is.null(names(run_result())[1]))
if (names(run_result())[1] == "error_value") {
error_status <- TRUE
}
}
)
return(error_status)
})
output$error_message <- renderUI({
req(!is.null(code_error()))
if(code_error()) {
h4(paste("Error!", run_result()$message), style = "color:red")
} else {
return(NULL)
}
})
# just capture the screen output
output$console_output <- renderText({
req(!code_error())
req(logs$code)
out <- ""
withProgress(message = "Running the code for console...", {
incProgress(0.4)
try(
out <- capture.output(eval(
parse(