Hi, In this blog post, you will learn how to use the OpenAI API with PHP for text completion using the GPT-3 (Generative Pre-trained Transformer 3) model. The post will guide you through the process of obtaining an API key and installing the OpenAI PHP client library, and will then demonstrate how to use the client library to send text completion requests to the OpenAI API and process the responses. The tutorial will also cover how to customize the text completion request by setting the temperature and max_tokens parameters and will show you how to extract and display the generated text from the response in a streaming way.

Whether you are a beginner or an experienced developer, this post will provide you with the knowledge and skills you need to get started using the OpenAI API with PHP for text completion using the GPT-3 model.

Get OpenAI API key

Follow the given steps to get an API key from OpenAI.

  1. Open OpenAI in your web browser.
  2. Click on the "Get Started" button. You will be redirected to the signup page.
  3. Click on "Continue with Google" or use your email address to continue.
  4. If using Google, select your email address from the given options.
  5. Enter your first and last name.
  6. Verify your phone number.
  7. Enter the OTP code you received via text on your phone number.
  8. Select your purpose of use from the given options. You will be redirected to the "Overview" page.
  9. Click on your profile icon in the top right corner of the page.
  10. From the dropdown, click on "View API Keys".
  11. Click on "Create new secret key" to create your first API key. A popup will display your new API key.
  12. Copy the key and save it somewhere, as it will not be displayed again.
  13. You can create and delete multiple keys as needed.

Watch the whole process of obtaining the API key in this video.

In the free trial, you will get $18 that you can use within three months. The most powerful model 'Davinci' consume $0.02 on 1000 tokens (Avg. 750 words). Get more OpenAI Pricing detail.

Installing PHP Library

We will use the OpenAI PHP Client library by Orhanerday for this project. There are two ways to add the PHP library to your project. You can use the Composer Package Manager or download the library from GitHub.

Using Composer

For that, you must have the Composer installed in your operating system. Open the command prompt in your project folder and run the `composer require orhanerday/open-ai` command. This will install the library in your project and you can access it as given below.

Downloading From Github

You can also get the library from GitHub. Download the zip file and extract it. There is a folder named 'src' that has two PHP files. We just need these two files here. You can use them as given below.

Make Request and Get Response

We have installed the PHP client library for using OpenAI API and have access to it in our PHP file. Now, make a request and get a response from OpenAI. Create an object of the OpenAI class and provide your API key as a parameter to initialize. Also, collect the prompt data that we will send through the JS file using the Get method.

Make an API request using the completion() method of the $open_ai object and pass an object having all API parameters and a callback function as arguments to the completion() method.

API Request Parameter Design

Create an object with all parameters that we will send through API for response preparation.

Model: We will use text-davinci-003 model. It is a powerful model for overall text creation. Give higher quality and longer responses staying close to the instructions.

Prompt: Give your input text to the prompt property.

Temperature: At 0 temperature, the model becomes deterministic and produces the same response each time but responses are very close to the given instructions. As the temperature goes higher, the model produces a variety of responses for the same prompt each time but the responses are random means they may not be very close to your instruction. Its value is from 0 to 1.

Max_tokens: These are defined as the number of characters in response and 256 tokens are good for optimal response.

Top_p: This parameter controls the prediction of a new token(say that new word) during generating a response. For example, the model is generating a response and makes the sentence 'I want to eat', and now the model has many words to add after 'eat'. But each word has a different probability. For example, carrots (10%), cucumbers (40%), and Spinach (30%), on the basis of previously trained datasets. The model knows which word has come with the last word 'eat' and how much time it comes and creates the probability percentage. If we select Top_p as 1, it will select the word with the highest probability. If we select 0, the model uses all words randomly and becomes more creative. Its value is from 0 to 1.

Frequency_penalty: It controls the frequency of words in the response. As the value of Frequency Penalty goes higher, it generate a wider range of words and phrases in the response. Its value is from 0 to 2.

Presence_penalty: This parameter controls the similarity of response with the input text. If the presence penalty is set too low, the model may generate output text that is not similar to the input text and if the presence penalty is set too high, the model may be too restrictive in its output and may struggle to generate response that is very similar to the input text. Its value is from 0 to 2.

Stream: If true, model give streamable response and you can get the response using callback function. If false, model give response at once. No need to use callback function, response will return to the '$complete' variable.

Get Streamable Response

As we set the stream property to true, now we can get response on the callback function. Data variable have the response, just print it. The flush () function will help to show the current state of the webpage and show data in a streaming way.

Get Server Events in JS

Now, get the server events using JS and show the response on the webpage. We will use SSE(Server-Sent Events) javascript library for getting events in a flexible way. So first, add the SSE Library to your webpage.

Run a function, when the user clicks the button. Get the text from the input field that will use as a prompt later and check the input field before going further.

Communication setup for SSE

Create an object using SSE() and pass the PHP file name where we call the API with a 'prompt' parameter. This will send input text to the PHP file during connection. The message is a callback function that accrues when receive a new event from the server side. We will extract the response text from the received event later. Now, activate the stream of events using stream().

Process the Response

Before processing the data, first, check whether the data is available or not. It may be empty sometimes. Also, check if the data is still remaining or completed. The server sends the '[DONE]' response on completed and if not properly handled, may give an error on JSON parsing because we can only parse valid JSON events. Now, extract the response text from the object using the correct object properties and add the response with already available text.

Final Thoughts

In this blog post, we have created a simple application that uses the OpenAI API using the PHP client library. You can do more and can develop an advanced application with different scenarios, using different models and designing your prompt with different request parameter values. OpenAI is an advanced natural language processing system that can be further used for Chatbot, grammar correction, extracting keywords from paragraphs, making searches, creating a direction-by-direction response, converting natural languages to SQL queries, explaining programs, etc. This tutorial will definitely help you in developing more applications using OpenAI API.


Orhanerday OpenAI SDK
OpenAI Playground
OpenAI Text Completion Guid