R POST request for model gpt-3.5-turbo not working

Hello everyone,

I share with you my code bellow to get a response from a POST request with R :

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 part is not working. Do you have an idea why ?

Thanks a lot

user’ is not of type ‘object

Messages needs to be an array of objects…

1 Like

Hi PaulBellow,

Thanks for your reply. but How should I update messages = c(“role” = “user”,“content” = “Hello”) to make it an object ?

Thanks

Its all in the chat docs here, @raph

https://platform.openai.com/docs/guides/chat/introduction

Its a great idea to take 5 minutes and read the API docs.

:slight_smile:

Hi ruby_coder,

Thanks for your reply.

I have read the API doc, actually I am able make it work with PHP and the bellow json code works perfectly in postman, my issue is with R

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

$client = new \GuzzleHttp\Client();
            $headers = [
                'Authorization'=>'Bearer '.$openai_secret_key,
                'Content-Type'=>'application/json'
            ];

            $url = 'https://api.openai.com/v1/chat/completions';
            $bodyText = [
                "model"=>"gpt-3.5-turbo",
                "messages"=>[
                    [
                        "role"=>"user",
                        "content"=>"Hello!"
                    ]
                ]
            ];

$response = $client->request('POST', $url, ['headers'=>$headers, 'body'=>json_encode($bodyText)]);

$body = $response->getBody();
            

$data = json_decode($body, true);

            return $data;

This would help, I guess