softcreatr / php-openai-sdk
A powerful and easy-to-use PHP SDK for the OpenAI API, allowing seamless integration of advanced AI-powered features into your PHP projects.
Fund package maintenance!
softcreatr
ecologi.com/softcreatr?r=61212ab3fc69b8eb8a2014f4
Requires
- php: >=8.1
- ext-json: *
- psr/http-client: *
- psr/http-factory: *
- psr/http-message: *
Requires (Dev)
- friendsofphp/php-cs-fixer: >=3
- guzzlehttp/guzzle: >=7
- phpunit/phpunit: >=10
README
This PHP library provides a simple wrapper for the OpenAI API, allowing you to easily integrate the OpenAI API into your PHP projects.
Features
- Easy integration with OpenAI API
- Supports all OpenAI API endpoints
- Streaming support for real-time responses in chat completions
- Utilizes PSR-17 and PSR-18 compliant HTTP clients and factories for making API requests
Requirements
- PHP 8.1 or higher
- A PSR-17 HTTP Factory implementation (e.g., guzzle/psr7 or nyholm/psr7)
- A PSR-18 HTTP Client implementation (e.g., guzzlehttp/guzzle or symfony/http-client)
Installation
You can install the library via Composer:
composer require softcreatr/php-openai-sdk
Usage
First, include the library in your project:
<?php require_once 'vendor/autoload.php';
Then, create an instance of the OpenAI
class with your API key, organization (optional), an HTTP client, an HTTP request factory, and an HTTP stream factory:
use SoftCreatR\OpenAI\OpenAI; $apiKey = 'your_api_key'; $organization = 'your_organization_id'; // optional // Replace these lines with your chosen PSR-17 and PSR-18 compatible HTTP client and factories $httpClient = new YourChosenHttpClient(); $requestFactory = new YourChosenRequestFactory(); $streamFactory = new YourChosenStreamFactory(); $uriFactory = new YourChosenUriFactory(); $openAI = new OpenAI($requestFactory, $streamFactory, $uriFactory, $httpClient, $apiKey, $organization);
Now you can call any supported OpenAI API endpoint using the magic method __call
:
$response = $openAI->createChatCompletion([ 'model' => 'gpt-4', 'messages' => [ ['role' => 'system', 'content' => 'You are a helpful assistant.'], ['role' => 'user', 'content' => 'Hello!'], ], ]); // Process the API response if ($response->getStatusCode() === 200) { $responseObj = json_decode($response->getBody()->getContents(), true); print_r($responseObj); } else { echo "Error: " . $response->getStatusCode(); }
Streaming Example
You can enable real-time streaming for chat completions:
$streamCallback = static function ($data) { if (isset($data['choices'][0]['delta']['content'])) { echo $data['choices'][0]['delta']['content']; } }; $openAI->createChatCompletion( [ 'model' => 'gpt-4', 'messages' => [ [ 'role' => 'user', 'content' => 'Tell me a story about a brave knight.', ], ], 'stream' => true, ], $streamCallback );
For more details on how to use each endpoint, refer to the OpenAI API documentation, and the examples provided in the repository.
Supported Methods
Below is a list of supported methods organized by category. Each method links to its corresponding OpenAI API documentation and includes a link to an example in this repository.
Audio
- Create Transcription - API Reference - Example
createTranscription(array $options = [])
- Create Translation - API Reference - Example
createTranslation(array $options = [])
- Create Speech - API Reference - Example
createSpeech(array $options = [])
Chat
- Create Chat Completion - API Reference - Example
createChatCompletion(array $options = [])
Embeddings
- Create Embedding - API Reference - Example
createEmbedding(array $options = [])
Fine-tuning
- Create Fine-tuning Job - API Reference - Example
createFineTuningJob(array $options = [])
- List Fine-tuning Jobs - API Reference - Example
listFineTuningJobs()
- Retrieve Fine-tuning Job - API Reference - Example
retrieveFineTuningJob(array $parameters)
- Cancel Fine-tuning Job - API Reference - Example
cancelFineTuning(array $parameters)
- List Fine-tuning Events - API Reference - Example
listFineTuningEvents(array $parameters, array $options = [])
Batch
- Create Batch - API Reference - Example
createBatch(array $options = [])
- Retrieve Batch - API Reference - Example
retrieveBatch(array $parameters)
- Cancel Batch - API Reference - Example
cancelBatch(array $parameters)
- List Batches - API Reference - Example
listBatches()
Files
- List Files - API Reference - Example
listFiles()
- Upload File - API Reference - Example
uploadFile(array $options = [])
- Delete File - API Reference - Example
deleteFile(array $parameters)
- Retrieve File - API Reference - Example
retrieveFile(array $parameters)
- Download File - API Reference - Example
retrieveFileContent(array $parameters)
Uploads
- Create Upload - API Reference - Example
createUpload(array $options = [])
- Add Upload Part - API Reference - Example
addUploadPart(array $parameters, array $options = [])
- Complete Upload - API Reference - Example
completeUpload(array $parameters)
- Cancel Upload - API Reference - Example
cancelUpload(array $parameters)
Images
- Create Image - API Reference - Example
createImage(array $options = [])
- Create Image Edit - API Reference - Example
createImageEdit(array $options = [])
- Create Image Variation - API Reference - Example
createImageVariation(array $options = [])
Models
- List Models - API Reference - Example
listModels()
- Retrieve Model - API Reference - Example
retrieveModel(array $parameters)
- Delete Model - API Reference - Example
deleteModel(array $parameters)
Moderations
- Create Moderation - API Reference - Example
createModeration(array $options = [])
Assistants
Assistants
- Create Assistant - API Reference - Example
createAssistant(array $options = [])
- List Assistants - API Reference - Example
listAssistants()
- Retrieve Assistant - API Reference - Example
retrieveAssistant(array $parameters)
- Modify Assistant - API Reference - Example
modifyAssistant(array $parameters, array $options = [])
- Delete Assistant - API Reference - Example
deleteAssistant(array $parameters)
Threads
- Create Thread - API Reference - Example
createThread(array $options = [])
- Retrieve Thread - API Reference - Example
retrieveThread(array $parameters)
- Modify Thread - API Reference - Example
modifyThread(array $parameters, array $options = [])
- Delete Thread - API Reference - Example
deleteThread(array $parameters)
Messages
- Create Message - API Reference - Example
createMessage(array $parameters, array $options = [])
- List Messages - API Reference - Example
listMessages(array $parameters)
- Retrieve Message - API Reference - Example
retrieveMessage(array $parameters)
- Modify Message - API Reference - Example
modifyMessage(array $parameters, array $options = [])
- Delete Message - API Reference - Example
deleteMessage(array $parameters)
Runs
- Create Run - API Reference - Example
createRun(array $parameters, array $options = [])
- Create Thread and Run - API Reference - Example
createThreadAndRun(array $options = [])
- List Runs - API Reference - Example
listRuns(array $parameters)
- Retrieve Run - API Reference - Example
retrieveRun(array $parameters)
- Modify Run - API Reference - Example
modifyRun(array $parameters, array $options = [])
- Submit Tool Outputs to Run - API Reference - Example
submitToolOutputsToRun(array $parameters, array $options = [])
- Cancel Run - API Reference - Example
cancelRun(array $parameters)
Run Steps
- List Run Steps - API Reference - Example
listRunSteps(array $parameters)
- Retrieve Run Step - API Reference - Example
retrieveRunStep(array $parameters)
Vector Stores
- Create Vector Store - API Reference - Example
createVectorStore(array $options = [])
- List Vector Stores - API Reference - Example
listVectorStores()
- Retrieve Vector Store - API Reference - Example
retrieveVectorStore(array $parameters)
- Modify Vector Store - API Reference - Example
modifyVectorStore(array $parameters, array $options = [])
- Delete Vector Store - API Reference - Example
deleteVectorStore(array $parameters)
Vector Store Files
- Create Vector Store File - API Reference - Example
createVectorStoreFile(array $parameters, array $options = [])
- List Vector Store Files - API Reference - Example
listVectorStoreFiles(array $parameters)
- Retrieve Vector Store File - API Reference - Example
retrieveVectorStoreFile(array $parameters)
- Delete Vector Store File - API Reference - Example
deleteVectorStoreFile(array $parameters)
Vector Store File Batches
- Create Vector Store File Batch - API Reference - Example
createVectorStoreFileBatch(array $parameters, array $options = [])
- Retrieve Vector Store File Batch - API Reference - Example
retrieveVectorStoreFileBatch(array $parameters)
- Cancel Vector Store File Batch - API Reference - Example
cancelVectorStoreFileBatch(array $parameters)
- List Vector Store Files in Batch - API Reference - Example
listVectorStoreFilesInBatch(array $parameters)
Administration
Invites
- List Invites - API Reference - Example
listInvites()
- Create Invite - API Reference - Example
createInvite(array $options = [])
- Retrieve Invite - API Reference - Example
retrieveInvite(array $parameters)
- Delete Invite - API Reference - Example
deleteInvite(array $parameters)
Users
- List Users - API Reference - Example
listUsers()
- Modify User - API Reference - Example
modifyUser(array $parameters, array $options = [])
- Retrieve User - API Reference - Example
retrieveUser(array $parameters)
- Delete User - API Reference - Example
deleteUser(array $parameters)
Projects
- List Projects - API Reference - Example
listProjects()
- Create Project - API Reference - Example
createProject(array $options = [])
- Retrieve Project - API Reference - Example
retrieveProject(array $parameters)
- Modify Project - API Reference - Example
modifyProject(array $parameters, array $options = [])
- Archive Project - API Reference - Example
archiveProject(array $parameters)
Project Users
- List Project Users - API Reference - Example
listProjectUsers(array $parameters)
- Create Project User - API Reference - Example
createProjectUser(array $parameters, array $options = [])
- Retrieve Project User - API Reference - Example
retrieveProjectUser(array $parameters)
- Modify Project User - API Reference - Example
modifyProjectUser(array $parameters, array $options = [])
- Delete Project User - API Reference - Example
deleteProjectUser(array $parameters)
Project Service Accounts
- List Project Service Accounts - API Reference - Example
listProjectServiceAccounts(array $parameters)
- Create Project Service Account - API Reference - Example
createProjectServiceAccount(array $parameters, array $options = [])
- Retrieve Project Service Account - API Reference - Example
retrieveProjectServiceAccount(array $parameters)
- Delete Project Service Account - API Reference - Example
deleteProjectServiceAccount(array $parameters)
Project API Keys
- List Project API Keys - API Reference - Example
listProjectApiKeys(array $parameters)
- Retrieve Project API Key - API Reference - Example
retrieveProjectApiKey(array $parameters)
- Delete Project API Key - API Reference - Example
deleteProjectApiKey(array $parameters)
Audit Logs
- List Audit Logs - API Reference - Example
listAuditLogs(array $options = [])
Changelog
For a detailed list of changes and updates, please refer to the CHANGELOG.md file. We adhere to Semantic Versioning and document notable changes for each release.
Known Problems and Limitations
Streaming Support
Streaming is now supported for real-time token generation in chat completions. Please make sure you are handling streams correctly using a callback, as demonstrated in the examples.
License
This library is licensed under the ISC License. See the LICENSE file for more information.