Integrate ChatGPT API to the Chatbot
By Webotapp Academy•Published: •Updated:
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
"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
"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();
?>
Chat with Panda AI
Chat with Panda AI
Exclusive Discount Offer
Inquire for Course Fee & Discounts
Get full program details, syllabus breakdown, and claim your exclusive course fee discount for the Best Digital Marketing Course in Guwahati.