How to Use ChatGPT API in PHP?

By Hardik Savani May 14, 2024 Category : PHP

Hey Folks,

This post is focused on how to use chatgpt api in php. This article will give you a simple example of how to use openai api in php. This article goes in detailed on php openai api curl request. This tutorial will give you a simple example of php chatgpt api example.

In this example, i will show you step by step how to use chatgpt/openai api in php. we will create new account with OpenAI and then we will run simple curl request to getting data from chatgpt. here, i explained step to make it done this example.

Step 1: Create OpenAI Account

Here, you need to follow few things to create new account with OpenAI.

1. Go to https://openai.com and create new account on it.

2. After login, click on right side corner "Personal" and then click on "View API keys".

3. Then there is a "Create new secret key" button and click on it.

4. Now, add app name and generate new API key and copy it. we will use it on our PHP App.

Step 2: Create index.php

Here, you need to add OpenAI secret key on $openAISecretKey variable. then just create following file with code.

index.php

<?php

$openAISecretKey = "sk-lFIxlfTFsWk3uUlQe4zCT3B...";

$search = "Give me 2 words related to php";

$data = [

"model" => "gpt-3.5-turbo",

'messages' => [

[

"role" => "user",

"content" => $search

]

],

'temperature' => 0.5,

"max_tokens" => 200,

"top_p" => 1.0,

"frequency_penalty" => 0.52,

"presence_penalty" => 0.5,

"stop" => ["11."],

];

$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, 'https://api.openai.com/v1/chat/completions');

curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

curl_setopt($ch, CURLOPT_POST, 1);

curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));

$headers = [];

$headers[] = 'Content-Type: application/json';

$headers[] = 'Authorization: Bearer '.$openAISecretKey;

curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

$response = curl_exec($ch);

if (curl_errno($ch)) {

echo 'Error:' . curl_error($ch);

}

curl_close($ch);

print_r($response);

Run PHP File:

All the required steps have been done, now you have to type the given below command and hit enter to run the Laravel app:

php -S localhost:8000

Now, Go to your web browser, type the given URL and view the app output:

http://localhost:8000/index.php

Output:

{

"id": "chatcmpl-7gZQtOJv42s039hgaF3a..",

"object": "chat.completion",

"created": 1690380335,

"model": "gpt-3.5-turbo-0613",

"choices": [

{

"index": 0,

"message": {

"role": "assistant",

"content": "

1) Web development

2) MySQL

"

},

"finish_reason": "stop"

}

],

"usage": {

"prompt_tokens": 15,

"completion_tokens": 8,

"total_tokens": 23

}

}

I hope it can help you...

Tags :
Shares