Skip to content

Instantly share code, notes, and snippets.

@rasmusab
Last active June 22, 2023 06:46
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • 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."
@pvsundar
Copy link

pvsundar commented Mar 3, 2023

ask_chatgtp("What function makes a histogram in R?")
Error in content_type_json() :
could not find function "content_type_json"

@kshtjkumar
Copy link

i too got the same error as @pvsundar.
Error in content_type_json() :
could not find function "content_type_json"

are we missing something? or is this the full code block ?

@rasmusab
Copy link
Author

rasmusab commented Mar 3, 2023

@kshtjkumar @pvsundar No, I was just sloppy and did a last minute refactoring that didn't work (replacing library(httr) with httr::, but forgot a place). I've now put library(httr) back above ☝️ , and everything should work. Thanks for trying it out! :D

@pvsundar
Copy link

pvsundar commented Mar 3, 2023

Thanks. Will try it. In the meantime, I used:

install.packages("remotes")
remotes::install_github("jcrodriguez1989/chatgpt")

Sys.setenv(OPENAI_API_KEY = "sk-5-your-actual-api-key-Fauci")

#OPENAI_VERBOSE=FALSE
OPENAI_ADDIN_REPLACE=TRUE

@laresbernardo
Copy link

laresbernardo commented Mar 3, 2023

I've got a couple of suggestions:

  1. Return (return()) the actual OpenAI's response so that if we want to store the returned results or check at anything else, we can simply assign it to an object and use it later on.
  2. Add a cat() to the print so it renders nicely.
  3. Warn with the returned error message if that's the case

This should fix all:

  ret <- content(response)
  if ("error" %in% names(ret)) warning(ret$error$message)  
  if ("message" %in% names(ret$choices[[1]]))
    cat(stringr::str_trim(ret$choices[[1]]$message$content))
  return(invisible(ret))

@kshtjkumar
Copy link

@laresbernardo I agree rendering cud actually help greatly, right now it just gives everything in a messy order. where do i put ur fix in the whole code ?

@laresbernardo
Copy link

laresbernardo commented Mar 3, 2023

# 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
      ))
    )
  )
  ret <- content(response)
  if ("error" %in% names(ret)) warning(ret$error$message)
  if ("message" %in% names(ret$choices[[1]]))
    cat(stringr::str_trim(ret$choices[[1]]$message$content))
  return(invisible(ret))
}

# For example: 
ask_chatgtp("What function makes a histogram in R?")
## "The `hist()` function makes a histogram in R."

@pvsundar
Copy link

pvsundar commented Mar 4, 2023

Thank you... This works now.

@staceymir
Copy link

Starting from today content(response) returns an Error in UseMethod("content", x) : no applicable method for 'content' applied to an object of class "response".
Any ideas how to fix it?

Thank you!

@pvsundar
Copy link

@staceymir Stacey it is working for me.
Try restarting.

@pvsundar
Copy link

In the meantime look at this option
https://github.com/jcrodriguez1989/chatgpt

@staceymir
Copy link

Thank you for the link pvsundar, I'll give it a try.

In case if anyone can help with the issue, here is a code:

library(httr)
api_key <- "..."
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 = "What is ChatGPT?"
)
)
)
)
content(response)

@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