PHP Classes

File: chatbot.php

Recommend this page to a friend!
  Classes of Ahmed Abdulla   PHP ChatGPT Client   chatbot.php   Download  
File: chatbot.php
Role: Application script
Content type: text/plain
Description: integration with the ChatGPT API.
Class: PHP ChatGPT Client
Use ChatGPT API to interact with ChatGPT
Author: By
Last change: update code
Date: 9 months ago
Size: 1,861 bytes
 

Contents

Class file image Download
<?php
//error_reporting(E_ALL);
//ini_set('display_errors', 1);
session_start();

function
getBotResponse($userMessage) {

 
   
$apiKey = "Enter the Key";
   
$selectedLanguage = isset($_SESSION['lang']) ? $_SESSION['lang'] : 'ar';
   
       
// Set the appropriate title based on the selected language
       
if ($selectedLanguage === 'en') {
           
$prompt = "Please find the answer from the next paragraph for ".$userMessage." and if there is link please provided it \n\n";
           } else {
            
$prompt = "Please find the answer in briefly And translate it into Arabic from the next paragraph for ".$userMessage."\n\n";
        }

// To update
$prompt = $prompt."Please add the paragraph that the system will search within here.";
      

           
$url = 'https://api.openai.com/v1/chat/completions';

           
$data = [
               
'model' => 'gpt-3.5-turbo',
               
'messages' => [
                    [
'role' => 'user', 'content' => $prompt]
                ],
               
'temperature' => 0.7
           
];

           
$payload = json_encode($data);

           
$ch = curl_init($url);
           
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
           
curl_setopt($ch, CURLOPT_POST, true);
           
curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
           
curl_setopt($ch, CURLOPT_HTTPHEADER, [
               
'Content-Type: application/json',
               
'Authorization: Bearer ' . $apiKey
           
]);

           
$result = curl_exec($ch);

            if (
curl_errno($ch)) {
               
//echo 'Error: ' . curl_error($ch);
           
} else {
               
//return $result;
               
$data = json_decode($result, true);
               
$content = $data['choices'][0]['message']['content'];
                return
$content;
            }

           
curl_close($ch);



   
}

if (isset(
$_POST['user-message'])) {
   
$userMessage = $_POST['user-message'];
   
$botResponse = getBotResponse($userMessage);

    echo
$botResponse;
} else {
    echo
"No user message received.";
}

?>