Working with the ChatGPT API: Putting & Getting Data in PHP

February 21, 2024
ChatGPT, Developers
LinkedInTwitterFacebookEmail

If you’re interested in using ChatGPT’s API using PHP, this is the article for you!

I’ll walk you through the requirements to create this in a simple way using procedural programming, but coming up with a prompt that will get you what you want – that’s on you!

Integrating with WordPress

Not in WordPress? Skip to the next step. If you’re going to add this into a WordPress site, I’d recommend putting this into a plugin. If you haven’t created a plugin before, or you’d like a cheat sheet, here’s the steps:

  1. create a folder in your plugins folder with a name of your plugin (no spaces)
  2. create a php file under that folder and add the following code:
/*
Plugin Name: AI API
Plugin URI: https://whitefoxcreative.com
Description: Custom API Connections
Version: 1.0
Author: https://whitefoxcreative.com
Author URI: https://whitefoxcreative.com/
License: GPLv2 or later
License URI: https://www.gnu.org/licenses/gpl-2.0.html
Text Domain: foxapi
*/

Primary Function

Our first function we create will be the one we call.

function newProject($content, $model, $type, $ID){
}

$content: REQUIRED. This variable should include all the changing data that you’ll be passing to ChatGPT. This is not the entire prompt, just the variable items of the prompt. I would create this as a variable with each item being the unique data being passed.

$model: REQUIRED. This is the model of the API you want to use. Different ones have different limitations. You can review on the Models page. The one you’ll pass here is under the “model” column as you scroll down the page. For example, you’d set this variable as “gpt-4-0125-preview”. See below for the overview of the models

$type: if you have multiple prompts, you can use this variable to distinguish between the prompts, while using the same function. You can leave this out if you only need one prompt.

$ID: If you need to get information from a custom post type, you can pass the $ID of the post here.

Quick Overview of How Models work

Each model has it’s limitations, with more recent ones getting better responses since they’re more developed. The model name is what you’ll use in the function above. The description gets you some information about this model. The training data says what information it has access to, since ChatGPT cannot search the internet live.

The most important item you’ll need to know is the token amount. Tokens are a little confusing, so it’s best to test with the amount you’re trying to use to make sure there are enough tokens. If you don’t have enough to run the prompt, it will return an error, so make sure you’ve considered what you want. Also, pricing on the Open AI system is done per token number.

Roughly, 100 tokens is about 75 words. You can go more in-depth on openAI documentation token article.

Filling in the Function: API Key

Before you continue, you’ll need an API key:

$api_key = 'key-goes-here';

To get one, you’ll need to sign up for an account with Open AI. You can log in or sign up here: https://openai.com/

Once you have an account, you can log in and choose the API option.

Navigate to the API keys: https://platform.openai.com/api-keys, and create a new API key. If you have more than one default organization, make sure the right one is chosen below.

API Keys

Creating the Prompt Function

The next step is to compile the data to connect to the API with. This step I split into a separate function, so each prompt can be handled separately.

One Prompt:

$data = promptFunction($model, $content);

Multiple Prompts:

if ($type == 'panda'){
$data = promptFunction_pan($model, $content);
} else if ($type == 'puppy'){
$data = promptFunction_pup($model, $content);
}

This way we’re putting the content together and then we’ll send it to the API in completed form.

function participant_overview($model, $datas){
	$data = array(
		'model' => $model,
		'messages' => array(
		        array('role' => 'system', 'content' => 'What do you think about ' . $datas['animal'] . '?' ),
		),
		'max_tokens' => 4000,
		'temperature' => .7,
	);
	return $data; 
}

This function puts together the variables we passed in the array $content into one string for the prompt. The prompt will be help inside of the $data[‘messages’][‘content’] variable, as seen above.

Tokens: We include the max tokens, which includes not just what Open AI returns, but what we put into the system. You can review pricing on the Open AI system. So your content here will count towards the tokens, as will the AI’s response. If you don’t include enough for the AI to do it’s job, it will return an error. More tokens means it will take slightly longer, and keep in mind each model has it’s own token upper limit. You can review them here: Models page.

Temperature: This indicates whether we want predictability or novelty/creativity in the results. The closer to 0, the more predictable the results will be. The closer to 1, the more creative the response will be.

Create one of these functions for each separate prompt.

API Connection

This is the final function newProject, with everything include. DON’T FORGET: You need the Creating the Prompt Function above in addition to this function

function newProject($content, $model, $type, $ID){
$api_key = 'key-goes-here';
$data = promptFunction($model, $content); //function is found above - see title "Creating the Prompt Function"
$ch = curl_init('https://api.openai.com/v1/chat/completions');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Authorization: Bearer ' . $api_key,
'Content-Type: application/json'
));
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
$response = curl_exec($ch);
curl_close($ch);
if ($response === false) {
echo 'Error: ' . curl_error($ch);
} else {
$decodedResponse = json_decode($response, true);
if ( !array_key_exists('error', $decodedResponse) ){
$decodedResponse = json_decode($decodedResponse['choices'][0]['message']['content']);
}
}
return $decodedResponse;
}

Running the Function

When you run the function, you then provide this:

$content = array('animal' => 'dogs');
$model = 'gpt-4-0125-preview';
$type = '';
$ID = '';
$project = newProject($content, $model, $type, $ID)
echo $project; 

This should return something like this from our prompt, “what do you think about dogs?“:

“Dogs are amazing animals! They’re known as humans’ best friends for a reason. Dogs are loyal, loving, and great companions. They come in all shapes, sizes, and personalities, which makes them unique and special. Many people enjoy having dogs as pets because they bring joy and happiness into their lives. Plus, dogs are often very playful and can be trained to do all sorts of tricks and tasks. Overall, dogs are wonderful creatures that make the world a better place with their presence.”

Summary

That’s it! Two simple functions can allow you to interact with AI.

Good luck on your API journey, and please don’t help it take over the world!

Join the Discussion

Your email address will not be published.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>