DEV Community

dhavaldav
dhavaldav

Posted on

PHP ChatGPT – CURL ChatGPT API using PHP

PHP ChatGPT – CURL ChatGPT API using PHP

To access OpenAI’s ChatGPT API using PHP, you can use any HTTP client library that supports making HTTP requests with JSON payloads, such as Guzzle or cURL. You may find it a bit ridiculous because ChatGPT hasn’t officially announced the API yet. But the fact that OpenAI already has APIs available to provide full task processing like ChatGPT. This REST API can answer your questions or handle your requests with the same results as ChatGPT.

$data = array( "prompt" => "do we need wording about  Climate Change?", //Your request or question 
  "temperature" => 0.5,
  "max_tokens" => 500
);

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://api.openai.com/v1/engines/davinci-codex/completions');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));

$headers = array();
$headers[] = 'Content-Type: application/json';
$headers[] = 'Authorization: Bearer YOUR_API_KEY';
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

$response = curl_exec($ch);
if (curl_errno($ch)) {
    echo 'Error:' . curl_error($ch);
}
curl_close($ch);
echo $response;
Enter fullscreen mode Exit fullscreen mode

Code Source : https://onlinecode.org

Top comments (0)