easygithdev / phpopenai
Requires
- php: >=8.1
- ext-curl: *
Requires (Dev)
- friendsofphp/php-cs-fixer: ^3.0
- phpunit/phpunit: ^9.5
README
PHPOpenAI
是一个社区维护的库,它允许在PHP中使用OpenAI
API。
该项目是用PHP编写的,可以轻松地将OpenAI API
集成到现有的PHP项目中。
系统要求
该项目基于PHP 8.1版本,以使用枚举等特性。该项目不需要任何外部依赖。但是,您必须安装cURL扩展才能正常工作。
- PHP版本 >= 8.1
- cURL扩展
安装
该项目使用Composer来管理依赖。如果您尚未安装Composer,可以按照官方Composer网站上的说明进行安装。
Packagist安装
要安装该项目,您可以使用以下命令从packagist.org安装包
composer require easygithdev/php-openai
编写第一个示例
要使用OpenAI API
,您需要在他们的网站上注册并获取API密钥。一旦您有了API密钥,您就可以在PHP代码中使用它来向OpenAI API发送请求。
要了解如何获取您的密钥,请访问以下地址
https://help.openai.com/en/articles/4936850-where-do-i-find-my-secret-api-key.
以下是一个示例代码,展示了如何在PHP中使用OpenAI API
<?php require_once __DIR__ . '/vendor/autoload.php'; use EasyGithDev\PHPOpenAI\Helpers\ModelEnum; use EasyGithDev\PHPOpenAI\OpenAIClient; $apiKey = getenv('OPENAI_API_KEY'); $response = (new OpenAIClient($apiKey))->Completion()->create( ModelEnum::TEXT_DAVINCI_003, "Say this is a test", )->toObject(); // Response as stClass object echo '<pre>', print_r($response, true), '</pre>';
此代码使用API密钥创建一个新的OpenAIApi
对象,然后创建一个新的Completion
对象以使用OpenAI提供的GPT-3 AI语言模型进行文本完成。
在Completion
对象上调用create()
方法以生成新的文本完成。它接受两个参数
- 第一个参数是要用于完成的GPT-3模型的ID。在这种情况下,它使用TEXT_DAVINCI_003模型。
- 第二个参数是要生成的完成的提示或输入文本。在这种情况下,提示是"Say this is a test"。
完成的结果存储在$response
变量中。然后可以进一步处理结果,例如显示完成的文本或将其输入到程序的另一部分进行进一步处理。
管理API密钥
您可以使用环境变量来存储您的密钥。然后您可以在以下示例中使用此变量
export OPENAI_API_KEY="sk-xxxxxxxxxxx"
您可以将变量放入Apache配置文件中
<VirtualHost hostname:80>
...
SetEnv OPENAI_API_KEY sk-xxxxxxxxxxx
...
</VirtualHost>
然后重启服务。
现在,您可以通过调用PHP的getenv()
函数来使用环境变量。
<?php $response = (new OpenAIApi(getenv('OPENAI_API_KEY')))->Completion()->create( ModelEnum::TEXT_DAVINCI_003, "Say this is a test", );
管理组织
如果您想提供关于您组织的资料,请按照以下步骤进行。
<?php $apiKey = getenv('OPENAI_API_KEY'); $org = getenv('OPENAI_API_ORG'); // Passing the organization to the client $response = (new OpenAIClient($apiKey, $org))
管理API的URL
如果您需要修改API的URL,可以按照以下步骤进行
<?php $apiKey = getenv('OPENAI_API_KEY'); // Create a new router, with origine url and version $route = new OpenAIRoute( 'https://api.openai.com', 'v1' ); // Get a specific Url echo $route->completionCreate() , '<br>'; // Passing the router to the client $response = (new OpenAIClient($apiKey)) ->setRoute($route);
要重新定义路由,您需要扩展OpenAIRoute
类或实现Route
接口。
管理响应
API以JSON格式返回响应。为了便于访问不同的信息,您可以通过调用Handler对象的toObject()
或toArray()
方法来访问数据。
<?php $response = (new OpenAIClient($apiKey))->Completion()->create( ModelEnum::TEXT_DAVINCI_003, "Say this is a test", )->toObject(); // Response as a stClass object echo '<pre>', print_r($response, true), '</pre>'; $response = (new OpenAIClient($apiKey))->Completion()->create( ModelEnum::TEXT_DAVINCI_003, "Say this is a test", )->toArray(); // Response as an associative array echo '<pre>', print_r($response, true), '</pre>';
管理错误
有时,API会返回错误。因此,有必要能够识别导致问题的原因。为了处理这个困难,您有很多选择。
如果您使用的是具有toObject()
或toArray()
方法的Handler对象,只需使用try-catch
结构。
try { $response = (new OpenAIClient('BAD KEY')) ->Completion() ->create( ModelEnum::TEXT_DAVINCI_003, "Say this is a test", ) ->toObject(); } catch (Throwable $t) { echo nl2br($t->getMessage()); die; }
如果您使用的是CurlResponse
对象,可以使用验证器来检查是否发生了错误。
$handler = (new OpenAIClient('BAD KEY'))->Completion()->create( ModelEnum::TEXT_DAVINCI_003, "Say this is a test", ); $response = $handler->getResponse(); $contentTypeValidator = $handler->getContentTypeValidator(); if (!(new StatusValidator($response))->validate() or !(new $contentTypeValidator($response))->validate()) { echo $response->getBody(); }
应用程序示例
以下是一个视频,展示了一个允许您使用用户定义的绘画风格创建图像的应用程序。此应用程序使用PHPOpenAI项目创建。
playground.mp4
您可以在以下位置找到代码
https://github.com/EasyGithDev/PHPOpenAI-Playground.git.
代码示例
将OpenAI集成到您的应用程序中现在就像几行代码那么简单。
您可以在以下位置找到所有代码
https://github.com/EasyGithDev/PHPOpenAI-Examples.
使用ChatGPT进行文本补全
$response = (new OpenAIClient($apiKey))->Chat()->create( ModelEnum::GPT_3_5_TURBO, [ new ChatMessage(ChatMessage::ROLE_SYSTEM, "You are a helpful assistant."), new ChatMessage(ChatMessage::ROLE_USER, "Who won the world series in 2020?"), new ChatMessage(ChatMessage::ROLE_ASSISTANT, "The Los Angeles Dodgers won the World Series in 2020."), new ChatMessage(ChatMessage::ROLE_USER, "Where was it played?"), ] )->toObject();
使用GPT-3进行文本补全
$response = (new OpenAIClient($apiKey))->Completion()->create( ModelEnum::TEXT_DAVINCI_003, "Say this is a test", )->toObject();
使用流进行文本补全
OpenAI API中的stream属性是一个可选参数,您可以使用它来控制API返回的数据流。如果您将此选项设置为True,API将以流数据的形式返回响应,而不是单个响应。
这意味着您可以在数据可用时检索API的结果,而不是在处理之前等待完整的响应。此选项对于需要实时处理大量数据的程序很有用。
openai-completion-stream.mp4
<?php header('Content-Type: text/event-stream'); header('Cache-Control: no-cache'); ... (new OpenAIClient($apiKey))->Completion()->create( model: "text-davinci-003", prompt: "Translate this into 1. French, 2. Spanish and 3. Japanese:\n\nWhat rooms do you have available?\n\n1.", temperature: 0.3, max_tokens: 100, top_p: 1.0, frequency_penalty: 0.0, presence_penalty: 0.0, stream: true )->getResponse();
<html> <body> <div id="result"></div> <script> function nl2br(str, replaceMode, isXhtml) { var breakTag = (isXhtml) ? '<br />' : '<br>'; var replaceStr = (replaceMode) ? '$1' + breakTag : '$1' + breakTag + '$2'; return (str + '').replace(/([^>\r\n]?)(\r\n|\n\r|\r|\n)/g, replaceStr); } if (typeof (EventSource) !== 'undefined') { console.info('Starting connection...'); var source = new EventSource('stream.php'); source.addEventListener('open', function (e) { console.info('Connection was opened.'); }, false); source.addEventListener('error', function (e) { var txt; switch (event.target.readyState) { // if reconnecting case EventSource.CONNECTING: txt = 'Reconnecting...'; break; // if error was fatal case EventSource.CLOSED: txt = 'Connection failed. Will not retry.'; break; } console.error('Connection error: ' + txt); }, false); source.addEventListener('message', function (e) { if (e.data == "[DONE]") { source.close(); return; } document.getElementById('result').innerHTML += nl2br(JSON.parse(e.data).choices[0].text); }, false); } else { alert('Your browser does not support Server-sent events! Please upgrade it!'); console.error('Connection aborted'); } </script> </body> </html>
文本编辑
$response = (new OpenAIClient($apiKey))->Edit()->create( "What day of the wek is it?", ModelEnum::TEXT_DAVINCI_EDIT_001, "Fix the spelling mistakes", )->toObject();
使用DALL·E进行图像生成
function displayUrl($url) { return '<img src="' . $url . '" />'; } $response = (new OpenAIClient($apiKey))->Image()->create( "a rabbit inside a beautiful garden, 32 bit isometric", n: 2, size: ImageSizeEnum::is256, )->toObject();
<?php foreach ($response->data as $image) : ?> <div> <?= displayUrl($image->url) ?> </div> <?php endforeach; ?>
使用DALL·E进行图像变体
$response = (new OpenAIClient($apiKey))->Image()->createVariation( __DIR__ . '/../../assets/image_variation_original.png', n: 2, size: ImageSizeEnum::is256 )->toObject();
使用DALL·E进行图像编辑
$response = (new OpenAIClient($apiKey))->Image()->createEdit( image: __DIR__ . '/../../assets/image_edit_original.png', mask: __DIR__ . '/../../assets/image_edit_mask2.png', prompt: 'a sunlit indoor lounge area with a pool containing a flamingo', size: ImageSizeEnum::is512, )->toObject();
嵌入
$response = (new OpenAIClient($apiKey))->Embedding()->create( ModelEnum::TEXT_EMBEDDING_ADA_002, "The food was delicious and the waiter...", )->toObject();
音频转写(语音转文本)使用Whisper
$response = (new OpenAIClient($apiKey))->Audio() ->addCurlParam('timeout', 30) ->transcription( __DIR__ . '/../../assets/openai.mp3', ModelEnum::WHISPER_1, response_format: AudioResponseEnum::SRT )->toObject();
音频翻译(语音转文本)使用Whisper
$response = (new OpenAIClient($apiKey))->Audio() ->addCurlParam('timeout', 30) ->translation( __DIR__ . '/../../assets/openai_fr.mp3', 'whisper-1', response_format: AudioResponseEnum::TEXT )->toObject();
模型列表
$response = (new OpenAIClient($apiKey)) ->Model() ->list() ->toObject();
模型检索
$response = (new OpenAIClient($apiKey)) ->Model() ->retrieve('text-davinci-001') ->toObject();
模型删除
$response = (new OpenAIClient($apiKey)) ->Model() ->delete( $_POST['model'] )->toObject();
文件列表
$response = (new OpenAIApi($apiKey)) ->File() ->list() ->toObject();
文件上传
$response = (new OpenAIApi($apiKey)) ->File() ->create( __DIR__ . '/../../assets/mydata.jsonl', 'fine-tune', ) ->toObject();
文件删除
$response = (new OpenAIApi($apiKey)) ->File() ->delete('file-xxxx') ->toObject();
文件检索
$response = (new OpenAIApi($apiKey)) ->File() ->retrieve('file-xxxx') ->toObject();
文件检索内容
$response = (new OpenAIApi($apiKey)) ->File() ->download('file-xxxx') ->toObject();
微调列表
$response = (new OpenAIApi($apiKey)) ->FineTune() ->list() ->toObject();
微调创建
$response = (new OpenAIApi($apiKey)) ->FineTune() ->create( 'file-xxxx' ) ->toObject();
微调检索
$response = (new OpenAIApi($apiKey)) ->FineTune() ->retrieve('ft-xxx') ->toObject();
微调列表事件
$response = (new OpenAIApi($apiKey)) ->FineTune() ->listEvents('ft-xxx') ->toObject();
微调取消
$response = (new OpenAIApi($apiKey)) ->FineTune() ->Cancel('ft-xxx') ->toObject();
内容审核
$response = (new OpenAIClient($apiKey)) ->Moderation() ->create('I want to kill them.') ->toObject();
测试
运行所有测试
composer test tests
仅运行一个测试
composer test tests/[NAME]Test.php
摘要
PHPOpenAI是一个对PHP开发者有用的项目,它可以帮助开发者轻松地将OpenAI API集成到他们的项目中。通过简单的安装和使用Composer,您可以将文本分类、图像生成和命名实体识别等功能集成到PHP应用程序中。