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