blob: c2497a699608e01038abab01952f331c284beae5 [file] [log] [blame]
ben-aaron188ad8b3f32023-03-05 20:22:57 +01001#' Makes a single chat completion request to the ChatGPT API
2#'
3#' @description
4#' `chatgpt_single()` sends a single [chat completion request](https://platform.openai.com/docs/guides/chat) to the Open AI GPT API. Doing so, makes this equivalent to the sending single completion requests with `gpt3_single_completion()`. You can see the notes on chat vs completion requests here: [https://platform.openai.com/docs/guides/chat/chat-vs-completions](https://platform.openai.com/docs/guides/chat/chat-vs-completions). This function allows you to specify the role and content for your API call.
5#' @details For a general guide on the completion requests, see [https://platform.openai.com/docs/api-reference/chat](https://platform.openai.com/docs/api-reference/chat). This function provides you with an R wrapper to send requests with the full range of request parameters as detailed on [https://beta.openai.com/docs/api-reference/completions](https://beta.openai.com/docs/api-reference/completions) and reproduced below.
6#'
7#' Parameters not included/supported:
8#' - `logit_bias`: [https://platform.openai.com/docs/api-reference/chat/create#chat/create-logit_bias](https://platform.openai.com/docs/api-reference/chat/create#chat/create-logit_bias)
9#' - `stream`: [https://platform.openai.com/docs/api-reference/chat/create#chat/create-stream](https://platform.openai.com/docs/api-reference/chat/create#chat/create-stream)
10#'
11#'
12#' @param prompt_role character (default: 'user') that contains the role for the prompt message in the ChatGPT message format. Must be one of 'system', 'assistant', 'user' (default), see [https://platform.openai.com/docs/guides/chat](https://platform.openai.com/docs/guides/chat)
13#' @param prompt_content character that contains the content for the prompt message in the ChatGPT message format, see [https://platform.openai.com/docs/guides/chat](https://platform.openai.com/docs/guides/chat). This is the key instruction that ChatGPT receives.
14#' @param model a character vector that indicates the [ChatGPT model](https://platform.openai.com/docs/api-reference/chat/create#chat/create-model) to use; one of "gpt-3.5-turbo" (default), "gpt-3.5-turbo-0301"
15#' @param output_type character determining the output provided: "complete" (default), "text" or "meta"
16#' @param max_tokens numeric (default: 100) indicating the maximum number of tokens that the completion request should return (from the official API documentation: _The maximum number of tokens allowed for the generated answer. By default, the number of tokens the model can return will be (4096 - prompt tokens)._)
17#' @param temperature numeric (default: 1.0) specifying the sampling strategy of the possible completions (from the official API documentation: _What sampling temperature to use, between 0 and 2. Higher values like 0.8 will make the output more random, while lower values like 0.2 will make it more focused and deterministic. We generally recommend altering this or `top_p` but not both._)
18#' @param top_p numeric (default: 1) specifying sampling strategy as an alternative to the temperature sampling (from the official API documentation: _An alternative to sampling with temperature, called nucleus sampling, where the model considers the results of the tokens with top_p probability mass. So 0.1 means only the tokens comprising the top 10% probability mass are considered. We generally recommend altering this or `temperature` but not both._)
19#' @param n numeric (default: 1) specifying the number of completions per request (from the official API documentation: _How many chat completion choices to generate for each input message. **Note: Because this parameter generates many completions, it can quickly consume your token quota.** Use carefully and ensure that you have reasonable settings for max_tokens and stop._)
20#' @param stop character or character vector (default: NULL) that specifies after which character value when the completion should end (from the official API documentation: _Up to 4 sequences where the API will stop generating further tokens._)
21#' @param presence_penalty numeric (default: 0) between -2.00 and +2.00 to determine the penalisation of repetitiveness if a token already exists (from the official API documentation: _Number between -2.0 and 2.0. Positive values penalize new tokens based on whether they appear in the text so far, increasing the model's likelihood to talk about new topics._). See also: [https://beta.openai.com/docs/api-reference/parameter-details](https://beta.openai.com/docs/api-reference/parameter-details)
22#' @param frequency_penalty numeric (default: 0) between -2.00 and +2.00 to determine the penalisation of repetitiveness based on the frequency of a token in the text already (from the official API documentation: _Number between -2.0 and 2.0. Positive values penalize new tokens based on their existing frequency in the text so far, decreasing the model's likelihood to repeat the same line verbatim._). See also: [https://beta.openai.com/docs/api-reference/parameter-details](https://beta.openai.com/docs/api-reference/parameter-details)
23#'
24#' @return A list with two data tables (if `output_type` is the default "complete"): [[1]] contains the data table with the columns `n` (= the mo. of `n` responses requested), `prompt_role` (= the role that was set for the prompt), `prompt_content` (= the content that was set for the prompt), `chatgpt_role` (= the role that ChatGPT assumed in the chat completion) and `chatgpt_content` (= the content that ChatGPT provided with its assumed role in the chat completion). [[2]] contains the meta information of the request, including the request id, the parameters of the request and the token usage of the prompt (`tok_usage_prompt`), the completion (`tok_usage_completion`) and the total usage (`tok_usage_total`).
25#'
26#' If `output_type` is "text", only the data table in slot [[1]] is returned.
27#'
28#' If `output_type` is "meta", only the data table in slot [[2]] is returned.
29#' @examples
30#' # First authenticate with your API key via `gpt3_authenticate('pathtokey')`
31#'
32#' # Once authenticated:
33#'
34#' ## Simple request with defaults:
35#' chatgpt_single(prompt_content = 'You are a teacher: explain to me what science is')
36#'
37#' ## Instruct ChatGPT to write ten research ideas of max. 150 tokens with some controls:
38#' chatgpt_single(prompt_role = 'user', prompt_content = 'Write a research idea about using text data to understand human behaviour:'
39#' , temperature = 0.8
40#' , n = 10
41#' , max_tokens = 150)
42#'
43#' ## For fully reproducible results, we need `temperature = 0`, e.g.:
44#' chatgpt_single(prompt_content = 'Finish this sentence:/n There is no easier way to learn R than'
45#' , temperature = 0.0
46#' , max_tokens = 50)
47#'
48#' @export
49chatgpt_single = function(prompt_role = 'user'
50 , prompt_content
51 , model = 'gpt-3.5-turbo'
52 , output_type = 'complete'
53 , max_tokens = 100
54 , temperature = 1.0
55 , top_p = 1
56 , n = 1
57 , stop = NULL
58 , presence_penalty = 0
59 , frequency_penalty = 0
60 ){
61
62 #check for request issues with `n` and `best_of`
63
64 if(temperature == 0 & n > 1){
65 n = 1
66 message('You are running the deterministic model, so `n` was set to 1 to avoid unnecessary token quota usage.')
67 }
68
69 messages = c = data.frame(role = prompt_role
70 , content = prompt_content)
71
72 parameter_list = list(messages = messages
73 , model = model
74 , max_tokens = max_tokens
75 , temperature = temperature
76 , top_p = top_p
77 , n = n
78 , stop = stop
79 , presence_penalty = presence_penalty
80 , frequency_penalty = frequency_penalty
81 )
82
83 request_base = httr::POST(url = url.chat_completions
84 , body = parameter_list
85 , httr::add_headers(Authorization = paste("Bearer", api_key))
86 , encode = "json")
87
88 request_content = httr::content(request_base)
89
90 if(n == 1){
91 core_output = data.table::data.table('n' = 1
92 , 'prompt_role' = prompt_role
93 , 'prompt_content' = prompt_content
94 , 'chatgpt_role' = request_content$choices[[1]]$message$role
95 , 'chatgpt_content' = request_content$choices[[1]]$message$content)
96 } else if(n > 1){
97
98 core_output = data.table::data.table('n' = 1:n
99 , 'prompt_role' = rep(prompt_role, n)
100 , 'prompt_content' = rep(prompt_content, n)
101 , 'chatgpt_role' = rep("", n)
102 , 'chatgpt_content' = rep("", n))
103
104 for(i in 1:n){
105 core_output$chatgpt_role[i] = request_content$choices[[i]]$message$role
106 core_output$chatgpt_content[i] = request_content$choices[[i]]$message$content
107 }
108
109 }
110
111
112 meta_output = data.table::data.table('request_id' = request_content$id
113 , 'object' = request_content$object
114 , 'model' = request_content$model
115 , 'param_prompt_role' = prompt_role
116 , 'param_prompt_content' = prompt_content
117 , 'param_model' = model
118 , 'param_max_tokens' = max_tokens
119 , 'param_temperature' = temperature
120 , 'param_top_p' = top_p
121 , 'param_n' = n
122 , 'param_stop' = stop
123 , 'param_presence_penalty' = presence_penalty
124 , 'param_frequency_penalty' = frequency_penalty
125 , 'tok_usage_prompt' = request_content$usage$prompt_tokens
126 , 'tok_usage_completion' = request_content$usage$completion_tokens
127 , 'tok_usage_total' = request_content$usage$total_tokens)
128
129
130 if(output_type == 'complete'){
131 output = list(core_output
132 , meta_output)
133 } else if(output_type == 'meta'){
134 output = meta_output
135 } else if(output_type == 'text'){
136 output = core_output
137 }
138
139 return(output)
140
141}