/
chatgpt.R
453 lines (437 loc) · 16.2 KB
/
chatgpt.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
####################################################################
#' ChatGPT API Interaction with R
#'
#' This function lets the user ask ChatGPT via its API, and returns
#' the rendered reply. There are a couple of specific verbs (functions) with a
#' preset prompt to help fetch the data in specific formats. We also
#' store the prompts and replies in current session with their respective
#' time-stamps so user can gather historical results.
#'
#' @family API
#' @family ChatGPT
#' @family LLM
#' @inheritParams cache_write
#' @inheritParams db_download
#' @param ask Character. Redacted prompt to ask. If multiple asks are
#' requested, they will be concatenated with "+" into a single request.
#' @param secret_key Character. Secret Key. Get yours in:
#' \href{https://platform.openai.com}{platform.openai.com} for OpenAI or
#' \href{https://makersuite.google.com/app/apikey}{makersuite.google.com}
#' for Gemini.
#' @param url Character. Base API URL.
#' @param model Character. OpenAI model to use. This can be adjusted
#' according to the available models in the OpenAI API (such as "gpt-4").
#' @param temperature Numeric. The temperature to use for generating
#' the response. Default is 0.5. The lower the \code{temperature},
#' the more deterministic the results in the sense that the highest probable
#' next token is always picked. Increasing temperature could lead to more
#' randomness, which encourages more diverse or creative outputs. You are
#' essentially increasing the weights of the other possible tokens.
#' In terms of application, you might want to use a lower temperature value
#' for tasks like fact-based QA to encourage more factual and concise responses.
#' For poem generation or other creative tasks, it might be beneficial to
#' increase the temperature value.
#' @param max_tokens Integer. The maximum number of tokens in the response.
#' @param num_retries Integer. Number of times to retry the request in
#' case of failure. Default is 3.
#' @param pause_base Numeric. The number of seconds to wait between retries.
#' Default is 1.
#' @return (Invisible) list. Content returned from API POST and processed.
#' @examples
#' \dontrun{
#' api_key <- get_credentials()$openai$secret_key
#' # Open question:
#' gpt_ask("Can you write an R function to plot a dummy histogram?", api_key)
#'
#' ##### The following examples return dataframes:
#' # Classify each element based on categories:
#' gpt_classify(1:10, c("odd", "even"))
#'
#' # Add all tags that apply to each element based on tags:
#' gpt_tag(
#' c("I love chocolate", "I hate chocolate", "I like Coke"),
#' c("food", "positive", "negative", "beverage")
#' )
#'
#' # Extract specific information:
#' gpt_extract(
#' c("My mail is 123@@test.com", "30 Main Street, Brooklyn, NY, USA", "+82 2-312-3456", "$1.5M"),
#' c("email", "full state name", "country of phone number", "amount as number")
#' )
#'
#' # Format values
#' gpt_format(
#' c("March 27th, 2021", "12-25-2023 3:45PM", "01.01.2000", "29 Feb 92"),
#' format = "ISO Date getting rid of time stamps"
#' )
#'
#' # Convert temperature units
#' gpt_convert(c("50C", "300K"), "Fahrenheit")
#'
#' # Create a table with data
#' gpt_table("5 random people's address in South America, email, phone, age between 18-30")
#' gpt_table(
#' ask = "5 largest cities, their countries, and population",
#' cols = c("city_name", "where", "POP")
#' )
#'
#' # Translate text to any language
#' gpt_translate(
#' rep("I love you with all my heart", 5),
#' language = c("spanish", "chinese", "japanese", "russian", "german")
#' )
#'
#' # Now let's read the historical prompts, replies, ano more from current session
#' gpt_history()
#' }
#' @export
gpt_ask <- function(ask,
secret_key = get_credentials()$openai$secret_key,
url = Sys.getenv("LARES_GPT_URL"),
model = Sys.getenv("LARES_GPT_MODEL"),
num_retries = 3,
temperature = 0.5,
max_tokens = NULL,
pause_base = 1,
quiet = FALSE, ...) {
ts <- Sys.time()
if (length(ask) > 1) ask <- paste(ask, collapse = " + ")
# Save historical questions
cache <- bind_rows(
data.frame(ts = ts, prompt = ask),
cache_read("GPT_HIST_ASK", quiet = TRUE, ...)) %>%
as_tibble()
cache_write(distinct(cache), "GPT_HIST_ASK", quiet = TRUE, ...)
# Ask ChatGPT using their API
response <- POST(
url = url,
add_headers(Authorization = paste("Bearer", secret_key)),
httr::content_type_json(),
encode = "json",
times = num_retries,
pause_base = pause_base,
body = list(
model = model,
temperature = temperature,
max_tokens = max_tokens,
messages = list(list(
role = "user",
content = ask
))
)
)
ret <- content(response)
if ("error" %in% names(ret)) warning(ret$error$message)
if ("message" %in% names(ret$choices[[1]]) & !quiet) {
cat(paste(stringr::str_trim(ret$choices[[1]]$message$content), "\n"))
}
# Save historical answers
cache <- bind_rows(
data.frame(ts = ts, reply = ret),
cache_read("GPT_HIST_REPLY", quiet = TRUE, ...)) %>%
as_tibble()
cache_write(distinct(cache), "GPT_HIST_REPLY", quiet = TRUE, ...)
return(invisible(ret))
}
#' @rdname gpt_ask
#' @export
gpt_history <- function(quiet = TRUE, ...) {
asks <- cache_read("GPT_HIST_ASK", quiet = quiet, ...)
replies <- cache_read("GPT_HIST_REPLY", quiet = quiet, ...)
if (!is.null(asks)) {
if (!is.null(replies)) {
hist <- left_join(asks, replies, by = "ts") %>%
select(.data$ts, .data$prompt, contains("message.content"), everything())
return(hist)
} else {
return(asks)
}
} else {
message("No historical prompts nor replies registered yet")
return(invisible(NULL))
}
}
#' @param cols Vector. Force column names for your table results.
#' @rdname gpt_ask
#' @export
gpt_table <- function(x, cols = NULL, quiet = TRUE, ...) {
p <- gpt_prompter(instruction = x, output = "table", cols = cols, ...)
resp <- gpt_ask(p$prompt, quiet = quiet, ...)
df <- gpt_markdown2df(resp)
return(df)
}
#' @param x Vector. List items you wish to process in your instruction
#' @param categories,tags Vector. List of possible categories/tags to consider.
#' @rdname gpt_ask
#' @export
gpt_classify <- function(x, categories, quiet = TRUE, ...) {
p <- gpt_prompter(
instruction = paste(
"For each of the inputs,",
"classify using only the options in context"
),
input = x, context = categories,
output = "table",
cols = c("Input", "Category"),
...
)
resp <- gpt_ask(p$prompt, quiet = quiet, ...)
df <- gpt_markdown2df(resp)
return(df)
}
#' @rdname gpt_ask
#' @export
gpt_tag <- function(x, tags, quiet = TRUE, ...) {
p <- gpt_prompter(
instruction = paste(
"For each of the inputs,",
"provide which of the context values apply as correct tags using TRUE/FALSE"
),
input = x, context = tags,
output = "table",
...
)
resp <- gpt_ask(p$prompt, quiet = quiet, ...)
df <- gpt_markdown2df(resp)
return(df)
}
#' @param extract,format,unit Character. Length 1 or same as x to extract/format/unit
#' information from x. For example: email, country of phone number, country, amount as number,
#' currency ISO code, ISO, Fahrenheit, etc.
#' @rdname gpt_ask
#' @export
gpt_extract <- function(x, extract, quiet = TRUE, ...) {
stopifnot(length(extract) %in% c(1, length(x)))
p <- gpt_prompter(
instruction = paste(
"For each of the inputs,",
"extract each of the information asked in context"
),
input = x, context = extract,
output = "table",
cols = c("Input", "Element_to_extract", "Value"),
...
)
resp <- gpt_ask(p$prompt, quiet = quiet, ...)
df <- gpt_markdown2df(resp)
return(df)
}
#' @rdname gpt_ask
#' @export
gpt_format <- function(x, format, quiet = TRUE, ...) {
stopifnot(length(format) %in% c(1, length(x)))
p <- gpt_prompter(
instruction = paste(
"For each of the inputs,",
"standardize and format all values to the format in context"
),
input = x, context = format,
output = "table",
cols = c("Input", "Formatted"),
...
)
resp <- gpt_ask(p$prompt, quiet = quiet, ...)
df <- gpt_markdown2df(resp)
return(df)
}
#' @rdname gpt_ask
#' @export
gpt_convert <- function(x, unit, quiet = TRUE, ...) {
stopifnot(length(unit) %in% c(1, length(x)))
p <- gpt_prompter(
instruction = paste(
"For each of the inputs,",
"provide new converted values using the units in context"
),
input = x, context = unit,
output = "table",
cols = c("Input", "Original_Unit", "Total_Value", "Converted_Value", "New_Unit"),
...
)
resp <- gpt_ask(p$prompt, quiet = quiet, ...)
df <- gpt_markdown2df(resp)
return(df)
}
#' @param language Character. Language to translate to
#' @rdname gpt_ask
#' @export
gpt_translate <- function(x, language, quiet = TRUE, ...) {
stopifnot(length(language) %in% c(1, length(x)))
p <- gpt_prompter(
instruction = paste(
"For each of the inputs,",
"translate to the respective languages provided in context"
),
input = x, context = language,
output = "table",
cols = c("Input", "Language", "Translation"),
...
)
resp <- gpt_ask(p$prompt, quiet = quiet, ...)
df <- gpt_markdown2df(resp)
return(df)
}
gpt_markdown2df <- function(resp) {
if ("message" %in% names(resp$choices[[1]])) {
resp <- resp$choices[[1]]$message$content
}
df <- try(markdown2df(resp))
attr(df, "response") <- df
return(df)
}
# DEPRECATED: Now using the new gpt_prompter()
# gpt_prompter_basic <- function(type = "category", cols = c("item", type), x, y) {
# paste(
# "Return a structured markdown table",
# "with", length(cols), "columns named exactly", v2t(cols, and = "and"),
# ". Consider the following items:", v2t(x, quotes = FALSE),
# ". For each respective item, what", type, "represent each item using:", v2t(y, quotes = FALSE),
# ". If you don't know any item, replace with NA"
# )
# }
### Theoretical elements to build prompts in a standard and cleaner way
# TIP: Start simple and be very specific
####################################################################
#' Structured Prompt Builder for LLM (ChatGPT)
#'
#' Build standard prompts to get the right outcomes using the four theoretical
#' elements required to build standard and cleaner asks: instruction, input, context,
#' and output. Inspired by the
#' \href{https://www.promptingguide.ai/}{Prompt Engineering Guide} free guide.
#' Remember to start simple and be very specific to get exactly what you need.
#'
#' @section Elements of a Prompt:
#' \describe{
#' \item{Instruction}{a specific task or instruction you want the model to perform.
#' It usually starts with a verb given its an instruction.}
#' \item{Input}{input data, elements or question that we are interested to find a response for,}
#' \item{Context}{external information, additional context or references to steer
#' the model to better responses.}
#' \item{Output}{type or format of the output.}
#' }
#'
#' @family ChatGPT
#' @family LLM
#' @param instruction,input,context,output Character or vector.
#' You do not need all the four elements for a prompt and the
#' format depends on the task at hand.
#' @param quiet Boolean. Should the written prompt be printed or not?
#' @param ... Additional parameters. You can pass \code{cols} parameter to
#' explicitly set column names.
#' @return (Invisible) list with written prompt and elements provided.
#' @examples
#' # A simple formatted table with data
#' # Note: I mostly use output = "table" and enabled an auxiliary enrichment prompt
#' (p <- gpt_prompter(instruction = "Capitals of the world", output = "table"))
#'
#' # Classify
#' p <- gpt_prompter(
#' instruction = "For each of the inputs, classify using only the options in context",
#' input = c("Molecule", "Elephant", "Milky Way", "Cat", "Planet Earth"),
#' context = c("Big", "Medium", "Small"),
#' output = "table",
#' # This cols parameter is auxiliary
#' cols = c("Input", "Category"),
#' quiet = FALSE)
#'
#' # Tag all categories that apply
#' p <- gpt_prompter(
#' instruction = paste("For each of the inputs, provide which of the",
#' "context values apply as correct tags using TRUE/FALSE"),
#' input = c("I love chocolate", "I hate chocolate", "I like Coke", "Who am I?", "T-REX"),
#' context = c("food", "positive", "negative", "beverage"),
#' output = "table",
#' quiet = FALSE)
#'
#' # Extract information from strings
#' p <- gpt_prompter(
#' instruction = "For each of the inputs, extract each of the information asked in context",
#' input = c("My mail is 123@@test.com", "30 Main St, NY, USA", "+82 2-312-3456", "$1.5M"),
#' context = c("email", "full state name", "country of phone", "full non-abbreviated number"),
#' output = "table",
#' cols = c("Input", "Element_to_extract", "Value"),
#' quiet = FALSE)
#'
#' # Translate to several languages
#' p <- gpt_prompter(
#' instruction = "For each of the inputs, translate to the respective languages in context",
#' input = rep("I love you with all my heart", 5),
#' context = c("spanish", "chinese", "japanese", "russian", "german"),
#' output = "table",
#' cols = c("Input", "Language", "Translation"),
#' quiet = FALSE)
#'
#' # Format date values
#' p <- gpt_prompter(
#' instruction = paste("For each of the inputs,",
#' "standardize and format all values to the format in context"),
#' input = c("March 27th, 2021", "12-25-2023 3:45PM", "01.01.2000", "29 Feb 92"),
#' context = "ISO Date getting rid of time stamps",
#' output = "table",
#' cols = c("Input", "Formatted"),
#' quiet = FALSE)
#'
#' # Convert units
#' p <- gpt_prompter(
#' instruction = paste("For each of the inputs,",
#' "provide new converted values using the units in context"),
#' input = c("50C", "300K", "100F", "0F", "32C", "0K"),
#' context = "Fahrenheit",
#' output = "table",
#' cols = c("Input", "Original_Unit", "Total_Value", "Converted_Value", "New_Unit"),
#' quiet = FALSE)
#'
#' # Read a text and answer a question related to it
#' gpt_prompter(instruction = "read",
#' context = "Long text here",
#' input = "Question here")$prompt
#' @export
gpt_prompter <- function(instruction = NULL,
input = NULL,
context = NULL,
output = NULL,
quiet = TRUE,
...) {
# Generic helpers for common use cases
if ("table" %in% output) {
output <- paste(
"Markdown format table. If missing elements, replace with NA.",
"For numerical columns, only use a dot for decimals, no delimiters, no abbreviations"
)
}
if ("read" %in% instruction) {
instruction <- paste(
"You are a pro content editor who will read the context text and",
"reply using a single concise response to the question asked in input.",
"If the answer is not found in context, reply you cannot find the answer in the text"
)
}
if ("cols" %in% names(list(...))) {
cols <- list(...)[["cols"]]
if (!is.null(cols)) {
output <- paste0(
output, "; also, it must have ", length(cols), " columns named exactly: ", v2t(cols, and = "and")
)
}
}
# Build the list with 4 elements (and additional information passed through ...)
elements <- list(
instruction = if (!is.null(instruction)) paste("Instruction =", paste(instruction, collapse = "; ")) else NULL,
input = if (!is.null(input)) paste("Input =", paste(input, collapse = "; ")) else NULL,
context = if (!is.null(context)) paste("Context =", paste(context, collapse = "; ")) else NULL,
output = if (!is.null(output)) paste("Output =", paste(output, collapse = "; ")) else NULL,
...
)
# Get rid of already used information
elements["cols"] <- NULL
# Check if something's actually being prompted
are_null <- unlist(lapply(elements, is.null))
if (all(are_null)) warning("No prompt provided. Set any of the elements: ", v2t(names(elements)))
if (!quiet) cat(paste(paste(elements[!are_null], collapse = "\n"), "\n"))
return(invisible(
list(
prompt = v2t(elements[!are_null], quotes = FALSE, sep = " ### "),
elements = list(instruction = instruction, input = input, context = context, output = output, ...)
)
))
}