-
Notifications
You must be signed in to change notification settings - Fork 10
/
openai.R
68 lines (56 loc) · 2.36 KB
/
openai.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
library(jsonlite)
library(httr2)
library(stringr)
# Save your API key in the file openai_key.txt
MY_OPENAI_API_KEY <- readLines("openai_key.txt")
Sys.setenv(OPENAI_API_KEY = MY_OPENAI_API_KEY)
# Edit the following line with the endpoint of the API.
# You can find this in the Azure portal under "Keys and Endpoint".
MY_ENDPOINT <- "https://openai-test-20230120.openai.azure.com/"
# Edit the following line with the model you want to use.
# You can find options in the Azure portal under "Model Deployments"
MY_DEPLOYMENT <- "text-davinci-003"
openai <- function(prompt, temperature=1,top_p=0.5,max_tokens=100,stop="null",
OPENAI_API_KEY=MY_OPENAI_API_KEY,
ENDPOINT=MY_ENDPOINT,
model=MY_DEPLOYMENT, print.it=TRUE) {
# openai(prompt) returns a string of text generated by the OpenAI API
# ARGUMENTS:
# prompt: a string of text to prompt the API with (Do not include single quotes)
# VALUE:
# the completion generated by the OpenAI API
# in addition, if print.it=TRUE (the defualt), the completion is printed
# to the console minus any leading whitespace
# Example:
# openai("The quick brown fox jumps over the lazy dog. Translate into French:")
req <- request(ENDPOINT) %>%
req_url_path_append("openai/deployments") %>%
req_url_path_append(model) %>%
req_url_path_append("completions") %>%
req_url_query("api-version"="2022-12-01")
# newlines in the prompt confuse the API, so use toJSON to encode as \n
payload <- paste0('{
"prompt": ', toJSON(prompt, auto_unbox=TRUE), ',
"max_tokens": ',max_tokens,',
"temperature": ', temperature, ',
"frequency_penalty": 0,
"presence_penalty": 0,
"top_p": ', top_p, ',
"best_of": 1,
"stop": ',stop,'
}')
req <- req %>% req_headers(
`api-key` = OPENAI_API_KEY,
) %>%
req_body_raw(payload, "application/json")
#print(req_dry_run(req))
result <- req %>% req_perform() %>% resp_body_json()
completion <- result$choices[[1]]$text
output <- str_trim(completion) # remove leading and trailing whitespace
if (print.it) cat(output,"\n")
return(invisible(completion))
}
#Examples:
#openai("tell me a joke")
#openai("Your favorite number is 5. Pick a number between 1 and 10. Go:", top_p=1)
#openai("Complete this sentence: The best flavor of ice cream is ", top_p=0.9)