Search code examples
ropenai-apichatgpt-api

OpenAI Chat Completions API error 400: "'user' is not of type 'object'"


I share with you my code below to get a response from a POST request with R from the OpenAI Chat Completions API:

param <- list(model = "gpt-3.5-turbo",
              messages = c("role" = "user", 
                           "content" = "Hello"))

result <- POST("https://api.openai.com/v1/chat/completions",
               body = param,
               add_headers(Authorization=openai_secret_key),
               encode = "json")

Here is the result :

Response [https://api.openai.com/v1/chat/completions] Date: 2023-03-02 16:28 Status: 400 Content-Type: application/json Size: 158 B { “error”: { “message”: “‘user’ is not of type ‘object’ - ‘messages.0’”, “type”: “invalid_request_error”, “param”: null, “code”: null } }

So the user and the content parts are not working but the model is working.

Thanks a lot!

In postman, I have this JSON working but can't make it work in R:

{
   "model":"gpt-3.5-turbo",
   "messages":[
      {
         "role":"user",
         "content":"Hello!"
      }
   ]
}

Solution

  • If you run test.r the OpenAI API will return the following completion:

    [1] "\n\nHello! How may I assist you today?"

    test.r

    library(httr)
    library(jsonlite)
    
    OPENAI_API_KEY <- "sk-xxxxxxxxxxxxxxxxxxxx"
    
    param <- list(model = "gpt-3.5-turbo",
                  messages = list(list(role = "user", content = "Hello"))
             )
        
    result <- POST("https://api.openai.com/v1/chat/completions",
                   body = param,
                   add_headers("Authorization" = paste("Bearer", OPENAI_API_KEY)),
                   encode = "json")
    
    response_content <- fromJSON(rawToChar(result$content))
    print(response_content$choices[[1]]$content)