How to use ChatGPT API in PHP

The ChatGPT API is a tool that allows developers to integrate OpenAI's language model into their software applications. This Answer will guide you through the application of the ChatGPT API in PHP, from account setup and API key acquisition to executing requests to the ChatGPT API endpoint utilizing PHP’s cURL library.

Steps to use ChatGPT API in PHP

Acquire API credentials

To start using the ChatGPT API, you first need to obtain your API credentials. This involves creating an OpenAI account and generating your API key. This key is crucial as it grants access to your OpenAI resources.

Configure your PHP environment

Next, your development environment needs to be correctly configured. This entails the installation of cURL, a library enabling HTTP requests from PHP, and Composer, a dependency management utility for PHP. You'll also need to establish a new PHP project or utilize an existing one to incorporate the ChatGPT API.

Install the OpenAI PHP SDK

The OpenAI PHP SDK is a handy tool that lets you interact with the ChatGPT API from within your PHP software. You can install the SDK by executing the command composer require openai/api in your PHP project directory. Upon completion of the installation, you can import the OpenAI PHP SDK into your PHP files using the respective code:

require 'vendor/autoload.php';
use OpenAI\Api\OpenAI;

Make API requests

With your PHP environment set up and the SDK installed, you can initiate API requests to the ChatGPT API. Here's a demonstration of how a chat-based response can be generated using the API.

$openai = new OpenAI('YOUR_API_KEY');
$response = $openai->complete([
'model' => 'gpt-3.5-turbo',
'messages' => [
['role' => 'system', 'content' => 'You are a helpful assistant.'],
['role' => 'user', 'content' => 'Who won the world series in 2020?']
],
'temperature' => 0.6
]);
Code explanation
  • Line 1: Instantiate the OpenAI class with your API key.

  • Line 3: Call the complete method on the OpenAI instance. The result of the method is stored in $response.

  • Line 4: Specify the model parameter as gpt-3.5-turbo.

  • Lines 5–8: Define the messages parameter as an array of message objects. Each object has a 'role' (either 'system' or 'user') and 'content' (the actual message).

  • Line 9: Set the temperature parameter to 0.6, controlling the randomness of the model's output.

Optimum practices

To ensure the efficiency of your implementation, consider the following optimal practices when employing the ChatGPT API in PHP:

  • Batching requests: Rather than executing individual API calls for each user interaction, consider batching multiple messages together to reduce latency and cost.

  • Managing rate limits: The ChatGPT API has rate limits implemented. Ensure you handle rate limit errors gracefully by implementing adequate error handling and retry logic.

  • Cleansing user inputs: Like any user-generated content, it’s crucial to sanitize and validate inputs to prevent any inappropriate content from being sent to the API.

  • Experimenting with parameters: Modifying the temperature parameter enables you to regulate the randomness of the response. Experiment with different values to find the right balance for your application.

Example

Consider a scenario where a lengthy text input exceeds the maximum token limit of the ChatGPT API. The text is a discussion between a user and an assistant about a complex topic. The conversation is too extensive to fit within the token limit, necessitating the need to fragment it into smaller sections.

Firstly, it is vital to understand that the ChatGPT API accepts a series of messages as input and delivers a model-generated message as output. Each message has a role (which can be 'system', 'user', or 'assistant') and content (the text of the message from the role).

To fragment the conversation, we can follow these steps:

  1. Identify natural breaks: Identify natural breaks in the conversation where the text can be split without losing context. These could be at the conclusion of a topic or question.

  2. Fragment the text: Split the text at the identified breaks to create smaller sections. Each section should be within the token limit of the ChatGPT API.

  3. Dispatch each section to the API: Send each section to the API as a separate message. The 'system' message can be used to define the behavior of the assistant, and the 'user' messages can be the sections of the conversation.

Here's an example of how you can fragment a longer conversation into smaller sections:

$openai = new OpenAI('YOUR_API_KEY');
$response = $openai->complete([
'model' => 'gpt-3.5-turbo',
'messages' => [
['role' => 'system', 'content' => 'You are a helpful assistant.'],
['role' => 'user', 'content' => 'Part 1 of the conversation'],
['role' => 'user', 'content' => 'Part 2 of the conversation'],
['role' => 'user', 'content' => 'Part 3 of the conversation']
],
'temperature' => 0.6
]);

Code example

Let's see a simple example of how to use the OpenAI API to interact with the GPT-3.5 model for conversational purposes.

Note: Add your OPENAI API key in the code and then click "RUN" to execute the code.

<?php
// Define API key and endpoint URL
const OPENAI_API_KEY = "YOUR_API_KEY_HERE"; // Make sure to replace with your actual API key
const ENDPOINT_URL = "https://api.openai.com/v1/chat/completions";
// Check if the API key is provided
if (OPENAI_API_KEY === "YOUR_API_KEY_HERE") {
die("Please replace 'YOUR_API_KEY_HERE' with your OpenAI API key.");
}
// Define header parameters
$headerParameters = array(
"Content-Type: application/json",
"Authorization: Bearer " . OPENAI_API_KEY
);
// Define body parameters
$bodyParameters = array(
"model" => "gpt-3.5-turbo",
"messages" => array(
array(
"role" => "system",
"content" => "Assume the persona of Shakespeare and provide profound, intellectual responses as if we were in the 1750s."
),
array(
"role" => "user",
"content" => "What are computers!"
)
)
);
// Initialize cURL session
$ch = curl_init();
// Set cURL options
curl_setopt($ch, CURLOPT_URL, ENDPOINT_URL);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headerParameters);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($bodyParameters));
// Execute cURL request
$response = curl_exec($ch);
// Check for cURL errors
if ($response === false) {
die("cURL Error: " . curl_error($ch));
}
// Get HTTP status code
$httpStatusCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
// Check for HTTP errors
if ($httpStatusCode !== 200) {
echo "HTTP Error: " . $httpStatusCode;
echo "Response Body: " . $response;
} else {
// Decode JSON response
$responseData = json_decode($response, true);
// Output response
echo "Response Object: " . print_r($responseData, true);
}
// Close cURL session
curl_close($ch);
?>

Explanation

  • Line 8-10: We add a check to ensure that the API key has been replaced. If not, it prompts the user to replace the placeholder with their actual API key.

  • Line 13-31: We set up header parameters including the content type and authorization using the API key. It also sets up body parameters including the model to be used (gpt-3.5-turbo) and the conversation messages.

  • Line 44-49: The code initializes a cURL session ($ch) and sets various options such as URL, request type (POST), headers, and body parameters. The cURL request is executed, and the response is stored in $response.

  • Line 66: Close the cURL session.

Conclusion

By adhering to the steps outlined in this Answer, you can effectively utilize the ChatGPT API in PHP. Remember to stick to the best practices, such as batching requests and cleansing user inputs, to ensure the efficiency and effectiveness of your implementation.

Free Resources

Copyright ©2024 Educative, Inc. All rights reserved