401 error when accessing OpenAI using httr2 library

224 Views Asked by At

Error: Error in req_perform(): ! HTTP 401 Unauthorized. Run rlang::last_trace() to see where the error occurred.

#Libraries used (probably overkill): 
library(httr2)
library(wordcloud)
library(RColorBrewer)
library(wordcloud2)
library(tm)
library(readr)
library(pdftools)
library(htmlwidgets)
library(stopwords)
url_base <-"https://api.openai.com/v1/"
prompt <- "Please tell me a dad joke"

Input code: model_type<-"gpt-3.5-turbo"

body <- list(model    = model_type,
             messages = list(list(role = "user", 
             content = prompt)))

response<-request(url_base) |>
req_url_path_append("chat/completions") |>
req_auth_bearer_token(token = api_key) |>
req_headers("Content-Type" = "application/json") |> 
req_user_agent("JustADude @justadude") |> 
req_body_json(body)  |> 
req_perform()

req_dry_run() output:

POST /v1/chat/completions HTTP/1.1
Host: api.openai.com
User-Agent: JustADude @justadude
Accept: */*
Accept-Encoding: deflate, gzip
Authorization: <REDACTED>
Content-Type: application/json
Content-Length: 92

{"model":"gpt-3.5-turbo","messages":[{"role":"user","content":"Please tell me a dad joke"}]}

Any recommendations for fixing the error? I've looked into the OpenAI Reference material (https://platform.openai.com/docs/api-reference) but not seeing the error on my part. Thank you for any recommendations on fixing the error.

0

There are 0 best solutions below