PHP code example of softcreatr / php-openai-sdk

1. Go to this page and download the library: Download softcreatr/php-openai-sdk library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

softcreatr / php-openai-sdk example snippets





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);

$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();
}

$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
);
bash
composer