Hey all, this is my first post here, hope you are all well o/
I am trying to create a simple API call from PHP to GPT-3.5-turbo. I do not have access to CURL on the server and I won’t get it either so I am trying to work with simple HTTP requests. Here is my code:
function get_rephrased_text($api_key, $text) {
$endpoint = 'https://api.openai.com/v1/chat/completions';
$headers = array(
"Authorization: Bearer $api_key",
"Content-Type: application/json"
);
$payload = array(
"model" => "gpt-3.5-turbo",
"messages" => array(
array(
"role" => "user",
"content" => $text
)
),
"max_tokens" => 250,
"temperature" => 0.7
);
$jsonPayload = json_encode($payload);
// debug
var_dump($jsonPayload);
echo "<br/>";
$options = array(
'http' => array(
'header' => implode("\r\n", $headers),
'method' => 'POST',
'content' => $jsonPayload
)
);
$context = stream_context_create($options);
$response = file_get_contents($endpoint, false, $context);
$response_data = json_decode($response, true);
// debug
var_dump($response_data);
echo "<br/>";
if (isset($response_data['choices']) && count($response_data['choices']) > 0)
{
return trim($response_data['choices'][0]['text']);
}
else
{
return null;
}
}
The debug output of the JSON seems perfectly fine. Also I can see the API requests in the OpenAi dashboard under my API key so that is also correct. Can anyone spot what I am doing wrong here?
Thanks a lot !
Have you tried dumping the actual response before converting it to JSON?
1 Like
Hey Serge,
thanks a lot for the suggestion!
This pointed me in the right direction. For anyone running into a similar problem, add the following to your HTTP request:
‘ignore_errors’ => true
$options = array(
'http' => array(
'header' => implode("\r\n", $headers),
'method' => 'POST',
'content' => $jsonPayload,
'ignore_errors' => true
)
);
This results in you getting an actual error message instead of just false. Now I know that I simply exceeded my current quota … I feel silly but thanks a lot for your help!
Cleaner would be to check if the response is an error and handle that
See what’s in $http_response_header to check for errors