In our previous tutorial, we have developed ChatBot with PHP, MySQL and AJAX. In this tutorial, we are going to develop AI ChatBot using ChatGPT and PHP.
In recent months, AI ChatBots created a lot of noise. Due to this, we have decided to develop a fully AI base ChatBot System using ChatGPT created by OpenAI.
Here we will develop a customer support and service ChatBot to allow to enter their queries to get replies automatically from Bot.
So let’s proceed with developing system. The file structure are:
- chatbot-chatgpt-php
- index.php
- fetch_data.php
- ChatBot.php
1. Design ChatBot Page
We will create index.php file and design our ChatBot page design by creating HTML. We will create message send area with an input and a button. We will also create section to list message and its repsonses.
<section class="section"> <div class="container"> <div class="columns box"> <div class="column"> <div class="columns"> <div class="column has-text-centered"> <h1 class="title"> Hello AI ChatBot! </h1> </div> </div> <div class="columns"> <div class="column"> <div class="card-content" style="height:600px;overflow:auto;flex-grow: 1;flex-shrink: 1;"> <div class="content messageHistory"> </div> </div> </div> </div> <div class="columns"> <div class="column"> <input class="input message" type="text" placeholder="Type your message"> </div> <div class="column is-narrow"> <button class="button is-info sendMessage"> Send </button> </div> </div> </div> </div> <div class="columns box is-hidden"> <div class="column result"></div> </div> <div class="columns box is-hidden"> <div class="column notification is-danger error has-text-centered"> </div> </div> </div> </section>
2. Make Query and List Responses
We will implement to make ajax request to fetch_data.php with user input message and get response from ChatGPT. We will list response under related query.
<script type="module"> window.addEventListener('load', (event) => { document.querySelector(".sendMessage").addEventListener('click', (event) => { event.currentTarget.classList.add('is-loading'); event.currentTarget.disabled = true; document.querySelector(".result").parentElement.classList.add("is-hidden"); document.querySelector(".error").parentElement.classList.add("is-hidden"); let currentHour = new Date(); const messageHTML = `<div class="columns"> <div class="column is-one-third"></div> <div class="column"> <div class="notification is-success"> <h6 class="subtitle is-6">${currentHour.getHours() + ":" + currentHour.getMinutes()}</h6> ${document.querySelector(".message").value} </div> </div> </div>` let chatBox = document.querySelector(".messageHistory"); chatBox.innerHTML += messageHTML; chatBox.scrollIntoView(false); const payload = JSON.stringify({ "message": document.querySelector(".message").value }); document.querySelector(".message").value = ""; fetch('fetch_data.php', { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: payload, }).then(response => response.json()) .then(data => { let currentHour = new Date(); data.responseMsg = data.responseMsg.replace("\n", "<br>"); let aiMsgTemplate = `<div class="columns"> <div class="column"> <div class="notification is-info"> <h6 class="subtitle is-6">${currentHour.getHours() + ":" + currentHour.getMinutes()}</h6> ${data.responseMsg} </div> </div> <div class="column is-one-third"></div> </div>` chatBox.innerHTML += aiMsgTemplate; chatBox.scrollIntoView(false); }) .catch((error) => { console.error('Error:', error); }).finally(() => { document.querySelector(".sendMessage").classList.remove('is-loading'); document.querySelector(".sendMessage").disabled = false; }); }); }); </script>
3. Implement To Send Message and Fetch Response
We will implement fetch_data.php to include ChatBot.php class. We will create object of this class and call method sendMessage() to send message to OpenAI endpoint to get return response.
<?php require("ChatBot.php"); $params = json_decode( file_get_contents("php://input"), true ); $ChatBot = new ChatBot(); $response = $ChatBot->sendMessage($params["message"]); $responseMsg = json_encode(array("responseMsg" => $response)); echo $responseMsg; exit;
4. Implement ChatBot
We will implement ChatBot.php class and define autohrization key and endpoint to OpenAI. We will define methid sendMessage() and handle functionality to make HTTP request to openAI with user input message and return response.
<?php class ChatBot { private $authorization; private $endpoint; public function __construct() { $this->authorization = 'OpenAI-APIKEY'; $this->endpoint = 'https://api.openai.com/v1/chat/completions'; } public function sendMessage(string $message): string { $data = [ 'messages' => [ [ 'role' => 'system', 'content' => 'Get answer for your queries.' ], [ 'role' => 'user', 'content' => $message ], ], 'model' => 'gpt-3.5-turbo' ]; $headers = [ 'Content-Type: application/json', 'Authorization: Bearer ' . $this->authorization, ]; $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $this->endpoint); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data)); curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $response = curl_exec($ch); if (curl_errno($ch)) { $error = curl_error($ch); curl_close($ch); throw new Exception('Error sending the message: ' . $error); } curl_close($ch); $result = json_decode($response, true); $responseContent = $result["choices"][0]["message"]["content"]; return $responseContent; } }