Integrate ChatGPT API to the Chatbot
By Webotapp Academy•
<!-- wp:paragraph -->\n<p>In this lecture we will discuss how to integrate chatgpt API to the chatbot</p>\n<!-- /wp:paragraph -->\n\n<!-- wp:heading -->\n<h2 class=\"wp-block-heading\">At first we will initialize a session</h2>\n<!-- /wp:heading -->\n\n<!-- wp:list {\"ordered\":true} -->\n<ol><!-- wp:list-item -->\n<li></li>\n<!-- /wp:list-item --></ol>\n<!-- /wp:list -->\n\n<!-- wp:list {\"ordered\":true} -->\n<ol><!-- wp:list-item -->\n<li></li>\n<!-- /wp:list-item --></ol>\n<!-- /wp:list -->\n\n<!-- wp:code -->\n<pre class=\"wp-block-code\"><code>session_start();\n\nif (!isset($_SESSION['conversation'])) {\n $_SESSION['conversation'] = array(\n array(\"role\" => \"system\", \"content\" => \"AI prompt here\")\n );\n}\n</code></pre>\n<!-- /wp:code -->\n\n<!-- wp:list -->\n<ul><!-- wp:list-item -->\n<li><strong>session_start()</strong>: Starts a new session or resumes an existing session. Sessions allow data to be stored across multiple page requests.</li>\n<!-- /wp:list-item -->\n\n<!-- wp:list-item -->\n<li><strong>$_SESSION['conversation']</strong>: This array stores the conversation history. It is initialized with a system message (AI prompt) if it doesn't already exist. The system message typically includes instructions for the AI on how to respond.</li>\n<!-- /wp:list-item --></ul>\n<!-- /wp:list -->\n\n<!-- wp:heading -->\n<h2 class=\"wp-block-heading\">Handling POST Requests</h2>\n<!-- /wp:heading -->\n\n<!-- wp:code -->\n<pre class=\"wp-block-code\"><code>if ($_SERVER['REQUEST_METHOD'] === 'POST') {\n $userMessage = $_POST['userMessage'];\n $_SESSION['conversation'][] = array(\"role\" => \"user\", \"content\" => $userMessage);\n\n $curl = curl_init();\n $payload = json_encode(array(\n \"model\" => \"gpt-4\",\n \"messages\" => $_SESSION['conversation']\n ));\n\n curl_setopt_array($curl, array(\n CURLOPT_URL => 'https://api.openai.com/v1/chat/completions',\n CURLOPT_RETURNTRANSFER => true,\n CURLOPT_ENCODING => '',\n CURLOPT_MAXREDIRS => 10,\n CURLOPT_TIMEOUT => 0,\n CURLOPT_FOLLOWLOCATION => true,\n CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,\n CURLOPT_CUSTOMREQUEST => 'POST',\n CURLOPT_POSTFIELDS => $payload,\n CURLOPT_HTTPHEADER => array(\n 'Content-Type: application/json',\n 'Authorization: Bearer sk-xxxxxxxxxxxxxxxxxxxx'\n ),\n ));\n\n $response = curl_exec($curl);\n curl_close($curl);\n\n $responseArray = json_decode($response, true);\n $assistantMessage = $responseArray['choices'][0]['message']['content'];\n $_SESSION['conversation'][] = array(\"role\" => \"assistant\", \"content\" => $assistantMessage);\n\n header('Content-Type: application/json');\n echo json_encode(array('message' => $assistantMessage));\n exit;\n}\n</code></pre>\n<!-- /wp:code -->\n\n<!-- wp:list -->\n<ul><!-- wp:list-item -->\n<li><strong>if ($_SERVER['REQUEST_METHOD'] === 'POST')</strong>: This block executes if the request method is POST.</li>\n<!-- /wp:list-item -->\n\n<!-- wp:list-item -->\n<li><strong>$userMessage = $_POST['userMessage']</strong>: Retrieves the user's message from the POST request.</li>\n<!-- /wp:list-item -->\n\n<!-- wp:list-item -->\n<li><strong>$_SESSION['conversation'][] = array(\"role\" => \"user\", \"content\" => $userMessage)</strong>: Adds the user's message to the session's conversation array.</li>\n<!-- /wp:list-item -->\n\n<!-- wp:list-item -->\n<li><strong>cURL Initialization and Configuration</strong>:<!-- wp:list -->\n<ul><!-- wp:list-item -->\n<li><strong>curl_init()</strong>: Initializes a new cURL session.<strong>$payload</strong>: Creates a JSON-encoded payload containing the model (\"gpt-4\") and the conversation history.<strong>curl_setopt_array($curl, array(...))</strong>: Sets various options for the cURL session:</li>\n<!-- /wp:list-item -->\n\n<!-- wp:list-item -->\n<li><strong>CURLOPT_URL</strong>: The URL to send the request to (OpenAI's chat completion endpoint).</li>\n<!-- /wp:list-item -->\n\n<!-- wp:list-item -->\n<li><strong>CURLOPT_RETURNTRANSFER</strong>: Indicates that the response should be returned as a string.</li>\n<!-- /wp:list-item -->\n\n<!-- wp:list-item -->\n<li><strong>CURLOPT_POSTFIELDS</strong>: The JSON payload to send in the POST request.</li>\n<!-- /wp:list-item -->\n\n<!-- wp:list-item -->\n<li><strong>CURLOPT_HTTPHEADER</strong>: Sets the request headers, including the authorization header with the API key.</li>\n<!-- /wp:list-item --></ul>\n<!-- /wp:list --></li>\n<!-- /wp:list-item -->\n\n<!-- wp:list-item -->\n<li><strong>$response = curl_exec($curl)</strong>: Executes the cURL session and stores the response.</li>\n<!-- /wp:list-item -->\n\n<!-- wp:list-item -->\n<li><strong>curl_close($curl)</strong>: Closes the cURL session.</li>\n<!-- /wp:list-item -->\n\n<!-- wp:list-item -->\n<li><strong>$responseArray = json_decode($response, true)</strong>: Decodes the JSON response from the API into an associative array.</li>\n<!-- /wp:list-item -->\n\n<!-- wp:list-item -->\n<li><strong>$assistantMessage = $responseArray['choices'][0]['message']['content']</strong>: Extracts the assistant's message from the response.</li>\n<!-- /wp:list-item -->\n\n<!-- wp:list-item -->\n<li><strong>$_SESSION['conversation'][] = array(\"role\" => \"assistant\", \"content\" => $assistantMessage)</strong>: Adds the assistant's message to the conversation array.</li>\n<!-- /wp:list-item -->\n\n<!-- wp:list-item -->\n<li><strong>header('Content-Type: application/json')</strong>: Sets the response content type to JSON.</li>\n<!-- /wp:list-item -->\n\n<!-- wp:list-item -->\n<li><strong>echo json_encode(array('message' => $assistantMessage))</strong>: Sends the assistant's message as a JSON response.</li>\n<!-- /wp:list-item -->\n\n<!-- wp:list-item -->\n<li><strong>exit</strong>: Terminates the script execution.</li>\n<!-- /wp:list-item --></ul>\n<!-- /wp:list -->\n\n<!-- wp:heading -->\n<h2 class=\"wp-block-heading\">Displaying the Conversation</h2>\n<!-- /wp:heading -->\n\n<!-- wp:code -->\n<pre class=\"wp-block-code\"><code>$conversation = $_SESSION['conversation'] ?? array();\n</code></pre>\n<!-- /wp:code -->\n\n<!-- wp:paragraph -->\n<p>Retrieves the conversation history from the session. If the session variable does not exist, it initializes an empty array.</p>\n<!-- /wp:paragraph -->\n\n<!-- wp:heading -->\n<h2 class=\"wp-block-heading\">Complete PHP Code</h2>\n<!-- /wp:heading -->\n\n<!-- wp:code -->\n<pre class=\"wp-block-code\"><code><?php\nsession_start();\n\n\n\nif (!isset($_SESSION['conversation'])) {\n $_SESSION['conversation'] = array(\n array(\"role\" => \"system\", \"content\" => \"AI prompt here\")\n );\n}\n\nif ($_SERVER['REQUEST_METHOD'] === 'POST') {\n $userMessage = $_POST['userMessage'];\n $_SESSION['conversation'][] = array(\"role\" => \"user\", \"content\" => $userMessage);\n\n $curl = curl_init();\n $payload = json_encode(array(\n \"model\" => \"gpt-4\",\n \"messages\" => $_SESSION['conversation']\n ));\n\n curl_setopt_array($curl, array(\n CURLOPT_URL => 'https://api.openai.com/v1/chat/completions',\n CURLOPT_RETURNTRANSFER => true,\n CURLOPT_ENCODING => '',\n CURLOPT_MAXREDIRS => 10,\n CURLOPT_TIMEOUT => 0,\n CURLOPT_FOLLOWLOCATION => true,\n CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,\n CURLOPT_CUSTOMREQUEST => 'POST',\n CURLOPT_POSTFIELDS => $payload,\n CURLOPT_HTTPHEADER => array(\n 'Content-Type: application/json',\n 'Authorization: Bearer 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'\n ),\n ));\n\n $response = curl_exec($curl);\n curl_close($curl);\n\n $responseArray = json_decode($response, true);\n $assistantMessage = $responseArray['choices'][0]['message']['content'];\n $_SESSION['conversation'][] = array(\"role\" => \"assistant\", \"content\" => $assistantMessage);\n\n header('Content-Type: application/json');\n echo json_encode(array('message' => $assistantMessage));\n exit;\n}\n\n$conversation = $_SESSION['conversation'] ?? array();\n?>\n</code></pre>\n<!-- /wp:code -->\n\n<!-- wp:heading -->\n<h2 class=\"wp-block-heading\">Add the Javascript event listener to the chat form that triggers when the form is submitted</h2>\n<!-- /wp:heading -->\n\n<!-- wp:code -->\n<pre class=\"wp-block-code\"><code>document.getElementById('chat-form').addEventListener('submit', function(e) {\n e.preventDefault(); // Prevent the default form submission\n handleSubmit();\n });\n</code></pre>\n<!-- /wp:code -->\n\n<!-- wp:heading -->\n<h2 class=\"wp-block-heading\">Complete Code of the Chatbot</h2>\n<!-- /wp:heading -->\n\n<!-- wp:code -->\n<pre class=\"wp-block-code\"><code> \n\n<?php\nsession_start();\n\n\n\nif (!isset($_SESSION['conversation'])) {\n $_SESSION['conversation'] = array(\n array(\"role\" => \"system\", \"content\" => \"AI prompt here\")\n );\n}\n\nif ($_SERVER['REQUEST_METHOD'] === 'POST') {\n $userMessage = $_POST['userMessage'];\n $_SESSION['conversation'][] = array(\"role\" => \"user\", \"content\" => $userMessage);\n\n $curl = curl_init();\n $payload = json_encode(array(\n \"model\" => \"gpt-4\",\n \"messages\" => $_SESSION['conversation']\n ));\n\n curl_setopt_array($curl, array(\n CURLOPT_URL => 'https://api.openai.com/v1/chat/completions',\n CURLOPT_RETURNTRANSFER => true,\n CURLOPT_ENCODING => '',\n CURLOPT_MAXREDIRS => 10,\n CURLOPT_TIMEOUT => 0,\n CURLOPT_FOLLOWLOCATION => true,\n CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,\n CURLOPT_CUSTOMREQUEST => 'POST',\n CURLOPT_POSTFIELDS => $payload,\n CURLOPT_HTTPHEADER => array(\n 'Content-Type: application/json',\n 'Authorization: Bearer sk-xxxxxxxxxxxxxxxxxx'\n ),\n ));\n\n $response = curl_exec($curl);\n curl_close($curl);\n\n $responseArray = json_decode($response, true);\n $assistantMessage = $responseArray['choices'][0]['message']['content'];\n $_SESSION['conversation'][] = array(\"role\" => \"assistant\", \"content\" => $assistantMessage);\n\n header('Content-Type: application/json');\n echo json_encode(array('message' => $assistantMessage));\n exit;\n}\n\n$conversation = $_SESSION['conversation'] ?? array();\n?>\n\n\n<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n <meta charset=\"UTF-8\">\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n <title>Chat with Panda AI</title>\n\n <link rel=\"stylesheet\" href=\"https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.2/css/all.min.css\" integrity=\"sha512-z3gLpd7yknf1YoNbCzqRKc4qyor8gaKU1qmn+CShxbuBusANI9QpRohGBreCFkKxLhei6S9CQXFEbbKuqLg0DA==\" crossorigin=\"anonymous\" referrerpolicy=\"no-referrer\" />\n\n <script src=\"https://code.responsivevoice.org/responsivevoice.js\"></script>\n\n\n\n <style>\n body {\n font-family: Arial, sans-serif;\n background-color: #f0f0f0;\n margin: 0;\n padding: 0;\n }\n .chat-container {\n max-width: 400px;\n margin: 20px auto;\n background-color: #fff;\n border-radius: 10px;\n box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);\n }\n .chat-header {\n background-color: #9c27b0; /* Purple color */\n color: #fff;\n padding: 10px;\n text-align: center;\n font-weight: bold;\n border-top-left-radius: 10px;\n border-top-right-radius: 10px;\n }\n .chat-messages {\n padding: 10px;\n max-height: 400px;\n overflow-y: auto;\n }\n .message {\n margin: 10px 0;\n padding: 10px;\n border-radius: 10px;\n }\n .message.user {\n background-color: #f3e5f5; /* Light purple color */\n text-align: right;\n }\n .message.assistant {\n background-color: #ececec;\n }\n .chat-input {\n display: flex;\n padding: 10px;\n background-color: #f3e5f5; /* Light purple color */\n border-top: 1px solid #e1bee7; /* Border color */\n }\n .chat-input input {\n flex-grow: 1;\n padding: 10px;\n border: 1px solid #e1bee7; /* Border color */\n border-radius: 20px; /* Rounded corners */\n margin-right: 10px;\n outline: none; /* Remove default outline */\n font-size: 16px; /* Font size */\n }\n .chat-input input:focus {\n border-color: #9c27b0; /* Purple color when focused */\n }\n .chat-input button {\n padding: 10px 20px;\n background-color: #9c27b0; /* Purple color */\n color: #fff;\n border: none;\n border-radius: 20px; /* Rounded corners */\n cursor: pointer;\n font-size: 16px; /* Font size */\n outline: none; /* Remove default outline */\n transition: background-color 0.3s; /* Transition effect */\n }\n .chat-input button:hover {\n background-color: #7b1fa2; /* Darker purple color when hovered */\n }\n </style>\n</head>\n<body>\n <div class=\"chat-container\">\n <div class=\"chat-header\">Chat with Panda AI</div>\n <div class=\"chat-messages\" id=\"chat-messages\">\n <?php foreach ($conversation as $message): ?>\n <?php if ($message['role'] !== 'system'): ?>\n <div class=\"message <?php echo $message['role']; ?>\">\n <?php echo $message['content']; ?>\n </div>\n <?php endif; ?>\n <?php endforeach; ?>\n </div>\n <form id=\"chat-form\" class=\"chat-input\" method=\"POST\">\n <select id=\"language\" class=\"chat-input input\">\n <option value=\"en-US\">English</option>\n <option value=\"hi-IN\">Hindi</option>\n \n <!-- Add more options as needed -->\n </select>\n \n\n <button type=\"button\" id=\"voice-button\" onmousedown=\"startRecording()\" onmouseup=\"stopRecording()\"><i class=\"fa-solid fa-microphone\"></i></button>\n\n\n <input type=\"text\" class=\"chat-input\" name=\"userMessage\" id=\"userMessage\" placeholder=\"Type your message or speak...\" required>\n <button type=\"submit\"><i class=\"fa-regular fa-paper-plane\"></i></button>\n </form>\n </div>\n <script>\n var recognition = new (window.SpeechRecognition || window.webkitSpeechRecognition || window.mozSpeechRecognition || window.msSpeechRecognition)();\n recognition.lang = 'en-US'; // Default language\n recognition.interimResults = false;\n recognition.maxAlternatives = 1;\n\n document.getElementById('language').addEventListener('change', function() {\n recognition.lang = this.value;\n });\n\n function startRecording() {\n console.log('Start recording');\n recognition.start();\n }\n\n function stopRecording() {\n console.log('Stop recording');\n recognition.stop();\n }\n\n recognition.onresult = function(event) {\n var speechResult = event.results[0][0].transcript;\n console.log('Recognition result:', speechResult);\n document.getElementById('userMessage').value = speechResult;\n\n // Call the function that handles the form submission\n handleSubmit();\n };\n\n function handleSubmit() {\n var userMessage = document.getElementById('userMessage').value;\n if (!userMessage) return; // Prevent empty submissions\n var chatMessages = document.getElementById('chat-messages');\n\n var userDiv = document.createElement('div');\n userDiv.className = 'message user';\n userDiv.textContent = userMessage;\n chatMessages.appendChild(userDiv);\n\n // Use fetch to send the POST request\n fetch('', {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/x-www-form-urlencoded',\n },\n body: 'userMessage=' + encodeURIComponent(userMessage)\n })\n .then(response => response.json())\n .then(data => {\n var assistantDiv = document.createElement('div');\n assistantDiv.className = 'message assistant';\n assistantDiv.innerHTML = data.message.replace(/\\n/g, '<br>'); // Replace line breaks with <br> tags\n chatMessages.appendChild(assistantDiv);\n\n // Speak the assistant's response using ResponsiveVoice\n \n responsiveVoice.speak(data.message, \"Hindi Male\"); // You can change the voice as needed\n\n\n // Scroll to the bottom of the chat messages container\n chatMessages.scrollTop = chatMessages.scrollHeight;\n });\n document.getElementById('userMessage').value = '';\n }\n\n document.getElementById('chat-form').addEventListener('submit', function(e) {\n e.preventDefault(); // Prevent the default form submission\n handleSubmit();\n });\n\n </script>\n</body>\n</html>\n</code></pre>\n<!-- /wp:code -->