-
-
Save rasmusab/c25badf55f5dacee14ab13834798d3ef to your computer and use it in GitHub Desktop.
| # 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." |
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!
@staceymir Stacey it is working for me.
Try restarting.
In the meantime look at this option
https://github.com/jcrodriguez1989/chatgpt
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)
I updated the httr package and now the code is working :-)
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.
Thank you... This works now.