open ai php

This commit is contained in:
CHIEFSOFT\ameye
2023-06-16 21:20:28 -04:00
parent 468414a91c
commit cd22881269
11 changed files with 1862 additions and 1 deletions
+1 -1
View File
@@ -20,7 +20,7 @@ user_guide_src/build/*
user_guide_src/cilexer/build/*
user_guide_src/cilexer/dist/*
user_guide_src/cilexer/pycilexer.egg-info/*
/vendor/
#/vendor/
# IDE Files
#-------------------------
+162
View File
@@ -0,0 +1,162 @@
# Changelog
All notable changes to `open-ai` will be documented in this file.
## 3.5 - 2023-02-10
### What's Changed
- Fix "export-ignore" does not work by @assert6 in https://github.com/orhanerday/open-ai/pull/43
- Update README.md by @ali-wells in https://github.com/orhanerday/open-ai/pull/45
- Bump dependabot/fetch-metadata from 1.3.5 to 1.3.6 by @dependabot in https://github.com/orhanerday/open-ai/pull/47
- Add customURL support. by @orhanerday in https://github.com/orhanerday/open-ai/pull/49
### New Contributors
- @assert6 made their first contribution in https://github.com/orhanerday/open-ai/pull/43
- @ali-wells made their first contribution in https://github.com/orhanerday/open-ai/pull/45
**Full Changelog**: https://github.com/orhanerday/open-ai/compare/3.4...3.5
## 3.4 - 2023-01-03
### What's Changed
- Add organization support. by @orhanerday in https://github.com/orhanerday/open-ai/pull/40
**Full Changelog**: https://github.com/orhanerday/open-ai/compare/3.3...3.4
## 3.3 - 2022-12-28
### What's Changed
- Feature request: support stream by @orhanerday in https://github.com/orhanerday/open-ai/pull/37
**Full Changelog**: https://github.com/orhanerday/open-ai/compare/3.2.1...3.3
## 3.2.1 - 2022-12-07
### What's Changed
- Update README.md by @orhanerday
**Full Changelog**: https://github.com/orhanerday/open-ai/compare/3.2...3.2.1
## 3.2 - 2022-12-06
### What's Changed
- Ability to set a timeout value in seconds by @dsampaolo in https://github.com/orhanerday/open-ai/pull/31
### New Contributors
- @dsampaolo made their first contribution in https://github.com/orhanerday/open-ai/pull/31
**Full Changelog**: https://github.com/orhanerday/open-ai/compare/3.1...3.2
## 3.1 - 2022-11-22
### What's Changed
- Bump dependabot/fetch-metadata from 1.3.4 to 1.3.5 by @dependabot in https://github.com/orhanerday/open-ai/pull/28
- Fix tests by @adetch in https://github.com/orhanerday/open-ai/pull/29
- Add current completion endpoint by @adetch in https://github.com/orhanerday/open-ai/pull/30
### New Contributors
- @adetch made their first contribution in https://github.com/orhanerday/open-ai/pull/29
**Full Changelog**: https://github.com/orhanerday/open-ai/compare/3.0...3.1
## 3.0 - 2022-11-04
### What's Changed
- List models by @orhanerday in https://github.com/orhanerday/open-ai/pull/22
- Implement edit feature by @orhanerday in https://github.com/orhanerday/open-ai/pull/23
- Add Images feature by @orhanerday in https://github.com/orhanerday/open-ai/pull/24
- Embeddings feature by @orhanerday in https://github.com/orhanerday/open-ai/pull/25
- Add retrieve file content by @orhanerday in https://github.com/orhanerday/open-ai/pull/26
- Add deprecated methods by @orhanerday in https://github.com/orhanerday/open-ai/pull/27
**Full Changelog**: https://github.com/orhanerday/open-ai/compare/2.3...3.0
## 2.3 - 2022-11-04
### What's Changed
- Fix documentation for Url Class by @Muchwat in https://github.com/orhanerday/open-ai/pull/18
- Bump dependabot/fetch-metadata from 1.3.3 to 1.3.4 by @dependabot in https://github.com/orhanerday/open-ai/pull/19
- feat: Add image generation api by @SheepFromHeaven in https://github.com/orhanerday/open-ai/pull/21
### New Contributors
- @Muchwat made their first contribution in https://github.com/orhanerday/open-ai/pull/18
- @SheepFromHeaven made their first contribution in https://github.com/orhanerday/open-ai/pull/21
**Full Changelog**: https://github.com/orhanerday/open-ai/compare/2.2...2.3
## 2.2 - 2022-09-15
### What's Changed
- API for content filter, unit testing fixed and added documentation for content filtering by @bashar94 in https://github.com/orhanerday/open-ai/pull/17
### New Contributors
- @bashar94 made their first contribution in https://github.com/orhanerday/open-ai/pull/17
**Full Changelog**: https://github.com/orhanerday/open-ai/compare/2.1...2.2
## 2.1 - 2022-05-29
### What's Changed
- Adding more capabilities by @orhanerday in https://github.com/orhanerday/open-ai/pull/11
- Files
- Fine-tuning
### New Contributors
- @orhanerday made their first contribution in https://github.com/orhanerday/open-ai/pull/11
**Full Changelog**: https://github.com/orhanerday/open-ai/compare/2.0...2.1
## 2.0 - 2022-05-28
### What's Changed
- Orhanerday/open-ai now supports file uploads
- Bump dependabot/fetch-metadata from 1.1.1 to 1.2.0 by @dependabot in https://github.com/orhanerday/open-ai/pull/3
- Bump dependabot/fetch-metadata from 1.2.0 to 1.2.1 by @dependabot in https://github.com/orhanerday/open-ai/pull/4
- Bump dependabot/fetch-metadata from 1.2.1 to 1.3.0 by @dependabot in https://github.com/orhanerday/open-ai/pull/5
- Bump actions/checkout from 2 to 3 by @dependabot in https://github.com/orhanerday/open-ai/pull/6
- Bump dependabot/fetch-metadata from 1.3.0 to 1.3.1 by @dependabot in https://github.com/orhanerday/open-ai/pull/7
### New Contributors
- @dependabot made their first contribution in https://github.com/orhanerday/open-ai/pull/3
**Full Changelog**: https://github.com/orhanerday/open-ai/compare/1.1...2.0
## 1.1 - 2022-02-01
### **Big new**
- [orhanerday/open-ai](https://github.com/orhanerday/open-ai) now supports PHP 8
## What's Changed
- Remove duplicate entry from the changelog by @johanvanhelden in https://github.com/orhanerday/open-ai/pull/1
- Allow PHP8 by @mydnic in https://github.com/orhanerday/open-ai/pull/2
## New Contributors
- @johanvanhelden made their first contribution in https://github.com/orhanerday/open-ai/pull/1
- @mydnic made their first contribution in https://github.com/orhanerday/open-ai/pull/2
**Full Changelog**: https://github.com/orhanerday/open-ai/compare/1.0.0...1.1
## 1.0.0 - 2021-12-22
- initial release
+21
View File
@@ -0,0 +1,21 @@
The MIT License (MIT)
Copyright (c) orhanerday <orhanerday@gmail.com>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
+899
View File
@@ -0,0 +1,899 @@
# OpenAI API Client in PHP
<br />
<br />
> ### ChatGPT API is currently supported, [click here](#chat-as-known-as-chatgpt-api) for the implementation introductions.
<br />
*A message from creator,<br />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! <br /><br /> Orhan*
<br />
<br />
[![Latest Version on Packagist](https://img.shields.io/packagist/v/orhanerday/open-ai.svg?style=flat-square)](https://packagist.org/packages/orhanerday/open-ai)
[![Total Downloads](https://img.shields.io/packagist/dt/orhanerday/open-ai.svg?style=flat-square)](https://packagist.org/packages/orhanerday/open-ai)
<br />
<br />
<img src="./openai-elephpant.svg" width="1250" height="300" alt="orhanerday-open-ai-logo">
<br />
<br />
# Featured in
[![Jetbrains Blog](https://user-images.githubusercontent.com/22305274/222431781-86591161-ccd5-4889-bd80-97a0fd0fdf0d.png)](https://blog.jetbrains.com/phpstorm/2022/12/php-annotated-december-2022/#:~:text=orhanerday/open%2Dai%20%E2%80%93%20A%20PHP%20SDK%20for%20accessing%20the%20OpenAI%20GPT%2D3%20API)
[![Laravel News](https://user-images.githubusercontent.com/22305274/222430084-be097d59-e6bc-408d-8adb-7b751d5a05b2.png)](https://laravel-news.com/openai-sdk-for-php)
[![日思录](https://user-images.githubusercontent.com/22305274/222431699-f3a8a146-e27c-4fe3-8c93-1d762559752f.png)](http://tubring.cn/articles/59)
# 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 | Available, ([Community driven Discord Server](https://discord.gg/xpGUD528XJ) or personal mail [orhan@duck.com](mailto:orhan@duck.com)) |
| openai-** */c****t | PHP 8.1+ | OpenAI PHP API client. | Community | - |
<br />
## 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](https://laravel-news.com/openai-sdk-for-php).
> #### Free support is available. [Join our discord server](#join-our-discord-server)
> #### To get started with this package, you'll first want to be familiar with the [OpenAI API documentation](https://beta.openai.com/docs/introduction) and [examples](https://beta.openai.com/examples). Also you can get help from our discord channel that called [#api-support](https://discord.gg/R9CpVUdqQR)
## News
- orhanerday/open-ai added to community libraries php [section](https://beta.openai.com/docs/libraries/php).
- orhanerday/open-ai featured
on [PHPStorm blog post](https://blog.jetbrains.com/phpstorm/2022/12/php-annotated-december-2022/#:~:text=orhanerday/open%2Dai%20%E2%80%93%20A%20PHP%20SDK%20for%20accessing%20the%20OpenAI%20GPT%2D3%20API),
thanks JetBrains!
> Requires PHP 7.4+
## Join our discord server
![Discord Banner 2](https://discordapp.com/api/guilds/1047074572488417330/widget.png?style=banner2)
[Click here to join the Discord server](https://discord.gg/xpGUD528XJ)
## Support this project
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](https://www.buymeacoffee.com/orhane)
* [Patreon](https://patreon.com/orhann)
* [Click here for the Coinbase QR](#btc) **Bitcoin** > 34w2DftWGkDqDbYMixkmdWWMLmaP9uTRz7
* [Click here for the Coinbase QR](#doge) **Dogecoin** > DHiqcZox9M8kYDn7BkesnN6Z2kJ7dYG9Lc
* [Click here for the Coinbase QR](#eth) **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.
# Documentation
Please visit https://orhanerday.gitbook.io/openai-php-api-1/
# Endpoint Support
- Chat
- [x] [ChatGPT API](#chat-as-known-as-chatgpt-api)
- Models
- [x] [List models](https://beta.openai.com/docs/api-reference/models/list)
- [x] [Retrieve model](https://beta.openai.com/docs/api-reference/models/retrieve)
- Completions
- [x] [Create completion](https://beta.openai.com/docs/api-reference/completions/create)
- Edits
- [x] [Create edits](https://beta.openai.com/docs/api-reference/edits/create)
- Images
- [x] [Create image](https://beta.openai.com/docs/api-reference/images/create)
- [x] [Create image edit](https://beta.openai.com/docs/api-reference/images/create-edit)
- [x] [Create image variation](https://beta.openai.com/docs/api-reference/images/create-variation)
- Embeddings
- [x] [Create embeddings](https://beta.openai.com/docs/api-reference/embeddings/create)
- Audio
- [x] [Create transcription](https://platform.openai.com/docs/api-reference/audio/create)
- [x] [Create translation](https://platform.openai.com/docs/api-reference/audio/create)
- Files
- [x] [List files](https://beta.openai.com/docs/api-reference/files/list)
- [x] [Upload file](https://beta.openai.com/docs/api-reference/files/upload)
- [x] [Delete file](https://beta.openai.com/docs/api-reference/files/delete)
- [x] [Retrieve file](https://beta.openai.com/docs/api-reference/files/retrieve)
- [x] [Retrieve file content](https://beta.openai.com/docs/api-reference/files/retrieve-content)
- Fine-tunes
- [x] [Create fine-tune (beta)](https://beta.openai.com/docs/api-reference/fine-tunes/create)
- [x] [List fine-tunes (beta)](https://beta.openai.com/docs/api-reference/fine-tunes/list)
- [x] [Retrieve fine-tune (beta)](https://beta.openai.com/docs/api-reference/fine-tunes/retrieve)
- [x] [Cancel fine-tune (beta)](https://beta.openai.com/docs/api-reference/fine-tunes/cancel)
- [x] [List fine-tune events (beta)](https://beta.openai.com/docs/api-reference/fine-tunes/events)
- [x] [Delete fine-tune model (beta)](https://beta.openai.com/docs/api-reference/fine-tunes/delete-model)
- Moderation
- [x] [Create moderation](https://beta.openai.com/docs/api-reference/moderations/create)
- ~~Engines~~ *(deprecated)*
- ~~[List engines](https://beta.openai.com/docs/api-reference/engines/list)~~
- ~~[Retrieve engine](https://beta.openai.com/docs/api-reference/engines/retrieve)~~
## Installation
You can install the package via composer:
```bash
composer require orhanerday/open-ai
```
## Quick Start ⚡
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_
```powershell
$Env:OPENAI_API_KEY = "sk-gjtv....."
```
_Cmd_
```cmd
set OPENAI_API_KEY=sk-gjtv.....
```
_Linux or macOS_
```shell
export OPENAI_API_KEY=sk-gjtv.....
```
> Getting issues while setting up env? Please read
> the [article](https://help.openai.com/en/articles/5112595-best-practices-for-api-key-safety) or you can check
> my [StackOverflow answer](https://stackoverflow.com/a/73904271/15196622) for the Windows® ENV setup.
Create your `index.php` file and paste the following code part into the file.
```php
<?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);
$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 Content
echo($d->choices[0]->message->content);
```
_Run the server with the following command_
```shell
php -S localhost: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.
```php
use Orhanerday\OpenAi\OpenAi;
$open_ai = new OpenAi(env('OPEN_AI_API_KEY'));
```
## Requesting organization
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.
````php
$open_ai_key = getenv('OPENAI_API_KEY');
$open_ai = new OpenAi($open_ai_key);
$open_ai->setORG("org-IKN2E1nI3kFYU8ywaqgFRKqi");
````
## Base URL
You can specify Origin URL with `setBaseURL()` method;
````php
$open_ai_key = getenv('OPENAI_API_KEY');
$open_ai = new OpenAi($open_ai_key,$originURL);
$open_ai->setBaseURL("https://ai.example.com/");
````
## Use Proxy
You can use some proxy servers for your requests api;
````php
$open_ai->setProxy("http://127.0.0.1:1086");
````
## Set header
```php
$open_ai->setHeader(["Connection"=>"keep-alive"]);
```
## Get cURL request info
> ### !!! 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.
````php
$open_ai = new OpenAi($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.
```php
$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
<?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 Content
echo($d->choices[0]->message->content);
```
> ### Related: [ChatGPT Clone Project](#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.
```php
$complete = $open_ai->completion([
'model' => 'text-davinci-002',
'prompt' => 'Hello',
'temperature' => 0.9,
'max_tokens' => 150,
'frequency_penalty' => 0,
'presence_penalty' => 0.6,
]);
```
### Stream Example
This feature might sound familiar from [ChatGPT](https://chat.openai.com/chat).
<hr>
#### ChatGPT Clone Project
Video of demo:
https://user-images.githubusercontent.com/22305274/219878695-c76a58c0-5081-402c-a1b5-2b1fd971735a.mp4
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
<hr>
Whether to stream back partial progress. If set, tokens will be sent as
data-only [server-sent events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events#event_stream_format)
as they become available, with the stream terminated by a data: [DONE] message.
````php
$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
````php
<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;
https://user-images.githubusercontent.com/22305274/209847128-f72c9345-dd34-46f0-bbc5-daf1d7b6121f.mp4
## Edits
Creates a new edit for the provided input, instruction, and parameters
```php
$result = $open_ai->createEdit([
"model" => "text-davinci-edit-001",
"input" => "What day of the wek is it?",
"instruction" => "Fix the spelling mistakes",
]);
```
## Images (DALL·E)
> All DALL·E Examples available in this [repo](https://github.com/orhanerday/DALLE-Examples).
Given a prompt, the model will return one or more generated images as urls or base64 encoded.
### Create image
Creates an image given a prompt.
```php
$complete = $open_ai->image([
"prompt" => "A cat drinking milk",
"n" => 1,
"size" => "256x256",
"response_format" => "url",
]);
```
### Create image edit
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](https://github.com/orhanerday/DALLE-Examples)
````php
$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",
]);
````
### Create image variation
Creates a variation of a given image.
````php
$otter = curl_file_create(__DIR__ . './files/otter.png');
$result = $open_ai->createImageVariation([
"image" => $otter,
"n" => 2,
"size" => "256x256",
]);
````
## Searches
**_(Deprecated)_**
> This endpoint is deprecated and will be removed on December 3rd, 2022
> OpenAI developed new methods with better
> performance. [Learn more.](https://help.openai.com/en/articles/6272952-search-transition-guide)
Given a query and a set of documents or labels, the model ranks each document based on its semantic similarity to the
provided query.
```php
$search = $open_ai->search([
'engine' => 'ada',
'documents' => ['White House', 'hospital', 'school'],
'query' => 'the president',
]);
```
## Embeddings
Get a vector representation of a given input that can be easily consumed by machine learning models and algorithms.
Related guide: [Embeddings](https://beta.openai.com/docs/guides/embeddings)
### Create embeddings
```php
$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
> Weve developed new methods with better
> performance. [Learn more](https://help.openai.com/en/articles/6233728-answers-transition-guide).
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.
```php
$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.](https://help.openai.com/en/articles/6272941-classifications-transition-guide)
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.
```php
$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.
```php
$flags = $open_ai->moderation([
'input' => 'I want to kill them.'
]);
```
Know more about Content Moderations here: [OpenAI Moderations](https://beta.openai.com/docs/api-reference/moderations)
## List engines
**_(Deprecated)_**
> The Engines endpoints are deprecated.
> Please use their replacement, [Models](#list-models), instead. [Learn more](TODO?).
Lists the currently available engines, and provides basic information about each one such as the owner and availability.
```php
$engines = $open_ai->engines();
```
## Audio
### Create Transcription
Transcribes audio into the input language.
```php
$c_file = curl_file_create(__DIR__ . '/files/en-marvel-endgame.m4a');
$result = $open_ai->transcribe([
"model" => "whisper-1",
"file" => $c_file,
]);
```
#### Response
```json
{
"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](https://youtu.be/r2dQgdktUJg?t=90)_
```php
$c_file = curl_file_create(__DIR__ . '/files/tr-baris-ozcan-youtuber.m4a');
$result = $open_ai->translate([
"model" => "whisper-1",
"file" => $c_file,
]);
```
#### Response
```json
{
"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](#upload-file-with-html-form) section and change api references. Example :
```php
...
echo $open_ai->translate(
[
"purpose" => "answers",
"file" => $c_file,
]
);
...
// OR
...
echo $open_ai->transcribe(
[
"purpose" => "answers",
"file" => $c_file,
]
);
...
```
## Files
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.
```php
$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.
```php
$c_file = curl_file_create(__DIR__ . 'files/sample_file_1.jsonl');
$result = $open_ai->uploadFile([
"purpose" => "answers",
"file" => $c_file,
]);
```
### Upload file with HTML Form
```php
<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 "]";
}
```
### Delete file
```php
$result = $open_ai->deleteFile('file-xxxxxxxx');
```
### Retrieve file
```php
$file = $open_ai->retrieveFile('file-xxxxxxxx');
```
### Retrieve file content
```php
$file = $open_ai->retrieveFileContent('file-xxxxxxxx');
```
## Fine-tunes
Manage fine-tuning jobs to tailor a model to your specific training data.
### Create fine-tune
```php
$result = $open_ai->createFineTune([
"training_file" => "file-U3KoAAtGsjUKSPXwEUDdtw86",
]);
```
### List fine-tune
```php
$fine_tunes = $open_ai->listFineTunes();
```
### Retrieve fine-tune
```php
$fine_tune = $open_ai->retrieveFineTune('ft-AF1WoRqd3aJAHsqc9NY7iL8F');
```
### Cancel fine-tune
```php
$result = $open_ai->cancelFineTune('ft-AF1WoRqd3aJAHsqc9NY7iL8F');
```
### List fine-tune events
```php
$fine_tune_events = $open_ai->listFineTuneEvents('ft-AF1WoRqd3aJAHsqc9NY7iL8F');
```
### Delete fine-tune model
```php
$result = $open_ai->deleteFineTune('curie:ft-acmeco-2021-03-03-21-44-20');
```
## Retrieve engine
**_(Deprecated)_**
Retrieves an engine instance, providing basic information about the engine such as the owner and availability.
```php
$engine = $open_ai->engine('davinci');
```
## Models
List and describe the various models available in the API.
### List models
Lists the currently available models, and provides basic information about each one such as the owner and availability.
```php
$result = $open_ai->listModels();
```
### Retrieve model
Retrieves a model instance, providing basic information about the model such as the owner and permissioning.
```php
$result = $open_ai->retrieveModel("text-ada-001");
```
## Printing results *i.e.* `$search`
```php
echo $search;
```
## Testing
To run all tests:
```bash
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):
```bash
./vendor/bin/pest --group=working
```
## Changelog
Please see [CHANGELOG](CHANGELOG.md) for more information on what has changed recently.
## Contributing
Please see [CONTRIBUTING](.github/CONTRIBUTING.md) for details.
## Security Vulnerabilities
Please report security vulnerabilities to [orhanerday@gmail.com](mailto:orhanerday@gmail.com)
## Credits
- [Orhan Erday](https://github.com/orhanerday)
- [All Contributors](../../contributors)
## License
The MIT License (MIT). Please see [License File](LICENSE.md) for more information.
## Donation
<a href="https://www.buymeacoffee.com/orhane" target="_blank"><img src="https://www.buymeacoffee.com/assets/img/custom_images/orange_img.png" alt="Buy Me A Coffee" style="height: 41px !important;width: 174px !important;box-shadow: 0px 3px 2px 0px rgba(190, 190, 190, 0.5) !important;-webkit-box-shadow: 0px 3px 2px 0px rgba(190, 190, 190, 0.5) !important;" ></a>
#### btc
![image](https://user-images.githubusercontent.com/22305274/209946578-fc7db433-699c-491f-9f8b-1c962f0b9ea2.png)
#### eth
![image](https://user-images.githubusercontent.com/22305274/209946539-24f247d9-68a1-4f46-a18b-62790d943c99.png)
#### doge
![image](https://user-images.githubusercontent.com/22305274/209946556-164798d0-e404-4b6c-8669-d63e78f24228.png)
+50
View File
@@ -0,0 +1,50 @@
{
"name": "orhanerday/open-ai",
"description": "OpenAI GPT-3 Api Client in PHP",
"keywords": [
"orhanerday",
"open-ai"
],
"homepage": "https://github.com/orhanerday/open-ai",
"license": "MIT",
"authors": [
{
"name": "Orhan Erday",
"email": "orhanerday@gmail.com",
"role": "Developer"
}
],
"require": {
"php": ">=7.4",
"ext-curl": "*",
"ext-json": "*"
},
"require-dev": {
"friendsofphp/php-cs-fixer": "^3.0",
"pestphp/pest": "^1.20",
"spatie/ray": "^1.28"
},
"autoload": {
"psr-4": {
"Orhanerday\\OpenAi\\": "src"
}
},
"autoload-dev": {
"psr-4": {
"Orhanerday\\OpenAi\\Tests\\": "tests"
}
},
"scripts": {
"test": "vendor/bin/pest",
"test-coverage": "vendor/bin/pest --coverage",
"format": "vendor/bin/php-cs-fixer fix --allow-risky=yes"
},
"config": {
"sort-packages": true,
"allow-plugins": {
"pestphp/pest-plugin": true
}
},
"minimum-stability": "dev",
"prefer-stable": true
}
Binary file not shown.
@@ -0,0 +1,2 @@
{"text": "puppy A is happy", "metadata": "emotional state of puppy A"}
{"text": "puppy B is sad", "metadata": "emotional state of puppy B"}
@@ -0,0 +1 @@
<svg id="Layer_1" data-name="Layer 1" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 334.21 334.22"><path d="M414.1,253.4c-.28,93-75.16,167.17-168.48,166.85-92-.31-166-75.68-165.72-168.6.32-91.72,75.76-166,168.22-165.62C339.89,86.41,414.38,161.52,414.1,253.4ZM246.64,402.3c82.42,0,149.45-66.38,149.52-148.16C396.23,171,330,104.05,247.61,104c-83.18-.06-149.74,66.35-149.77,149.42C97.81,335.49,164.56,402.27,246.64,402.3Z" transform="translate(-79.9 -86.03)"/><path d="M236.26,294.18,215.93,185c3.67.24,7.06.3,10.4.75,1.8.24,2.41,1.83,2.33,3.6-.17,4-.69,8-.44,12,.95,14.9,6,28.15,17.49,38.12,8.14,7.09,18,9.69,28.79,8.55,1.63-.18,3.23-.57,4.85-.88a11.6,11.6,0,0,0,9-7.09c2.69-6.29,3.18-12.95,3.17-19.68,0-.16-.15-.32-.34-.69-1,3.1-1.63,6.11-2.78,8.91a108.61,108.61,0,0,1-5.32,11.16,8.5,8.5,0,0,1-8.27,4.37c-13.55-.55-24.22-6.44-31.52-17.86-6.57-10.27-8-21.71-6-33.52,1.9-10.89,8.88-17.71,19-21.47,11.23-4.18,22.92-4.7,34.72-4.11,4.92.25,9.82.71,14.73,1.08,7.68.58,13.51,4.8,18.71,9.95a80.22,80.22,0,0,1,20.68,35.28c2.71,9.35,4.07,18.84,2.68,28.59-1.54,10.82-6.4,20-13.65,28.06-4.18,4.67-7.87,9.79-11.71,14.77a10.29,10.29,0,0,0-1.4,3c-1.48,4.48-.05,7.35,4.37,9l1.48.55c4.41,1.62,5.39,4.75,2.63,8.61a15.32,15.32,0,0,1-8.9,6.11,6.26,6.26,0,0,1-4.49-1.22,33.28,33.28,0,0,1-12.11-15.65c-1.6-4.38-.5-8.44,1.54-12.3,2.45-4.64,5.13-9.15,7.67-13.74a15.66,15.66,0,0,0,1.26-3.09c1.22-4.09-1.37-7-5.65-6.56-4,.45-7,2.89-10,5.22s-5.77,4.77-8.77,7a14.32,14.32,0,0,0-6,10c-1.16,9.62.11,18.8,5.47,27.17a67.7,67.7,0,0,1,4.49,8.29c1.34,2.93.8,4.55-2.08,6a36.29,36.29,0,0,1-7.51,2.85A81.16,81.16,0,0,1,264.18,329a21.91,21.91,0,0,1-3.14-.24c-2.62-.38-3.37-1.27-3.45-3.89-.16-5.11-.18-10.23-.53-15.33a28.79,28.79,0,0,0-5.54-15.15c-3.39-4.63-7-5.16-11.93-2.08C238.57,293,237.48,293.52,236.26,294.18Zm86-72.28a5.11,5.11,0,0,0,4.2-5.69,5.05,5.05,0,0,0-5.92-4.1,5,5,0,1,0,1.72,9.79Z" transform="translate(-79.9 -86.03)"/><path d="M228.08,272.18l1.52,8.17c-7.61,6-15.14,12-22.9,17.8a7.24,7.24,0,0,1-5.5.74c-8.85-2.45-17.6-5.24-26.39-7.88-2.81-.85-5.65-1.6-8.56-2.43-.41,5.17,1.6,10.43,5.7,15.33,6.73,8,15.56,10.81,25.69,10.11,8-.55,14.7-4.22,20.81-9.26,4.43-3.66,9.15-7,13.74-10.46l2.15,11.54c-4.07,3.06-8.15,6.12-12.55,9.44a32,32,0,0,0,14.88,3.06l1.88,10.09a42.16,42.16,0,0,1-25.32-5.5,5.47,5.47,0,0,0-4.82-.65,43,43,0,0,1-24.3,1c-10.49-2.48-18.93-8.14-24.64-17.36A32.7,32.7,0,0,1,154.8,286c.17-2.33-.69-3.66-2.28-5.19-3-2.86-6.18-5.71-8.2-9.2-6.11-10.58-6.42-21.76-1.16-32.76,4.25-8.89,11.26-15.23,20.22-19.3a4.82,4.82,0,0,0,3-3.75c1.59-6.92,5.27-12.65,10.26-17.65a45.71,45.71,0,0,1,18.28-10.86L205,185.45l7,.19,2,10.57c-9.73-1.14-18.89.35-26.69,6.67-7.44,6-11.82,13.76-10.26,23.64,1.77,11.18,4,22.29,6.15,33.41a3.37,3.37,0,0,0,1.45,2.31c3.94,1.41,8,2.57,12.39,3.95-.21-1.5-.31-2.45-.48-3.38-2-10.9-3.76-21.85-6.12-32.67-1.09-4.94.45-7.95,4.27-10.77,7-5.15,13.77-10.61,20.64-15.94L217.42,215c-5.38,4.17-10.79,8.32-16.12,12.56-.89.71-2.15,1.91-2.05,2.74.5,4.07,1.39,8.09,2.23,12.58,3.36-2.61,6.33-5,9.35-7.23s6.12-4.48,9.19-6.71l2.15,11.54c-1.76-.13-3.42-1.58-5.31,0-4,3.21-8,6.3-12.09,9.39a3.39,3.39,0,0,0-1.4,3.8q1.37,6.56,2.46,13.18a3.35,3.35,0,0,0,2.7,3c4.21,1.2,8.49,2.23,12.57,3.78C223.93,274.64,226.08,274.31,228.08,272.18Zm-10.65,8.24c-2.28-.75-4-1.37-5.8-1.91q-17.38-5.28-34.77-10.52c-3.22-1-4.89-3-5.46-6.36-1.57-9.32-3.4-18.59-5.15-27.88-.19-1-.52-1.94-.8-3-8.69,4.09-14.33,13.77-14.64,23.16-.25,7.36,3.24,13.2,8.12,18.19a21.44,21.44,0,0,0,7.46,4.89c6.37,2.43,12.92,4.39,19.43,6.43,6,1.9,12.13,3.7,18.23,5.41a3.81,3.81,0,0,0,2.89-.4C210.35,286,213.64,283.36,217.43,280.42Z" transform="translate(-79.9 -86.03)"/></svg>

After

Width:  |  Height:  |  Size: 3.5 KiB

+563
View File
@@ -0,0 +1,563 @@
<?php
namespace Orhanerday\OpenAi;
use Exception;
class OpenAi
{
private string $engine = "davinci";
private string $model = "text-davinci-002";
private string $chatModel = "gpt-3.5-turbo";
private array $headers;
private array $contentTypes;
private int $timeout = 0;
private object $stream_method;
private string $customUrl = "";
private string $proxy = "";
private array $curlInfo = [];
public function __construct($OPENAI_API_KEY)
{
$this->contentTypes = [
"application/json" => "Content-Type: application/json",
"multipart/form-data" => "Content-Type: multipart/form-data",
];
$this->headers = [
$this->contentTypes["application/json"],
"Authorization: Bearer $OPENAI_API_KEY",
];
}
/**
* @return array
* Remove this method from your code before deploying
*/
public function getCURLInfo()
{
return $this->curlInfo;
}
/**
* @return bool|string
*/
public function listModels()
{
$url = Url::fineTuneModel();
$this->baseUrl($url);
return $this->sendRequest($url, 'GET');
}
/**
* @param $model
* @return bool|string
*/
public function retrieveModel($model)
{
$model = "/$model";
$url = Url::fineTuneModel().$model;
$this->baseUrl($url);
return $this->sendRequest($url, 'GET');
}
/**
* @param $opts
* @return bool|string
* @deprecated
*/
public function complete($opts)
{
$engine = $opts['engine'] ?? $this->engine;
$url = Url::completionURL($engine);
unset($opts['engine']);
$this->baseUrl($url);
return $this->sendRequest($url, 'POST', $opts);
}
/**
* @param $opts
* @param null $stream
* @return bool|string
* @throws Exception
*/
public function completion($opts, $stream = null)
{
if (array_key_exists('stream', $opts) && $opts['stream']) {
if ($stream == null) {
throw new Exception(
'Please provide a stream function. Check https://github.com/orhanerday/open-ai#stream-example for an example.'
);
}
$this->stream_method = $stream;
}
$opts['model'] = $opts['model'] ?? $this->model;
$url = Url::completionsURL();
$this->baseUrl($url);
return $this->sendRequest($url, 'POST', $opts);
}
/**
* @param $opts
* @return bool|string
*/
public function createEdit($opts)
{
$url = Url::editsUrl();
$this->baseUrl($url);
return $this->sendRequest($url, 'POST', $opts);
}
/**
* @param $opts
* @return bool|string
*/
public function image($opts)
{
$url = Url::imageUrl()."/generations";
$this->baseUrl($url);
return $this->sendRequest($url, 'POST', $opts);
}
/**
* @param $opts
* @return bool|string
*/
public function imageEdit($opts)
{
$url = Url::imageUrl()."/edits";
$this->baseUrl($url);
return $this->sendRequest($url, 'POST', $opts);
}
/**
* @param $opts
* @return bool|string
*/
public function createImageVariation($opts)
{
$url = Url::imageUrl()."/variations";
$this->baseUrl($url);
return $this->sendRequest($url, 'POST', $opts);
}
/**
* @param $opts
* @return bool|string
* @deprecated
*/
public function search($opts)
{
$engine = $opts['engine'] ?? $this->engine;
$url = Url::searchURL($engine);
unset($opts['engine']);
$this->baseUrl($url);
return $this->sendRequest($url, 'POST', $opts);
}
/**
* @param $opts
* @return bool|string
* @deprecated
*/
public function answer($opts)
{
$url = Url::answersUrl();
$this->baseUrl($url);
return $this->sendRequest($url, 'POST', $opts);
}
/**
* @param $opts
* @return bool|string
* @deprecated
*/
public function classification($opts)
{
$url = Url::classificationsUrl();
$this->baseUrl($url);
return $this->sendRequest($url, 'POST', $opts);
}
/**
* @param $opts
* @return bool|string
*/
public function moderation($opts)
{
$url = Url::moderationUrl();
$this->baseUrl($url);
return $this->sendRequest($url, 'POST', $opts);
}
/**
* @param $opts
* @param null $stream
* @return bool|string
* @throws Exception
*/
public function chat($opts, $stream = null)
{
if ($stream != null && array_key_exists('stream', $opts)) {
if (!$opts['stream']) {
throw new Exception(
'Please provide a stream function. Check https://github.com/orhanerday/open-ai#stream-example for an example.'
);
}
$this->stream_method = $stream;
}
$opts['model'] = $opts['model'] ?? $this->chatModel;
$url = Url::chatUrl();
$this->baseUrl($url);
return $this->sendRequest($url, 'POST', $opts);
}
/**
* @param $opts
* @return bool|string
*/
public function transcribe($opts)
{
$url = Url::transcriptionsUrl();
$this->baseUrl($url);
return $this->sendRequest($url, 'POST', $opts);
}
/**
* @param $opts
* @return bool|string
*/
public function translate($opts)
{
$url = Url::translationsUrl();
$this->baseUrl($url);
return $this->sendRequest($url, 'POST', $opts);
}
/**
* @param $opts
* @return bool|string
*/
public function uploadFile($opts)
{
$url = Url::filesUrl();
$this->baseUrl($url);
return $this->sendRequest($url, 'POST', $opts);
}
/**
* @return bool|string
*/
public function listFiles()
{
$url = Url::filesUrl();
$this->baseUrl($url);
return $this->sendRequest($url, 'GET');
}
/**
* @param $file_id
* @return bool|string
*/
public function retrieveFile($file_id)
{
$file_id = "/$file_id";
$url = Url::filesUrl().$file_id;
$this->baseUrl($url);
return $this->sendRequest($url, 'GET');
}
/**
* @param $file_id
* @return bool|string
*/
public function retrieveFileContent($file_id)
{
$file_id = "/$file_id/content";
$url = Url::filesUrl().$file_id;
$this->baseUrl($url);
return $this->sendRequest($url, 'GET');
}
/**
* @param $file_id
* @return bool|string
*/
public function deleteFile($file_id)
{
$file_id = "/$file_id";
$url = Url::filesUrl().$file_id;
$this->baseUrl($url);
return $this->sendRequest($url, 'DELETE');
}
/**
* @param $opts
* @return bool|string
*/
public function createFineTune($opts)
{
$url = Url::fineTuneUrl();
$this->baseUrl($url);
return $this->sendRequest($url, 'POST', $opts);
}
/**
* @return bool|string
*/
public function listFineTunes()
{
$url = Url::fineTuneUrl();
$this->baseUrl($url);
return $this->sendRequest($url, 'GET');
}
/**
* @param $fine_tune_id
* @return bool|string
*/
public function retrieveFineTune($fine_tune_id)
{
$fine_tune_id = "/$fine_tune_id";
$url = Url::fineTuneUrl().$fine_tune_id;
$this->baseUrl($url);
return $this->sendRequest($url, 'GET');
}
/**
* @param $fine_tune_id
* @return bool|string
*/
public function cancelFineTune($fine_tune_id)
{
$fine_tune_id = "/$fine_tune_id/cancel";
$url = Url::fineTuneUrl().$fine_tune_id;
$this->baseUrl($url);
return $this->sendRequest($url, 'POST');
}
/**
* @param $fine_tune_id
* @return bool|string
*/
public function listFineTuneEvents($fine_tune_id)
{
$fine_tune_id = "/$fine_tune_id/events";
$url = Url::fineTuneUrl().$fine_tune_id;
$this->baseUrl($url);
return $this->sendRequest($url, 'GET');
}
/**
* @param $fine_tune_id
* @return bool|string
*/
public function deleteFineTune($fine_tune_id)
{
$fine_tune_id = "/$fine_tune_id";
$url = Url::fineTuneModel().$fine_tune_id;
$this->baseUrl($url);
return $this->sendRequest($url, 'DELETE');
}
/**
* @param
* @return bool|string
* @deprecated
*/
public function engines()
{
$url = Url::enginesUrl();
$this->baseUrl($url);
return $this->sendRequest($url, 'GET');
}
/**
* @param $engine
* @return bool|string
* @deprecated
*/
public function engine($engine)
{
$url = Url::engineUrl($engine);
$this->baseUrl($url);
return $this->sendRequest($url, 'GET');
}
/**
* @param $opts
* @return bool|string
*/
public function embeddings($opts)
{
$url = Url::embeddings();
$this->baseUrl($url);
return $this->sendRequest($url, 'POST', $opts);
}
/**
* @param int $timeout
*/
public function setTimeout(int $timeout)
{
$this->timeout = $timeout;
}
/**
* @param string $proxy
*/
public function setProxy(string $proxy)
{
if ($proxy && strpos($proxy, '://') === false) {
$proxy = 'https://'.$proxy;
}
$this->proxy = $proxy;
}
/**
* @param string $customUrl
* @deprecated
*/
/**
* @param string $customUrl
* @return void
*/
public function setCustomURL(string $customUrl)
{
if ($customUrl != "") {
$this->customUrl = $customUrl;
}
}
/**
* @param string $customUrl
* @return void
*/
public function setBaseURL(string $customUrl)
{
if ($customUrl != '') {
$this->customUrl = $customUrl;
}
}
/**
* @param array $header
* @return void
*/
public function setHeader(array $header)
{
if ($header) {
foreach ($header as $key => $value) {
$this->headers[$key] = $value;
}
}
}
/**
* @param string $org
*/
public function setORG(string $org)
{
if ($org != "") {
$this->headers[] = "OpenAI-Organization: $org";
}
}
/**
* @param string $url
* @param string $method
* @param array $opts
* @return bool|string
*/
private function sendRequest(string $url, string $method, array $opts = [])
{
$post_fields = json_encode($opts);
if (array_key_exists('file', $opts) || array_key_exists('image', $opts)) {
$this->headers[0] = $this->contentTypes["multipart/form-data"];
$post_fields = $opts;
} else {
$this->headers[0] = $this->contentTypes["application/json"];
}
$curl_info = [
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => '',
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => $this->timeout,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => $method,
CURLOPT_POSTFIELDS => $post_fields,
CURLOPT_HTTPHEADER => $this->headers,
];
if ($opts == []) {
unset($curl_info[CURLOPT_POSTFIELDS]);
}
if (!empty($this->proxy)) {
$curl_info[CURLOPT_PROXY] = $this->proxy;
}
if (array_key_exists('stream', $opts) && $opts['stream']) {
$curl_info[CURLOPT_WRITEFUNCTION] = $this->stream_method;
}
$curl = curl_init();
curl_setopt_array($curl, $curl_info);
$response = curl_exec($curl);
$info = curl_getinfo($curl);
$this->curlInfo = $info;
curl_close($curl);
return $response;
}
/**
* @param string $url
*/
private function baseUrl(string &$url)
{
if ($this->customUrl != "") {
$url = str_replace(Url::ORIGIN, $this->customUrl, $url);
}
}
}
+163
View File
@@ -0,0 +1,163 @@
<?php
namespace Orhanerday\OpenAi;
class Url
{
public const ORIGIN = 'https://api.openai.com';
public const API_VERSION = 'v1';
public const OPEN_AI_URL = self::ORIGIN . "/" . self::API_VERSION;
/**
* @deprecated
* @param string $engine
* @return string
*/
public static function completionURL(string $engine): string
{
return self::OPEN_AI_URL . "/engines/$engine/completions";
}
/**
* @return string
*/
public static function completionsURL(): string
{
return self::OPEN_AI_URL . "/completions";
}
/**
*
* @return string
*/
public static function editsUrl(): string
{
return self::OPEN_AI_URL . "/edits";
}
/**
* @param string $engine
* @return string
*/
public static function searchURL(string $engine): string
{
return self::OPEN_AI_URL . "/engines/$engine/search";
}
/**
* @param
* @return string
*/
public static function enginesUrl(): string
{
return self::OPEN_AI_URL . "/engines";
}
/**
* @param string $engine
* @return string
*/
public static function engineUrl(string $engine): string
{
return self::OPEN_AI_URL . "/engines/$engine";
}
/**
* @param
* @return string
*/
public static function classificationsUrl(): string
{
return self::OPEN_AI_URL . "/classifications";
}
/**
* @param
* @return string
*/
public static function moderationUrl(): string
{
return self::OPEN_AI_URL . "/moderations";
}
/**
* @param
* @return string
*/
public static function transcriptionsUrl(): string
{
return self::OPEN_AI_URL . "/audio/transcriptions";
}
/**
* @param
* @return string
*/
public static function translationsUrl(): string
{
return self::OPEN_AI_URL . "/audio/translations";
}
/**
* @param
* @return string
*/
public static function filesUrl(): string
{
return self::OPEN_AI_URL . "/files";
}
/**
* @param
* @return string
*/
public static function fineTuneUrl(): string
{
return self::OPEN_AI_URL . "/fine-tunes";
}
/**
* @param
* @return string
*/
public static function fineTuneModel(): string
{
return self::OPEN_AI_URL . "/models";
}
/**
* @param
* @return string
*/
public static function answersUrl(): string
{
return self::OPEN_AI_URL . "/answers";
}
/**
* @param
* @return string
*/
public static function imageUrl(): string
{
return self::OPEN_AI_URL . "/images";
}
/**
* @param
* @return string
*/
public static function embeddings(): string
{
return self::OPEN_AI_URL . "/embeddings";
}
/**
* @param
* @return string
*/
public static function chatUrl(): string
{
return self::OPEN_AI_URL . "/chat/completions";
}
}