WmZilla - Webmaster and Marketplace

The Next Generation Webmaster and Trade Forum

How to Connect to the ChatGPT API Using PHP

zukule

New member

0

0%

Status

Offline

Posts

3

Likes

0

Rep

0

Bits

33

2

Months of Service

0%
Hi everyone,

I've created a simple class to help you connect to the ChatGPT API using PHP and retrieve responses. This class can be easily integrated into your projects. Below, I'll explain how it works and provide the code.

Overview​

The provided PHP class connects to the OpenAI ChatGPT API and sends a prompt to get a response. All you need to do is change the prompt and the API key in the code.

The Code​

Here's the code for the PHP class:


Code:
<?php
class GptApi
{
    private $apiKey;
    private $model = 'gpt-3.5-turbo';
    
    public function __construct($apiKey)
    {
        $this->apiKey = $apiKey;
    }

    public function getResponse($prompt)
    {
        $response = $this->chatWithGpt($prompt);
        return $response;
    }

    private function chatWithGpt($prompt)
    {
        $data = array(
            'model' => $this->model,
            'messages' => array(
                array('role' => 'user', 'content' => $prompt),
            ),
            'max_tokens' => 150, // Adjust this value as needed
            'temperature' => 0.7,
            'top_p' => 1,
            'n' => 1,
            'stop' => null,
        );

        $headers = array(
            'Content-Type: application/json',
            'Authorization: ' . 'Bearer ' . $this->apiKey,
        );

        $url = 'https://api.openai.com/v1/chat/completions';

        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
        
        $response = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        $curlError = curl_error($ch);
        
        curl_close($ch);

        if ($curlError) {
            return 'Curl error: ' . $curlError;
        }

        $responseArray = json_decode($response, true);
        
        if ($httpCode !== 200) {
            return 'API error: ' . $responseArray['error']['message'];
        }
        
        return $responseArray['choices'][0]['message']['content'] ?? 'No response';
    }
}

// Insert your API key here
$apiKey = 'Insert your OpenAI API key here.';
$prompt = 'wmzilla.';

$gptApi = new GptApi($apiKey);
echo $gptApi->getResponse($prompt);
 

247

1,278

1,298

Top