I'm writing a simple PHP script with no dependencies to access the ChatGPT API, but it's throwing an error I don't understand:
Here's the script so far:
$apiKey = "Your-API-Key";
$url = 'https://api.openai.com/v1/chat/completions';
$headers = array(
"Authorization: Bearer {$apiKey}",
"OpenAI-Organization: YOUR-ORG-STRING",
"Content-Type: application/json"
);
// Define messages
$messages = array();
$messages["role"] = "user";
$messages["content"] = "Hello future overlord!";
// Define data
$data = array();
$data["model"] = "gpt-3.5-turbo";
$data["messages"] = $messages;
$data["max_tokens"] = 50;
// init curl
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($data));
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec($curl);
if (curl_errno($curl)) {
echo 'Error:' . curl_error($curl);
} else {
echo $result;
}
curl_close($curl);
This returns an error from the API:
{"model":"gpt-3.5-turbo","messages":{"role":"user","content":"Hello future overlord!"},"max_tokens":50}{ "error": { "message": "{'role': 'user', 'content': 'Hello future overlord!'} is not of type 'array' - 'messages'", "type": "invalid_request_error", "param": null, "code": null } }
AFAIK, I'm sending the messages param as an array. Where is this going wrong? Is this an issue with json_encode? Why doesn't the API think this is an array?
Thanks in advance!
json_encode()
will encode a PHP associative array as a JSON object. If you need to create a JSON array you must create a PHP array with numeric indices. I'm not familiar with the API so I can't tell you what you need to do.$data["messages"] = $messages;
line to$data["messages[]"] = $messages;
and try it again?