Open Menu dzosoft
Close Menu dzosoft

   ALL ABOUT COMPUTER SCIENCE AND TECHNOLOGY


                             




Release your testosterone and observe the extreme increase in muscle mass.

Publish perfectly-optimized content in 1-click









 
 
 

How to use ChatGPT with PHP

 
 
How to use ChatGPT with PHP
 
Let's create a simple PHP language application that queries the GPT generative model through the OpenAI API

 

● Application requirements

 
Below is a brief list of the tools that will be used to carry out the project.

 

● API key and Organization ID

 
In addition to a PHP-based development environment, we need OpenAI API keys for our application. The procedure for requesting one is present in this part of the guide and is very simple. Again it bears repeating that the service provides a free $18 credit for testing its programming interfaces. If the same API Key is used by multiple organizations, it is also useful to specify the ID of the organization that intends to use it. This information is available by accessing your account from this page , and then following the menu path "Personal > Manage Account > Settings".

 
How to use ChatGPT with PHP
 

 
Source: https://platform.openai.com/account/api-keys 

 

● Libraries and templates

 

There are several PHP libraries that allow you to interact with OpenAI programming interfaces, just mention Orhanerday's OpenAI API Client available through GitHub and installable with Composer . In this case, however, we will only use vanilla code and the native syntax of the language, without resorting to pre-packaged frameworks or clients.

Another important point concerns the choice of the model to be interrogated. The latter affects several factors including the speed with which the outputs are generated, their level of accuracy and the cost for using the APIs. There are also templates developed for special purposes, such as Whisper for converting audio to text. In the application we will use a model from the GPT-3.5 set and specifically gpt-3.5-turbo.

The latter supports up to 4,096 tokens and has been trained with data updated to September 2021. To interact with it we will use the Open Source library cURL . It allows you to communicate with external services via network protocols, including those that require authentication. If you are running from Linux, for example on Mint , the PHP extension for cURL may not be installed by default. The problem can be solved by updating the packages present in the system:

sudo apt update


To then install the cURL library from the command line using the instruction:
sudo apt install curl


The success of the operation can be verified by running the command curl. For PHP to use the library, however, it is necessary to enable the relative extension in the configuration file php.ini. So let's open it with our favorite editor and uncomment the corresponding line:

 
How to use ChatGPT with PHP
 

Save the change and restart the Web server in use, for example Apache :

sudo service apache2 restart


In this way we will have everything we need to complete our project.


 

● The code

 

The first part of the application must be dedicated to the definition of all the useful data for communication with the platform. As anticipated, among the latter there are the OpenAI API key, the Organization ID (which is an optional data but useful if you manage multiple projects between different entities that belong to a single account) and the reference GPT model (or "engine"). To these is added the URL for calling the APIs which allows you to interact with the model through the latter.

//API KEY for authentication
$api_key = "sk-?????????????????????????";
//Service URL
$url = 'https://api.openai.com/v1/chat/completions';
// Organization ID
$org_id = ""; 
// Generative model to use
$model = "gpt-3.5-turbo";


In the second part of the code the API key and the Organization ID are passed as values ​​for the header parameters.

$headers = array(
    "Authorization: Bearer {$api_key}",
    "OpenAI-Organization: {$org_id}",
    "Content-Type: application/json"
);


The most interesting part of this step is about the header "Content-Type: application/json". It indicates that the HTTP request body leverages JSON ( JavaScript Object Notation ) for the data. This format is used for the interchange of information between web applications and offers a structured representation. "Content-Type: application/json"therefore it defines the type of message content and allows servers and clients to correctly process the data contained in the message body.

 

● Sending the message to the chatbot

 

Once the headers have been defined, we move on to setting the message ( prompt ) to be sent to the chatbot, i.e. any type of question ( content) from the user to which the system can respond in colloquial language.

$question="";
if(isset($_REQUEST["question"]))
 {
  $question=$_REQUEST["question"];
 }

// Request to the chatbot $messages = array(); $messages[] = array("role" => "user", "content" => $question);


The message is stored in an array ( $messages) which in turn becomes part of a multidimensional array ( $data) intended to contain the parameters for returning the output. In $data, in addition to the message we therefore have the previously indicated model ( $model = "gpt-3.5-turbo";) and the values ​​associated with the max_tokens and options temperature. The first indicates the maximum number of tokens that can be used for generating responses. If elevatedmax_tokensit can determine a higher expense for the use of the API but more in-depth answers, if low it allows greater cost control but can give rise to incomplete output. The second accepts values ​​between 0 and 1: with values ​​close to 0 you should have more structured answers, as you get closer to 1 they tend instead to be more creative.

// Parameters for returning output
$data = array();
$data["model"] = $model;
$data["messages"] = $messages;
$data["max_tokens"] = 150;
$data["temperature"] = 0.7;


 

● The cURL session

 

At this point we collect headers and parameters and, after initializing the cURL session, we use them to send the message to the API. A handle ($curl) is thus created to be passed to curl_exec(), a PHP function that executes the HTTP request and returns the response in the form of a string. Any errors during this phase will be signaled by the application, otherwise it will proceed with printing the string.

// cURL session
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($data));
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
// Performing the HTTP request and returning the result
$result = curl_exec($curl);
if (curl_errno($curl)) {
	// Error message
    echo "Attention: " . curl_error($curl);
} else {
	// Printout of the result
    echo "<pre>";
	var_dump($result);
	echo "</pre>";
}
curl_close($curl);


 

● JSON decoding and chatbot output

 
Printing the result allows you to view the JSON string containing the response and all its headers. At this point we can then decode this string using the function json_decode() and extract, for example, the count of tokens used for the request and the generation of the output.

//JSON response decoding
$json_response = json_decode($result, true);
// Report on used tokens
echo "They have been used in this chat <strong>" . $json_response["usage"]["prompt_tokens"] . "</strong> prompt token.<br />";
echo "<strong>".$json_response["usage"]["completion_tokens"] . "</strong> token for output.<br/>";
echo "<strong>".$json_response["usage"]["total_tokens"] . "</strong> total tokens used.<br/>";


The chatbot's response is printed last. Note how the latter is truncated because the system considers the value max_tokens too low to be able to provide a complete answer.

//Response extraction
$response = $json_response["choices"][0]["message"]["content"];
// Print the chat template response
echo '<br><br>';
echo '<br><br>';
echo '<strong>You:</strong> '.$question;
echo '<br><br>';
echo '<strong>Chatgpt:</strong> '.$response;
?>
<form action="chatgpt.php" method="get">
  <label for="fname">You:</label>
  <input type="text" id="question" name="question<br><br>
  <input type="submit" value="Submit">
</form>



Describing PHP as a "programming language" is perhaps not the most appropriate choice, just as the definition given of an Open Source application seems a bit restrictive. The accuracy of the model can therefore be improved, even by rephrasing the prompt, but in each case our code worked.

 

● The full code

 

<?php
//API KEY for authentication
$api_key = "sk-??????????????????????";
//Service URL
$url = 'https://api.openai.com/v1/chat/completions';
// Organization ID
$org_id = "";
// Generative model to use
$model = "gpt-3.5-turbo";
$headers = array(
    "Authorization: Bearer {$api_key}",
    "OpenAI-Organization: {$org_id}",
    "Content-Type: application/json"
);
$question="";
if(isset($_REQUEST["question"]))
 {
  $question=$_REQUEST["question"];
 }
// Request to the chatbot
$messages = array();
$messages[] = array("role" => "user", "content" => $question);

// Parameters for returning output $data = array(); $data["model"] = $model; $data["messages"] = $messages; $data["max_tokens"] = 150; $data["temperature"] = 0.7; // cURL session $curl = curl_init($url); curl_setopt($curl, CURLOPT_POST, 1); curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($data)); curl_setopt($curl, CURLOPT_HTTPHEADER, $headers); curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); // Performing the HTTP request and returning the result $result = curl_exec($curl); if (curl_errno($curl)) { // Error message echo "Attention: " . curl_error($curl); } else { // Printout of the result echo "<pre>"; var_dump($result); echo "</pre>"; } curl_close($curl); //JSON response decoding $json_response = json_decode($result, true); // Report on used tokens echo "They have been used in this chat <strong>" . $json_response["usage"]["prompt_tokens"] . "</strong> prompt token.<br />"; echo "<strong>".$json_response["usage"]["completion_tokens"] . "</strong> token for output.<br/>"; echo "<strong>".$json_response["usage"]["total_tokens"] . "</strong> total tokens used.<br/>"; //Response extraction $response = $json_response["choices"][0]["message"]["content"]; // Print the chat template response echo '<br><br>'; echo '<br><br>'; echo '<strong>You:</strong> '.$question; echo '<br><br>'; echo '<strong>Chatgpt:</strong> '.$response; ?> <form action="chatgpt.php" method="get"> <label for="fname">You:</label> <input type="text" id="question" name="question<br><br> <input type="submit" value="Submit"> </form>


 
How to use ChatGPT with PHP
 


 

● You can test this example here

 
https://www.dzosoft.com/examples/chatgpt 

 

● Conclusions

 
The OpenAI APIs allow you to query the GPT generative model using various languages. Previously we have analyzed the Python example, in this lesson we have proposed instead an example based on PHP. We will soon discover other ways to use these interfaces.

It might also interest you


The 5 best tutorials for learning php in 2023

How to create a chat application with PHP and HTML in just few steps

How to install XAMPP (with Apache, MySQL & phpMyAdmin) on Windows

How to easily send an email with PHPMailer in PHP

How to easily create charts using PHP

How to make login with OTP Authentication in PHP


Leave comment
          

Save nickname and email in this browser for the next time.



Loading...     
close publicity
Nord VPN