A message from creator,
Thank you for visiting the @orhanerday/open-ai repository! We are thrilled to see that it has been downloaded nearly 30k times. 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
Project Name | Required PHP Version | Downloads | Description | Type (Official / Community) | Support |
---|---|---|---|---|---|
orhanerday/open-ai | PHP 7.4+ | 🚀nearly 35K 🚀 |
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 | Available, (Community driven Discord Server or personal mail [email protected]) |
openai-php/client | PHP 8.1+ | OpenAI PHP API client. | Community | - |
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
- orhanerday/open-ai added to community libraries php section.
- orhanerday/open-ai featured on PHPStorm blog post, thanks JetBrains!
Requires PHP 7.4+
Click here to join the Discord server
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;
- Buy me a coffee
- Patreon
- Click here for the Coinbase QR Bitcoin > 34w2DftWGkDqDbYMixkmdWWMLmaP9uTRz7
- Click here for the Coinbase QR Dogecoin > DHiqcZox9M8kYDn7BkesnN6Z2kJ7dYG9Lc
- Click here for the Coinbase QR Ethereum > 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.
Sincerely,
Orhan Erday / Creator.
- Models
- Completions
- Edits
- Images
- Embeddings
- Files
- Fine-tunes
- Moderation
Engines(deprecated)
You can install the package via composer:
composer require orhanerday/open-ai
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.
Create your index.php
file and paste the following code part into the file.
<?php
require __DIR__ . '/vendor/autoload.php'; // remove this line if you use a PHP Framework.
use Orhanerday\OpenAi\OpenAi;
$open_ai_key = getenv('OPENAI_API_KEY');
$open_ai = new OpenAi($open_ai_key);
$complete = $open_ai->completion([
'model' => 'davinci',
'prompt' => 'Hello',
'temperature' => 0.9,
'max_tokens' => 150,
'frequency_penalty' => 0,
'presence_penalty' => 0.6,
]);
var_dump($complete);
Run the server with the following command
php -S localhost:8000 -t .
According to the following code
$open_ai
is the base variable for all open-ai operations.
use Orhanerday\OpenAi\OpenAi;
$open_ai = new OpenAi(env('OPEN_AI_API_KEY'));
Given a prompt, the model will return one or more predicted completions, and can also return the probabilities of alternative tokens at each position.
$complete = $open_ai->completion([
'model' => 'text-davinci-002',
'prompt' => 'Hello',
'temperature' => 0.9,
'max_tokens' => 150,
'frequency_penalty' => 0,
'presence_penalty' => 0.6,
]);
This feature might sound familiar from 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.
$open_ai = new OpenAi(env('OPEN_AI_API_KEY'));
$opts = [
'prompt' => "Hello",
'temperature' => 0.9,
"max_tokens" => 150,
"frequency_penalty" => 0,
"presence_penalty" => 0.6,
"stream" => true,
];
header('Content-type: text/event-stream');
header('Cache-Control: no-cache');
$open_ai->completion($opts, function ($curl_info, $data) {
echo $data . "<br><br>";
echo PHP_EOL;
ob_flush();
flush();
return strlen($data);
});
Add this part inside <body>
of the HTML
<div id="divID">Hello</div>
<script>
var eventSource = new EventSource("/");
var div = document.getElementById('divID');
eventSource.onmessage = function (e) {
if(e.data == "[DONE]")
{
div.innerHTML += "<br><br>Hello";
}
div.innerHTML += JSON.parse(e.data).choices[0].text;
};
eventSource.onerror = function (e) {
console.log(e);
};
</script>
You should see a response like the in video;
stream-event.mp4
Creates a new edit for the provided input, instruction, and parameters
$result = $open_ai->createEdit([
"model" => "text-davinci-edit-001",
"input" => "What day of the wek is it?",
"instruction" => "Fix the spelling mistakes",
]);
All DALL·E Examples available in this repo.
Given a prompt, the model will return one or more generated images as urls or base64 encoded.
Creates an image given a prompt.
$complete = $open_ai->image([
"prompt" => "A cat drinking milk",
"n" => 1,
"size" => "256x256",
"response_format" => "url",
]);
Creates an edited or extended image given an original image and a prompt.
You need HTML upload for image edit or variation? Please check DALL·E Examples
$otter = curl_file_create(__DIR__ . './files/otter.png');
$mask = curl_file_create(__DIR__ . './files/mask.jpg');
$result = $open_ai->imageEdit([
"image" => $otter,
"mask" => $mask,
"prompt" => "A cute baby sea otter wearing a beret",
"n" => 2,
"size" => "1024x1024",
]);
Creates a variation of a given image.
$otter = curl_file_create(__DIR__ . './files/otter.png');
$result = $open_ai->createImageVariation([
"image" => $otter,
"n" => 2,
"size" => "256x256",
]);
(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 documents or labels, the model ranks each document based on its semantic similarity to the provided query.
$search = $open_ai->search([
'engine' => 'ada',
'documents' => ['White House', 'hospital', 'school'],
'query' => 'the president',
]);
Get a vector representation of a given input that can be easily consumed by machine learning models and algorithms.
Related guide: Embeddings
$result = $open_ai->embeddings([
"model" => "text-similarity-babbage-001",
"input" => "The food was delicious and the waiter..."
]);
(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|>'],
]);
(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',
]);
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.'
]);
Know more about Content Moderations here: OpenAI Moderations
(Deprecated)
The Engines endpoints are deprecated. Please use their replacement, Models, instead. Learn more.
Lists the currently available engines, and provides basic information about each one such as the owner and availability.
$engines = $open_ai->engines();
Files are used to upload documents that can be used across features like Answers, Search, and Classifications
Returns a list of files that belong to the user's organization.
$files = $open_ai->listFiles();
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.
$c_file = curl_file_create(__DIR__ . 'files/sample_file_1.jsonl');
$result = $open_ai->uploadFile([
"purpose" => "answers",
"file" => $c_file,
]);
<form action="index.php" method="post" enctype="multipart/form-data">
Select file to upload:
<input type="file" name="fileToUpload" id="fileToUpload">
<input type="submit" value="Upload File" name="submit">
</form>
<?php
require __DIR__ . '/vendor/autoload.php';
use Orhanerday\OpenAi\OpenAi;
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
ob_clean();
$open_ai = new OpenAi(env('OPEN_AI_API_KEY'));
$tmp_file = $_FILES['fileToUpload']['tmp_name'];
$file_name = basename($_FILES['fileToUpload']['name']);
$c_file = curl_file_create($tmp_file, $_FILES['fileToUpload']['type'], $file_name);
echo "[";
echo $open_ai->uploadFile(
[
"purpose" => "answers",
"file" => $c_file,
]
);
echo ",";
echo $open_ai->listFiles();
echo "]";
}
$result = $open_ai->deleteFile('file-xxxxxxxx');
$file = $open_ai->retrieveFile('file-xxxxxxxx');
$file = $open_ai->retrieveFileContent('file-xxxxxxxx');
Manage fine-tuning jobs to tailor a model to your specific training data.
$result = $open_ai->createFineTune([
"training_file" => "file-U3KoAAtGsjUKSPXwEUDdtw86",
]);
$fine_tunes = $open_ai->listFineTunes();
$fine_tune = $open_ai->retrieveFineTune('ft-AF1WoRqd3aJAHsqc9NY7iL8F');
$result = $open_ai->cancelFineTune('ft-AF1WoRqd3aJAHsqc9NY7iL8F');
$fine_tune_events = $open_ai->listFineTuneEvents('ft-AF1WoRqd3aJAHsqc9NY7iL8F');
$result = $open_ai->deleteFineTune('curie:ft-acmeco-2021-03-03-21-44-20');
(Deprecated)
Retrieves an engine instance, providing basic information about the engine such as the owner and availability.
$engine = $open_ai->engine('davinci');
List and describe the various models available in the API.
Lists the currently available models, and provides basic information about each one such as the owner and availability.
$result = $open_ai->listModels();
Retrieves a model instance, providing basic information about the model such as the owner and permissioning.
$result = $open_ai->retrieveModel("text-ada-001");
echo $search;
To run all tests:
composer test
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
Please see CHANGELOG for more information on what has changed recently.
Please see CONTRIBUTING for details.
Please report security vulnerabilities to [email protected]
The MIT License (MIT). Please see License File for more information.