Created
January 29, 2024 10:51
-
-
Save bquilty25/1cb5c352a25a9af253646d1fc745cb4b to your computer and use it in GitHub Desktop.
Accessing OpenAI API from R
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
library(httr) | |
library(jsonlite) | |
api_key <- "sk-XXX" # Set your OpenAI API key (don't publish anywhere public!) | |
base_url_openai <- "https://api.openai.com/v1" | |
openai_call <- function(prompt) { | |
request_url <- paste0(base_url_openai, "/chat/completions") | |
payload <- list( | |
model = "gpt-3.5-turbo", # Choose the model | |
messages = list( | |
list(role = "system", content = "You are an AI that does X..."), | |
list(role = "user", content = "prompt") | |
), | |
temperature = 0.7 | |
) | |
response <- POST( | |
url = request_url, | |
add_headers("Content-Type" = "application/json", | |
"Authorization" = paste("Bearer", api_key)), | |
body = toJSON(payload, pretty = FALSE, auto_unbox = TRUE), | |
encode = "json" | |
) | |
content <- content(response, "text") | |
parsed_content <- fromJSON(content) | |
return(parsed_content$choices$message$content[[1]]) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment