Skip to content

Instantly share code, notes, and snippets.

@rasmusab
Last active June 22, 2023 06:46
Show Gist options
  • Save rasmusab/c25badf55f5dacee14ab13834798d3ef to your computer and use it in GitHub Desktop.
Save rasmusab/c25badf55f5dacee14ab13834798d3ef to your computer and use it in GitHub Desktop.
How to call the ChatGTP API from R (in 2023-03-01)
# How to call the new (as of 2023-03-01) ChatGTP API from R
# Get your API key over here: https://platform.openai.com/
api_key <- "sk-5-your-actual-api-key-Fvau6" # Don't share this! 😅
library(httr)
library(stringr)
# Calls the ChatGTP API with the given promps and returns the answer
ask_chatgtp <- function(prompt) {
response <- POST(
url = "https://api.openai.com/v1/chat/completions",
add_headers(Authorization = paste("Bearer", api_key)),
content_type_json(),
encode = "json",
body = list(
model = "gpt-3.5-turbo",
messages = list(list(
role = "user",
content = prompt
))
)
)
str_trim(content(response)$choices[[1]]$message$content)
}
# For example:
ask_chatgtp("What function makes a histogram in R?")
## "The `hist()` function makes a histogram in R."
@staceymir
Copy link

I updated the httr package and now the code is working :-)

@GeraldWittrock
Copy link

GeraldWittrock commented Mar 21, 2023

Thank you. By the way, when looking for internet essay samples to assist me write my essay, I came across this website https://www.topessaywriting.org/samples/culture On this website, I may get numerous free essay samples to assist me enhance and personalise my essay.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment