Image © 2023, Craiyon

Coding w/ OpenAI GPT-3 - Part I

Created on 2023-02-11 14:22

Published on 2023-02-12 04:14

I thought I would learn how to integrate OpenAI's GPT-3 engine via an Application Programming Interface (API), and document my progress, for anyone interested. I am not a programmer, and so I asked ChatGPT for assistance with the code, and I tweaked the results. The resulting tool can be useful for those working with and manipulating data.

This first part outlines setup of the system to include the web server where the HTML and PHP code will later be executed, to integrate with OpenAI's API. The second part begins the code setup. To use the PHP API code, you must get an API Key from OpenAI, which can be accomplished by 1) signing up here, and 2) visiting the OpenAI Key page, and 3) creating clicking "Create new secret key". Save the key and keep it secure.

Besides time, everything I used for this project was open source and no cost. I started with Ubuntu Server, and installed that on my VirtualBox which is on my Mac laptop. This provided me with the foundational operating system. I then installed Apache web server on that. You can of course install Apache directly on your computer, but I personally like the separation VirtualBox provides.

Once the operating system was up-and-running on VirtualBox, I updated it, restarted, and installed Apache (web server) and PHP. Here are the commands:

sudo apt-get update
sudo apt-get upgrade
sudo apt autoremove
sudo reboot

sudo apt-get install apache2
sudo systemctl enable apache2
sudo apt-get install php libapache2-mod-php
sudo apachectl restart

After this, I had a functional web server with PHP installed on my local Mac laptop [in VirtualBox]; however, Network Address Translation (NAT) was still required to be configured in VirtualBox, so that I could access the web server and SSH (remote terminal) from the host operating system (Windows or Mac, or whichever OS you're running VirtualBox from).

For the NATting, two settings are required in VirtualBox: one for HTTP and one for SSH:

Settings -> Network -> Adapter 1 -> "Attached to: NAT" -> Advanced
Select "Port Forwarding"
1) Name: SSH; Protocol: TCP; Host IP: 127.0.0.1; Host Port: 2222; Guest IP: {IP of guest server, usually 10.0.2.15}
2) Name: WWW; Protocol: TCP; Host IP: {blank}; Host Port: 8080; Guest IP: {IP of guest server, usually 10.0.2.15}
*Note, if this doesn't work, enter "ip a" at the command prompt, and search for an address near "inet"
Click OK to save.

You may need to restart the guest Ubuntu Server operating system for NAT to work. After, to test, you should be able to remotely connect via SSH using the command SSH {username}@127.0.0.2 -p 2222 from a Mac terminal window. SSH works better than simply using the VirtualBox terminal, since code can be copied/pasted from the host OS to the guest. Note, for Windows, see PuTTY.

After installing Apache, to test that the web server is functioning, browse from your host machine to http://127.0.0.1:8080 and you should be presented with the default Apache web server page.

Next, you will want to get familiar with the location of your web server's root folder, which is usually at /var/www/html/. This is where you will be working. You can get there by first SSH'ing to the server, signing-in, and typing cd /var/www/html. (CD stands for "change directory".) In that folder you should have the file index.html, which is the default file that is loaded up and processed by your browser when you visit the server. You should save the default file in case you need it later, by using the command cp index.html index.html.old. (CP stands for "copy".)

There are many different types of activities you can perform with OpenAI's API, and the possibilities can be found in OpenAI's API documentation. Some common processes are completing sentences, summarizing long statements, and comparing multiple statements/data. The capability I will be demonstrating is the comparison of two business processes for identifying similarities/differences and the rationale. In the future, as I continue researching and discovering more code, I would like to learn how to compare several business processes at a time with several others, such as for the purpose of mapping risk assessment frameworks and controls.

Next, the landing page is created. The HTML page that I pieced together allows the user to enter the two business processes, and those get passed to the PHP script, which in-turn appends an instruction for GPT-3 to compare the data. It then passes the entire prompt with the two processes to OpenAI via an API connection for processing. OpenAI acts on the prompt and provides the results back to the script, which presents it into the browser.

To begin creating the landing page, you will edit the index.html file in the web server root folder. Do this by changing directory to the root folder (cd /var/www/html) and typing sudo nano index.html. This will open up the nano editor. To clear out the existing HTML commands, move to the first line and press CTRL-K, which will delete each line individually. Another, easier approach is by deleting the index.html file entirely (sudo rm index.html) and by creating a new one (sudo nano index.html).

Next, you will enter the following code, or copy/paste, which prompts the user to enter two strings of information, later used for the comparison:

<html
<head>
  <title>Compare Two Business Processes</title>
</head>
<body>
  <h1>Compare Two Business Processes</h1>
  <form action="compare.php" method="post">
    <label for="text1">Enter first process:</label><br>
    <textarea id="text1" name="text1" rows="4" cols="50"></textarea><br><br>
    <label for="text2">Enter second process:</label><br>
    <textarea id="text2" name="text2" rows="4" cols="50"></textarea><br><br>
    <input type="submit" value="Submit">
  </form>
</body>
</html>>

This code creates a form with two text boxes, each one for entering business processes, and a button called "submit". It looks like this:

No alt text provided for this image

Once pressed, the Submit button passes (posts) the form data entered into the two boxes (text1 and text2) to the compare.php file.

Press CTRL-X, press "Y" [to save the modified buffer back to the index.html file], and ENTER to use the default filename (index.html), and exit the nano editor.

Next, the PHP code is written to the compare.php script. Create the file by typing sudo nano compare.php while in the same folder. The content for the compare.php file is shown below:

<?ph

// Your OpenAI API key
$apiKey = "<REPLACE WITH YOUR API KEY>";

// Get the text strings from the form inputs
$text1 = $_POST["text1"];
$text2 = $_POST["text2"];

// Set the API endpoint for the GPT engine
$url = "https://api.openai.com/v1/completions";

// Set the API request headers
$headers = array(
    "Content-Type: application/json",
    "Authorization: Bearer " . $apiKey
);

// Set the API request data
$data = array(
    "model" => "text-davinci-002",
    "prompt" => "Explain the similarity or difference between the following two business processes and provide rationale: " . >
    "max_tokens" => 100,
    "temperature" => 0.5,
    "top_p" => 0.5,
);

// Encode the API request data as JSON
$data = json_encode($data);

// Send the API request
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$response = curl_exec($ch);
curl_close($ch);

// Decode the API response
$response = json_decode($response, true);
$response1 = explode("%", $response["choices"][0]["text"])[0];

// Check for an error in the API response
if (array_key_exists("error", $response)) {
    echo "Error: " . $response["error"]["message"];
} else {
    // Extract the generated text from the API response
    $text = $response1

    //Display the generated text
    echo $text;
}

echo '<a href="index.html"><br><br>Return</a>';

?>

This code first sets up a few variables to include providing the API key which you obtained earlier from OpenAI's website. Next, it takes text1 and text2 (the data entered into the text boxes in the HTML page) and sets them as $text1 and $text2. The API endpoint is set to https://api.openai.com/v1/completions. The headers for the API connection are set, as well as the API configuration parameters (model, the prompt, etc.) More details about these parameters can be found on OpenAI's API documentation page listed above. And last, the PHP file sends the information to the OpenAI endpoint which parses the data and provides the results, which are stored in the variables $response and $response1. And last, this is displayed on the browser with the echo command.

Given the two business processes, "the business has a board-approved information security policy" and "the business reviews their firewall logs on a frequent basis", here are the results from GPT-3:

No alt text provided for this image

I hope you found this interesting and potentially useful. In the next part, I will modify the HTML and PHP code to accept CSV files as input, and have GPT-3 parse more data between the two files and provide more concise quantitative results.