Friday, September 20, 2024

Create A PHP Chatbot Using The OpenAI API & ChatGPT

Learn how to use PHP to create a chatbot that uses OpenAI API and ChatGPT. The interface is designed in Bootstrap 5 and jquery to create a stylized GUI for our chatbot.

ChatGPT Chatbot Demo

Make An API Connection To OpenAI’s ChatGPT

First, we will create a PHP class called ChatGPT, which will serve as a wrapper for OpenAI’s ChatGPT API. This class will allow us to interact with the API easily and make requests to generate text and images using the power of ChatGPT.

Step 1: Getting Started

Let’s start by setting up our PHP file and defining the ChatGPT class.

<?php

class ChatGPT
{
    // API Key and API URLs
    private $API_KEY = "OPEN_AI_API_KEY";
    private $textURL = "https://api.openai.com/v1/completions";
    private $imageURL = "https://api.openai.com/v1/images/generations";

    // cURL object and data request array
    public $curl;
    public $data = [];

    // Constructor: Initialize the cURL object
    public function __construct()
    {
        $this->curl = curl_init();
    }

    // Other methods will be added here later
}

Step 2: Initializing the API Request

We’ll add a method called initialize to set up the cURL object and define the request type (text or image) based on the parameter provided.

class ChatGPT
{

    // Initialize the cURL object for the specific request type (text or image)
    public function initialize($requestType = "text" || "image")
    {
        $this->curl = curl_init();

        if ($requestType === 'image')
            curl_setopt($this->curl, CURLOPT_URL, $this->imageURL);
        if ($requestType === 'text')
            curl_setopt($this->curl, CURLOPT_URL, $this->textURL);

        curl_setopt($this->curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($this->curl, CURLOPT_POST, true);

        $headers = array(
            "Content-Type: application/json",
            "Authorization: Bearer $this->API_KEY"
        );

        curl_setopt($this->curl, CURLOPT_HTTPHEADER, $headers);
    }

}

Step 3: Generating Text

We’ll add a method called createTextRequest that will allow us to generate text based on the provided prompt.

class ChatGPT
{

    // Generate text based on the given prompt
    public function createTextRequest($prompt, $model = 'text-davinci-003', $temperature = 0.5, $maxTokens = 1000)
    {
        curl_reset($this->curl);
        $this->initialize('text');

        $this->data["model"] = $model;
        $this->data["prompt"] = $prompt;
        $this->data["temperature"] = $temperature;
        $this->data["max_tokens"] = $maxTokens;

        curl_setopt($this->curl, CURLOPT_POSTFIELDS, json_encode($this->data));

        $response = curl_exec($this->curl);
        $response = json_decode($response, true);
        return $response['choices'][0]['text'] ?? -1; // return text or -1 if error
    }

}

Step 4: Generating Images

We’ll add a method called generateImage that will allow us to generate images based on the provided prompt.

class ChatGPT
{

    // Generate images based on the given prompt
    public function generateImage($prompt, $imageSize = '512x512', $numberOfImages = 1)
    {
        curl_reset($this->curl);
        $this->initialize('image');

        $this->data["prompt"] = $prompt;
        $this->data["n"] = $numberOfImages;
        $this->data["size"] = $imageSize;

        curl_setopt($this->curl, CURLOPT_POSTFIELDS, json_encode($this->data));

        $response = curl_exec($this->curl);
        $response = json_decode($response, true);
        return $response['data'][0]['url'] ?? -1; // return the first URL or -1 if error
    }

}

Step 5: Putting It All Together

With the ChatGPT class defined, you can now use it to interact with the OpenAI ChatGPT API and generate text or images based on the provided prompts. Here’s how you can use it:

// Include the PHP file with the ChatGPT class

// Create an instance of ChatGPT
$chatGPT = new ChatGPT();

// Generate text
$textPrompt = "Once upon a time";
$textResponse = $chatGPT->createTextRequest($textPrompt);
echo "Generated Text: " . $textResponse . "\n";

// Generate an image
$imagePrompt = "A serene lake with mountains in the background";
$imageResponse = $chatGPT->generateImage($imagePrompt);
echo "Generated Image URL: " . $imageResponse . "\n";

Please note that in this tutorial, we assume you have an API key for OpenAI’s ChatGPT API, and you can replace the API_KEY variable’s value with your actual API key.

Complete Code For ChatGPT.php

<?php

class ChatGPT
{

    private $API_KEY = "OPEN_AI_API_KEY";
    private $textURL = "https://api.openai.com/v1/completions";
    private $imageURL =  "https://api.openai.com/v1/images/generations";

    public $curl;       // create cURL object
    public $data = [];  // data request array

    public function __construct()
    {
        $this->curl = curl_init();
    }

    public function initialize($requestType = "text" || "image")
    {
        $this->curl = curl_init();

        if ($requestType === 'image')
            curl_setopt($this->curl, CURLOPT_URL, $this->imageURL);
        if ($requestType === 'text')
            curl_setopt($this->curl, CURLOPT_URL, $this->textURL);

        curl_setopt($this->curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($this->curl, CURLOPT_POST, true);

        $headers = array(
            "Content-Type: application/json",
            "Authorization: Bearer $this->API_KEY"
        );

        curl_setopt($this->curl, CURLOPT_HTTPHEADER, $headers);
    }

    // returns text
    public function createTextRequest($prompt, $model = 'text-davinci-003', $temperature = 0.5, $maxTokens = 1000)
    {
        curl_reset($this->curl);
        $this->initialize('text');

        $this->data["model"] = $model;
        $this->data["prompt"] = $prompt;
        $this->data["temperature"] = $temperature;
        $this->data["max_tokens"] = $maxTokens;

        curl_setopt($this->curl, CURLOPT_POSTFIELDS, json_encode($this->data));

        $response = curl_exec($this->curl);
        $response = json_decode($response, true);
        return $response['choices'][0]['text'] ?? -1; // return text or -1 if error
    }

    // returns URL with the image
    public function generateImage($prompt, $imageSize = '512x512', $numberOfImages = 1)
    {
        curl_reset($this->curl);
        $this->initialize('image');

        $this->data["prompt"] = $prompt;
        $this->data["n"] = $numberOfImages;
        $this->data["size"] = $imageSize;

        curl_setopt($this->curl, CURLOPT_POSTFIELDS, json_encode($this->data));

        $response = curl_exec($this->curl);
        $response = json_decode($response, true);
        return $response['data'][0]['url'] ?? -1; //return the first url or -1 if error
    }
}

Create a Simple Chatbot Interface For OpenAI API

We will create a simple HTML interface to interact with the ChatGPT class we defined in the previous tutorial. The HTML file will allow users to input messages and receive responses from the ChatGPT model using AJAX calls to the PHP backend.

Step 1: Set Up the HTML File

Let’s create an HTML file named index.html and add the necessary HTML structure to create the chatbot interface.

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Chatbot with OpenAI</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/css/bootstrap.min.css">
</head>

<body>
    <div class="container mt-5">
        <div class="row justify-content-center">
            <div class="col-md-6">
                <div class="card">
                    <div class="card-header">Chatbot</div>
                    <div class="card-body" id="chat">
                        <div class="message">Hello! How can I assist you today?</div>
                    </div>
                    <div class="card-footer">
                        <input type="text" id="userInput" class="form-control" placeholder="Type your message...">
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script>
        // Your JavaScript code will be added here
    </script>
</body>

</html>

Step 2: Implement JavaScript for the Chatbot

We’ll now add JavaScript code to the <script> section in the HTML file to handle user interactions and communicate with the ChatGPT backend using AJAX.

<script>
    $(document).ready(function() {
        // Function to add a user message to the chat
        function addUserMessage(message) {
            $("#chat").append(`<div class="message bg-light">${message}</div>`);
        }

        // Function to add a bot message to the chat
        function addBotMessage(message) {
            $("#chat").append(`<div class="message">${message}</div>`);
        }

        // Function to send user input to the chatbot and get a response
        function sendMessage() {
            const userInput = $("#userInput").val();
            if (userInput.trim() === "") return;

            addUserMessage(userInput);
            $("#userInput").val("");

            // Make an AJAX request to the PHP script to get the bot response
            $.ajax({
                type: "POST",
                url: "chatbot.php", // Replace with the actual filename that contains the PHP code
                data: {
                    message: userInput
                },
                success: function(response) {
                    addBotMessage(response);
                },
                error: function(xhr, status, error) {
                    console.log("Error status: " + status);
                    console.log("Error message: " + error);
                    addBotMessage("An error occurred while communicating with the bot.");
                }
            });
        }

        // Send user input when pressing Enter key
        $("#userInput").keypress(function(event) {
            if (event.which == 13) {
                event.preventDefault();
                sendMessage();
            }
        });

        // Send user input when clicking the Send button (optional)
        // Add the id="sendBtn" attribute to the button in the HTML to enable this functionality
        $("#sendBtn").click(function() {
            sendMessage();
        });
    });
</script>

Complete Code For Index.html

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Chatbot with OpenAI</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/css/bootstrap.min.css">
</head>

<body>
    <div class="container mt-5">
        <div class="row justify-content-center">
            <div class="col-md-6">
                <div class="card">
                    <div class="card-header">Chatbot</div>
                    <div class="card-body" id="chat">
                        <div class="message">Hello! How can I assist you today?</div>
                    </div>
                    <div class="card-footer">
                        <input type="text" id="userInput" class="form-control" placeholder="Type your message...">
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script>
        $(document).ready(function() {
            // Function to add a user message to the chat
            function addUserMessage(message) {
                $("#chat").append(`<div class="message bg-light">${message}</div>`);
            }

            // Function to add a bot message to the chat
            function addBotMessage(message) {
                $("#chat").append(`<div class="message">${message}</div>`);
            }

            // Function to send user input to the chatbot and get a response
            function sendMessage() {
                const userInput = $("#userInput").val();
                if (userInput.trim() === "") return;

                addUserMessage(userInput);
                $("#userInput").val("");

                // Make an AJAX request to the PHP script to get the bot response
                $.ajax({
                    type: "POST",
                    url: "chatbot.php", // Replace with the actual filename that contains the PHP code
                    data: {
                        message: userInput
                    },
                    success: function(response) {
                        addBotMessage(response);
                    },
error: function(xhr, status, error) {
    console.log("Error status: " + status);
    console.log("Error message: " + error);
    addBotMessage("An error occurred while communicating with the bot.");
}
                });
            }

            // Send user input when pressing Enter key
            $("#userInput").keypress(function(event) {
                if (event.which == 13) {
                    event.preventDefault();
                    sendMessage();
                }
            });

            // Send user input when clicking the Send button
            $("#sendBtn").click(function() {
                sendMessage();
            });
        });
    </script>
</body>

</html>

Creating a PHP Backend for the Chatbot Interface

In this tutorial, we will create a PHP backend script that communicates with the OpenAI ChatGPT API using the ChatGPT class we defined in the previous tutorials. The PHP script will handle AJAX requests from the chatbot interface and return the bot’s response to the user’s input.

Step 1: Set Up the PHP File

Create a new PHP file named chatbot.php and add the following code to it:

<?php
// Step 1: Include the ChatGPT class
include_once('ChatGPT.php');

// Step 2: Create a new instance of the ChatGPT class
$chatbot = new ChatGPT();

// Step 3: Get the user input from the AJAX request
if (isset($_POST['message'])) {
    $userInput = $_POST['message'];

    // Step 4: Call the createTextRequest function to get the bot response
    $botResponse = $chatbot->createTextRequest($userInput);

    // Step 5: Return the bot response
    echo $botResponse;
}
?>

Step 2: Run the Application

With everything set up, access the index.html file through a web browser. When you type a message and press Enter or click the Send button, the JavaScript code in the HTML file will make an AJAX request to the chatbot.php backend. The backend will then communicate with the ChatGPT API, and the bot’s response will be displayed in the chat window.

And there you have it! You’ve successfully created a simple chatbot interface that interacts with the OpenAI ChatGPT API through a PHP backend. Users can now communicate with the chatbot and receive generated responses based on their inputs.

Related Articles

Related Articles

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Latest Articles