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.

3.1.0 2025-04-23 10:13 UTC

This package is auto-updated.

Last update: 2025-04-23 10:35:34 UTC


README

Build Latest Release ISC licensed Plant Tree Codecov branch Code Climate maintainability

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

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

Responses

Chat

  • Create Chat CompletionAPI ReferenceExample
    createChatCompletion(array $options = [], ?callable $streamCallback = null)
  • Get Chat CompletionAPI ReferenceExample
    getChatCompletion(array $parameters)
  • Get Chat MessagesAPI ReferenceExample
    getChatMessages(array $parameters)
  • List Chat CompletionsAPI ReferenceExample
    listChatCompletions(array $options = [])
  • Update Chat CompletionAPI ReferenceExample
    updateChatCompletion(array $parameters, array $options = [])
  • Delete Chat CompletionAPI ReferenceExample
    deleteChatCompletion(array $parameters)

Embeddings

Fine-tuning

  • Create Fine-tuning JobAPI ReferenceExample
    createFineTuningJob(array $options = [])
  • List Fine-tuning JobsAPI ReferenceExample
    listFineTuningJobs(array $options = [])
  • List Fine-tuning EventsAPI ReferenceExample
    listFineTuningEvents(array $parameters, array $options = [])
  • List Fine-tuning CheckpointsAPI ReferenceExample
    listFineTuningCheckpoints(array $parameters, array $options = [])
  • Retrieve Fine-tuning JobAPI ReferenceExample
    retrieveFineTuningJob(array $parameters)
  • Cancel Fine-tuning JobAPI ReferenceExample
    cancelFineTuning(array $parameters)

Batch

Files

Uploads

Images

Models

Moderations

Assistants

Threads

Messages

Runs

Run Steps

Vector Stores

Vector Store Files

  • Create Vector Store FileAPI ReferenceExample
    createVectorStoreFile(array $parameters, array $options = [])
  • List Vector Store FilesAPI ReferenceExample
    listVectorStoreFiles(array $parameters)
  • Retrieve vector store file contentAPI ReferenceExample
    listVectorStoreFiles(array $parameters)
  • Update vector store file attributesAPI ReferenceExample
    listVectorStoreFiles(array $parameters)
  • Retrieve Vector Store FileAPI ReferenceExample
    retrieveVectorStoreFile(array $parameters)
  • Delete Vector Store FileAPI ReferenceExample
    deleteVectorStoreFile(array $parameters)

Vector Store File Batches

  • Create Vector Store File BatchAPI ReferenceExample
    createVectorStoreFileBatch(array $parameters, array $options = [])
  • Retrieve Vector Store File BatchAPI ReferenceExample
    retrieveVectorStoreFileBatch(array $parameters)
  • Cancel Vector Store File BatchAPI ReferenceExample
    cancelVectorStoreFileBatch(array $parameters)
  • List Vector Store Files in BatchAPI ReferenceExample
    listVectorStoreFilesInBatch(array $parameters)

Administration

Invites

Users

Admin API Keys

Certificates

Rate Limits

  • List Project Rate LimitsAPI ReferenceExample
    listProjectRateLimits(array $parameters)
  • Modify Project Rate LimitAPI ReferenceExample
    modifyProjectRateLimit(array $parameters, array $options = [])

Usage

Projects

Project Users

Project Service Accounts

  • List Project Service AccountsAPI ReferenceExample
    listProjectServiceAccounts(array $parameters)
  • Create Project Service AccountAPI ReferenceExample
    createProjectServiceAccount(array $parameters, array $options = [])
  • Retrieve Project Service AccountAPI ReferenceExample
    retrieveProjectServiceAccount(array $parameters)
  • Delete Project Service AccountAPI ReferenceExample
    deleteProjectServiceAccount(array $parameters)

Project API Keys

Audit Logs

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.

Maintainers 🛠️

Sascha Greuel
Sascha Greuel

Contributors ✨