OpenAI PHP SDK : Most downloaded, forked, contributed, huge community supported, and used PHP (Laravel , Symfony, Yii, Cake PHP or any PHP framework) SDK for OpenAI GPT-3 and DALL-E. It also supports
Last updated
OpenAI API Client in PHP
ChatGPT API is currently supported, click here for the implementation introductions.
A message from creator,Thank you for visiting the @orhanerday/open-ai repository! If you find this repository helpful or useful, we encourage you to star it on GitHub. Starring a repository is a way to show your support for the project. It also helps to increase the visibility of the project and to let the community know that it is valuable. Thanks again for your support and we hope you find the repository useful!Orhan
Featured in
Comparison With Other Packages
Project Name
Required PHP Version
Description
Type (Official / Community)
Support
orhanerday/open-ai
PHP 7.4+
Most downloaded, forked, contributed, huge community supported, and used PHP SDK for OpenAI GPT-3 and DALL-E. It also supports chatGPT-like streaming.
Community
openai-** /c***t
PHP 8.1+
OpenAI PHP API client.
Community
-
About this package
Fully open-source and secure community-maintained, PHP SDK for accessing the OpenAI GPT-3 API.
For more information, you can read laravel news blog post.
Free support is available. Join our discord server
To get started with this package, you'll first want to be familiar with the OpenAI API documentation and examples. Also you can get help from our discord channel that called #api-support
News
orhanerday/open-ai added to community libraries php section.
As you may know, OpenAI PHP is an open-source project wrapping tool for OpenAI. We rely on the support of our community to continue developing and maintaining the project, and one way that you can help is by making a donation.
Donations allow us to cover expenses such as hosting costs(for testing), development tools, and other resources that are necessary to keep the project running smoothly. Every contribution, no matter how small, helps us to continue improving OpenAI PHP for everyone.
If you have benefited from using OpenAI PHP and would like to support its continued development, we would greatly appreciate a donation of any amount. You can make a donation through;
Click here for the Coinbase QRBitcoin > 34w2DftWGkDqDbYMixkmdWWMLmaP9uTRz7
Click here for the Coinbase QRDogecoin > DHiqcZox9M8kYDn7BkesnN6Z2kJ7dYG9Lc
Click here for the Coinbase QREthereum > 0x135E2D5d7AC40c6850f844BA589D68e91a268Ceb
Thank you for considering a donation to Orhanerday/OpenAI PHP SDK. Your support is greatly appreciated and helps to ensure that the project can continue to grow and improve.
Before you get starting, you should set OPENAI_API_KEY as ENV key, and set OpenAI key as env value with the following commands;
Powershell
$Env:OPENAI_API_KEY ="sk-gjtv....."
Cmd
set OPENAI_API_KEY=sk-gjtv.....
Linux or macOS
export OPENAI_API_KEY=sk-gjtv.....
Getting issues while setting up env? Please read the article or you can check my StackOverflow answer for the Windows® ENV setup.
Create your index.php file and paste the following code part into the file.
<?phprequire__DIR__.'/vendor/autoload.php'; // remove this line if you use a PHP Framework.useOrhanerday\OpenAi\OpenAi;$open_ai_key =getenv('OPENAI_API_KEY');$open_ai =newOpenAi($open_ai_key);$chat = $open_ai->chat(['model'=>'gpt-3.5-turbo','messages'=> [ ["role"=>"system","content"=>"You are a helpful assistant." ], ["role"=>"user","content"=>"Who won the world series in 2020?" ], ["role"=>"assistant","content"=>"The Los Angeles Dodgers won the World Series in 2020." ], ["role"=>"user","content"=>"Where was it played?" ], ],'temperature'=>1.0,'max_tokens'=>4000,'frequency_penalty'=>0,'presence_penalty'=>0,]);var_dump($chat);echo"<br>";echo"<br>";echo"<br>";// decode response$d =json_decode($chat);// Get Contentecho($d->choices[0]->message->content);
Run the server with the following command
php-Slocalhost:8000-t.
Usage
Load your key from an environment variable.
According to the following code $open_ai is the base variable for all open-ai operations.
For users who belong to multiple organizations, you can pass a header to specify which organization is used for an API request. Usage from these API requests will count against the specified organization's subscription quota.
!!! WARNING:Your API key will expose if you add this method to your code, therefore remove the method before deployment. Be careful !
You can get cURL info after the request.
$open_ai =newOpenAi($open_ai_key);echo $open_ai->listModels(); // you should execute the request FIRST!var_dump($open_ai->getCURLInfo()); // You can call the request
Chat (as known as ChatGPT API)
Given a chat conversation, the model will return a chat completion response.
$complete = $open_ai->chat(['model'=>'gpt-3.5-turbo','messages'=> [ ["role"=>"system","content"=>"You are a helpful assistant." ], ["role"=>"user","content"=>"Who won the world series in 2020?" ], ["role"=>"assistant","content"=>"The Los Angeles Dodgers won the World Series in 2020." ], ["role"=>"user","content"=>"Where was it played?" ], ],'temperature'=>1.0,'max_tokens'=>4000,'frequency_penalty'=>0,'presence_penalty'=>0,]);
Accessing the Element
<?php// Dummy Response For Chat API $j ='{ "id":"chatcmpl-*****", "object":"chat.completion", "created":1679748856, "model":"gpt-3.5-turbo-0301", "usage":{ "prompt_tokens":9, "completion_tokens":10, "total_tokens":19 }, "choices":[ { "message":{ "role":"assistant", "content":"This is a test of the AI language model." }, "finish_reason":"length", "index":0 } ]}';// decode response$d =json_decode($j);// Get Contentecho($d->choices[0]->message->content);
Related: ChatGPT Clone Project
Completions
Given a prompt, the model will return one or more predicted completions, and can also return the probabilities of alternative tokens at each position.
ChatGPT clone is a simple web application powered by the OpenAI library and built with PHP. It allows users to chat with an AI language model that responds in real-time. Chat history is saved using cookies, and the project requires the use of an API key and enabled SQLite3.
Url of The ChatGPT-Clone Repo https://github.com/orhanerday/ChatGPT
Whether to stream back partial progress. If set, tokens will be sent as data-only server-sent events as they become available, with the stream terminated by a data: [DONE] message.
$result = $open_ai->embeddings(["model"=>"text-similarity-babbage-001","input"=>"The food was delicious and the waiter..."]);
Answers
(Deprecated)
This endpoint is deprecated and will be removed on December 3rd, 2022 We’ve developed new methods with better performance. Learn more.
Given a question, a set of documents, and some examples, the API generates an answer to the question based on the information in the set of documents. This is useful for question-answering applications on sources of truth, like company documentation or a knowledge base.
$answer = $open_ai->answer(['documents'=> ['Puppy A is happy.','Puppy B is sad.'],'question'=>'which puppy is happy?','search_model'=>'ada','model'=>'curie','examples_context'=>'In 2017, U.S. life expectancy was 78.6 years.','examples'=> [['What is human life expectancy in the United States?','78 years.']],'max_tokens'=>5,'stop'=> ["\n",'<|endoftext|>'],]);
Classifications
(Deprecated)
This endpoint is deprecated and will be removed on December 3rd, 2022 OpenAI developed new methods with better performance. Learn more.
Given a query and a set of labeled examples, the model will predict the most likely label for the query. Useful as a drop-in replacement for any ML classification or text-to-label task.
$classification = $open_ai->classification(['examples'=> [ ['A happy moment','Positive'], ['I am sad.','Negative'], ['I am feeling awesome','Positive'], ],'labels'=> ['Positive','Negative','Neutral'],'query'=>'It is a raining day =>(','search_model'=>'ada','model'=>'curie',]);
Content Moderations
Given a input text, outputs if the model classifies it as violating OpenAI's content policy.
$flags = $open_ai->moderation(['input'=>'I want to kill them.']);
{ "text": "I'm going to use the stones again. Hey, we'd be going in short-handed, you know. Look, he's still got the stones, so... So let's get them. Use them to bring everyone back. Just like that? Yeah, just like that. Even if there's a small chance that we can undo this, I mean, we owe it to everyone who's not in this room to try. If we do this, how do we know it's going to end any differently than it did before? Because before you didn't have me. Hey, little girl, everybody in this room is about that superhero life. And if you don't mind my asking, where the hell have you been all this time? There are a lot of other planets in the universe. But unfortunately, they didn't have you guys. I like this one. Let's go get this son of a bitch."
}
Create Translation
Translates audio into English.
I use Turkish voice for translation thanks to famous science YouTuber Barış Özcan
{ "text": "GPT-3. Last month, the biggest leap in the world of artificial intelligence in recent years happened silently. Maybe the biggest leap of all time. GPT-3's beta version was released by OpenAI. When you hear such a sentence, you may think, what kind of leap is this? But be sure, this is the most advanced language model with the most advanced language model with the most advanced language ability. It can answer these artificial intelligence questions, it can translate and even write poetry. Those who have gained access to the API or API of GPT-3 have already started to make very interesting experiments. Let's look at a few examples together. Let's start with an example of aphorism. This site produces beautiful words that you can tweet. Start to actually do things with your words instead of just thinking about them."
}
Need HTML upload for audio? Check this section and change api references. Example :
Files are used to upload documents that can be used across features like Answers, Search, and Classifications
List files
Returns a list of files that belong to the user's organization.
$files = $open_ai->listFiles();
Upload file
Upload a file that contains document(s) to be used across various endpoints/features. Currently, the size of all the files uploaded by one organization can be up to 1 GB. Please contact OpenAI if you need to increase the storage limit.
To run only those tests that work for most user (exclude those that require a missing folder or that hit deprecated endpoints no longer available to most users):
./vendor/bin/pest--group=working
Changelog
Please see CHANGELOG for more information on what has changed recently.