OpenAI API: ChatGPT has really evolved as the next base for building AI based applications and made a rather bigger boost for itself, since Microsoft has announced to invest heavily into the technology.
The basic concept of ChatGPT was developed by San Francisco startup OpenAI and after foreseeing its prominence impact towards the AI based applications, the Tech world has really given their nod on this.
From automation, business campaign to customer support, ChatGPT has shown its applicability to a wide range of applications.
OpenAI ChatGPT API Integration in PHP
Let’s start the tutorial for a basic integration with ChatGPT OpenAI API:
1) Create an account with OpenAI by going to URL https://openai.com/api/ and login.
2) Get your keys by clicking the “Personal” at the top of the page on the right hand side.
3) Now let’s start developing an application using the API. One can start a basic integration by choosing any of the example (application type) by going to URL:
https://platform.openai.com/examples
Let’s say, we want to create a basic application of the type say, English to Other Languages.
Just click on “English to Other Languages” section.
4) Just scroll down the pop-up box to reach the section as shown below:
Select library from the options as per your suitability. I chose curl.
5) Copy this code to make into a file (say translate_from_eng.php).
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
<?php $curl = curl_init(); curl_setopt_array($curl, array( CURLOPT_URL => 'https://api.openai.com/v1/completions', CURLOPT_RETURNTRANSFER => true, CURLOPT_ENCODING => '', CURLOPT_MAXREDIRS => 10, CURLOPT_TIMEOUT => 0, CURLOPT_FOLLOWLOCATION => true, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => 'POST', CURLOPT_POSTFIELDS =>'{ "model": "text-davinci-003", "prompt": "Translate this into 1. French, 2. Hindi, 3. Spanish, 4.Japanese:\n\n1 What rooms do you have available?\n\n.", "temperature": 0.3, "max_tokens": 100, "top_p": 1.0, "frequency_penalty": 0.0, "presence_penalty": 0.0 }', CURLOPT_HTTPHEADER => array( 'Authorization: Bearer sk-NRPZ9Ybx*****************L2mTVd8', 'Content-Type: application/json' ), )); $response = curl_exec($curl); curl_close($curl); echo "<pre>"; print_r(json_decode($response)); |
6) Run the translate_from_eng.php to get the output as follows:
A brief guide to use the API, particularly the terms used inside the code can be better understood by visiting the OpenAI API documentation available at the link:
https://platform.openai.com/docs/introduction/overview