chatGPT API call in R code returns an error

Hello

When I try to run the following R-code to call chatGPT:

library(httr)
library(stringr)

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 get an error:
Error in UseMethod(“content”, x) :
no applicable method for ‘content’ applied to an object of class “response”

Any ideas what’s wrong?

First some advice, use the formatting options to make your code easier to read so it is easier for everyone to debug.

Here’s your code:

library(httr)
library(stringr)

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)

Now that I can see that there aren’t any obvious errors in your actual code, it’s easier to focus on what the actual issue is.

You appear to be using the incorrect content() function. The httr::content() function is the correct one to use and it looks like you are using it, but the error says otherwise. The only other mainstream package I know which has a content() function is NLP, so I am guessing that sometime after loading the httr package you called library("NLP") probably to do some natural language processing on your response object.

Anyway, when you loaded NLP you would have gotten a message stating,

Attaching package: 'NLP'

The following object is masked from 'package:httr':

    content

since both packages have a content() function, whichever one was loaded most recently will be found in your search path and be used by R.

You can do one of,

  1. Call httr::content() explicitly with the proper namespace.
  2. Restart your R session and load NLP before httr so httr::content() masks NLP::content() instead of the other way around.

I would just wrap your code inside a function call so it is easily reusable, then explicitly use the namespace for all httr functions so it can’t ever be an issue again.

Hope that helps!

1 Like

Hi Jake,

Thank you very much for your find!
I have the ‘tm’ library initiated and this caused the issue. An explicit reference to the ‘content’ function in httr helped.

Sorry for the code formatting - it was a copy-paste issue. The code is formatted in my R-file and also wrapped in the function.

1 Like