ChatGPT 3.5 Turbo PHP Script with Memory

ChatGPT 3.5 Turbo (gpt-3.5-turbo) PHP Script with Memory is a powerful learning tool that can greatly enhance your knowledge of OpenAI. It uses advanced machine learning algorithms to provide natural language processing capabilities, allowing it to understand and respond to user queries in a more human-like way.

To make this tutorial even more interesting I have added the ability to place the prompt return text into CKeditor. Keep in mind that this is just a basic implementation of CKEditor I welcome you to make your own modifications and improve upon this script.

Here is a screenshot for those wishing to see it visually:

I added some forms at the bottom as experimental. You do not have to use them it’s only a proof of concept and I encourage you to make them better.

There is also a test-mode that allows you to see what is going on behind the scene. Here is a screenshot when using in test-mode:

Additionally, there is an added memory feature allows the script to learn from previous interactions and improve its responses over time. You can set desired value of how many past conversations that OpenAI remembers. Unfortunately, after many searches of the official OpenAI documentation I cannot find the MAX allowed value. I tested with up to “10” and all seemed to work fine.

I am only covering the basics and highly encourage you to explore the OpenAI docs for more detailed information.

What you need:

  1. Ability to run PHP
  2. Method (FTP) to upload the PHP script
  3. Your OpenAI API key
  4. Text editor to change values in PHP script

The PHP script can be downloaded below but recommend you follow this simple setup tutorial first.

There are only two vales that need to be changed to test ther ChatGPT 3.5 Turbo (gpt-3.5-turbo) PHP Script with Memory.

  1. Add your OpenAI API key
  2. Choose how many conversations to remember

Here is the PHP script (also link to download below):

<?php
/* 
OpenAI chat with a short-term memory uses the gpt-3.5-turbo language model
By Steve Attewell https://twitter.com/steveattewell
Additional funtions and html added by @ https://terryjett.com

Call this file like this: 
chatgpt-turbo.php?text=what is html5
chatgpt-turbo.php?forget=true&text=what is html5
chatgpt-turbo.php?testmode=true&text=what is html5

Calling ?forget=true to make the AI forget your previous responses before answering

WARNING: HIGHLY ADVISE ADDING PROTEXTION TO PREVENT OTHERS FROM FINDING/USING THIS PHP PAGE. People could use this to drain your OpenAI account!

*/

//Start a session and make sure the user has come from this website

session_start();
$testmode = isset($_GET['testmode']) ? $_GET['testmode'] : null;
$forget = isset($_GET['forget']) ? $_GET['forget'] : null;
if($forget){
  // forget the previous interactions
    $_SESSION['conversations'] = null;
    echo "<br>";
	echo '<div style="text-align:center;"><div style="display:inline-block;max-width:95%;width: 100%;">';
	echo "<h4>Previous Requests Forgotten</h4>";
	echo "</div></div>";
}

// SETUP VARIABLES:
// ===================================

$openai_api_key = 'sk-REPLACE-WITH-YOUR-OPENAI-API-kEY';
// Get your OpenAI API key. Get one from https://platform.openai.com/

$number_of_interactions_to_remember = 5; 
// Gan be 0. Basically a "short term memory". Remembers the last n interactions. Allow you to ask follow-up questions like "tell me more about that" or "give me another example". Not positive on the maximum imposed by OpenAI

// ===================================

if (isset($_POST['text'])) {
    $text = $_POST['text'];
} else 
	if (isset($_POST['forget'])) {
    $text = $_POST['forget'];
} else {
$text = isset($_GET['text']) ? $_GET['text'] : null;
}
if($text){

	//Detect if there is some mention of date or time in the text:
    // Define the keywords to search for
    $keywords = array('time', 'date', 'day is it');

    // Check if the text contains any of the keywords
    $containsKeyword = false;
    $regex = '/\b(' . implode('|', $keywords) . ')\b/i';
    $containsKeyword = preg_match($regex, $text);
    
    // Define getDateTime() to prevent errors
	function getDateTime() {
    return date('Y-m-d H:i:s');
	}
	
	// If the text contains a keyword, call the getWeather() function
    if ($containsKeyword) {
        $datetime = getDateTime(); 
        $text = "It is " . $datetime . ". If appropriate, respond to 
        the following in a short sentence: " . $text;
    }

  // Set up a session variable to store (on remote server) the last n questions and responses
  if (!isset($_SESSION['conversations'])) {
    $_SESSION['conversations'] = array();
  }

  // Remove oldest conversation if the number oif interactions >= $number_of_interactions_to_remember 
  if (count($_SESSION['conversations']) > $number_of_interactions_to_remember + 1) {
    $_SESSION['conversations'] = array_slice($_SESSION['conversations'], -$number_of_interactions_to_remember, $number_of_interactions_to_remember, true);
  }

  // This is the main call we'll send to OpenAI
  $data = array(
    'model' => 'gpt-3.5-turbo',
    'messages' => array(
      array(
        'role' => 'system',
        'content' => 'You are called Chatty McChatface. 
        You give short, friendly reponses. '
      )
    )
  );

  // Adding to the call above, poke in the last 10 message history into the prompt we'll send to openAI
  foreach ($_SESSION['conversations'] as $conversation) {
    foreach ($conversation as $message) {
      array_push($data['messages'], array(
        'role' => $message['role'],
        'content' => $message['content']
      ));
    }
  }

  // Finally add the latest text from the user to the prompt we'll send to openAI chat gpt-3.5-turbo
  array_push($data['messages'], array(
    'role' => 'user',
    'content' => $text
  ));

// make the call to the OpenAI API
  $curl = curl_init();

  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 => json_encode($data),
    CURLOPT_HTTPHEADER => array(
      'Authorization: Bearer ' . $openai_api_key,
      'Content-Type: application/json'
    ),
  ));

  $response = curl_exec($curl);
	
 //test mode ?testmode=true&text=
 
  if($testmode){
    //write out the previous conversation
    echo "<br><br>";
	echo '<div style="text-align:center;"><div style="display:inline-block;max-width:95%;width: 100%;">';
	echo "<h3>Last  $number_of_interactions_to_remember Raw Responses</h3>";
	echo '<textarea style="width:100%;height:200px;">';
	echo json_encode($data);
	echo '</textarea>';
    //write out the latest response
	echo "<br><br>";
	echo '<h3>Current Raw Prompt Response</h3>';
    echo '<textarea style="width:100%;height:200px;">';
	echo $response;
	echo '</textarea>';
	echo '</div></div><br>';
  }
  $response = json_decode($response, true);
  
  curl_close($curl);

  if (isset($response['choices'][0]['message']['content'])) {
    // The key exists, do something here
    $content = $response['choices'][0]['message']['content'];
  } else {
      // The key doesn't exist
      $content = "Something went wrong! ```" . json_encode($response) . "```";
  }

  // Add new conversation to end of the conversation array (we'll use this in the next prompt so that the AI has a short term memory of our last 10 interactions)
  
  //Make a note of the questions we were just asked, and the response we got back from OpenAI
  $new_conversation = array(
    array(
      'role' => 'user',
      'content' => $text
    ),
    array(
      'role' => 'assistant',
      'content' => $content
    )
  );

  //And push that into our "memory" of the last few interactions (dictated by $number_of_interactions_to_remember ).
  array_push($_SESSION['conversations'], $new_conversation);

  //echo $content;
}
 //the below html can be completely removed and the above echo $content used
?><!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>OpenAI to CKEditor with Memory</title>
	<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootswatch/5.2.3/flatly/bootstrap.min.css" integrity="sha512-q+Sm01IL0q3keoeZkh7cHh6CcUGU0LVwFIf9Il4utcw0oC2MH9mpATEyvuh6dbzDiV8Pw4CXlsT7O1zXFc0LwQ==" crossorigin="anonymous" referrerpolicy="no-referrer" />
    <script src="//cdn.ckeditor.com/4.16.1/standard/ckeditor.js"></script>
</head>
<body>
<nav class="navbar bg-light" style="margin-bottom:25px;">
  <div class="container-fluid">
    <a class="navbar-brand" href="https://terryjett.com" target="_blank">ChatGPT gpt-3.5-turbo Example</a>
  </div>
</nav>
<div class="container">
    <h2>Displayed in a CKeditor textarea:</h2>
	<form method="post">
        <textarea id="grabdata" name="editor1">
		<?php
		echo '<pre>';
		echo $content;
		echo '</pre>';
		?>
		</textarea>
        <script>
            CKEDITOR.replace('editor1');
        </script>
    </form>
	<br>
	<h2>Displayed in a plain textarea:</h2>
	<?php
		echo '<textarea id="output" spellcheck="false" style="width:100%;height:300px;" id="copy_text" class="autoExpand alert alert-primary">';
		echo htmlspecialchars($content. "\n");
		echo '</textarea>';
	  ?>
</div>
<br><br>

<!--
Form is experimental and only for proof of concept
I encourage you to make it better!
-->

<div class="container">
	<form>
	  <div class="mb-3">
		<label for="text" class="form-label">Question</label>
		<input type="text" class="form-control" id="text" name="text">
	  </div>
	  <button type="submit" class="btn btn-primary">Submit</button>
	</form>
	<br>
</div>

<div class="container">
	<form>
	  <div class="mb-3">
		<label for="forget" class="form-label">Forget</label>
		<input type="text" class="form-control" id="forget" name="forget" aria-describedby="fogetLast" placeholder"">
		<div id="forgotHelp" class="form-text">Only use to forget last question/response</div>
		<button type="submit" class="btn btn-primary">Submit</button>
	</form>
	<br>
</body>
</html>

That sums this tutorial up. Thanks for visiting!

ChatGPT 3.5 Turbo PHP Script with Memory

ChatGPT 3.5 Turbo PHP Script with Memory

Disclaimer:

Before putting any type of code or advice into production from this site, you should consult a professional. The code and advice here is for educational purposes only. It is your responsibility to ensure code safety.

Rate for Encouragement
[Total: 6 Average: 5]