This article walks you through with sampel code on how to call OpenAI GPT-3 API in PHP. It covers below topics:
- Install php package for openai
- set up environment variables
- import the php package
- call the gpt-3 api
OpenAI has not relased an official package for calling the GPT-3 API from php. However, there is a popular 3rd party php package that OpenAI recommends for this purpose.
In order to install the package, use below command.
composer require orhanerday/open-ai
Import the package in your code.
Add the OpenAI API key to your environment as
OPEN_AI_API_KEY. You can get your API key from your OpenAI account.
Next, load the openai API key from your environment
$open_ai = new OpenAi(env(‘OPEN_AI_API_KEY’));
Now we are ready to make our first call to OpenAI
$complete = $open_ai->complete([ 'engine' => 'davinci', 'prompt' => 'Hello', 'temperature' => 0.7, 'max_tokens' => 276, 'frequency_penalty' => 0, 'presence_penalty' => 0.6, ]);
The above code makes a call to the OpenAI GPT-3 completions endpoint. Completions endpoint is used for text generation.
Explanation for the parameters is as below:
- engine: The engine to use for completion.
- prompt: The prompt to complete.
- temperature: The temperature to use for sampling.
- max_tokens: The maximum number of tokens to return.
- frequency_penalty: The penalty to apply to words that appear frequently in - the prompt.
- presence_penalty: The penalty to apply to words that appear in the prompt.
This was a short how to on calling OpenAI GPT-3 API endpoints from php. We showed an example of a text generation call using davinci engine. Good luck with building your GPT-3 product in PHP.
Stick around and read more GPT-3 articles.