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




declare(strict_types=1);

leHttp\Psr7\HttpFactory;
use SoftCreatR\OpenAI\OpenAI;

$factory = new HttpFactory();
$openAI = new OpenAI(
    requestFactory: $factory,
    streamFactory: $factory,
    uriFactory: $factory,
    httpClient: new Client(['stream' => true]),
    apiKey: (string) getenv('OPENAI_API_KEY'),
    organization: (string) getenv('OPENAI_ORGANIZATION_ID'),
    project: (string) getenv('OPENAI_PROJECT_ID'),
);

use const JSON_THROW_ON_ERROR;

$response = $openAI->createResponse([
    'model' => 'gpt-5.4-mini',
    'input' => 'Give me a one-sentence summary of PSR-18.',
]);

$result = json_decode((string) $response->getBody(), true, 512, JSON_THROW_ON_ERROR);
echo $result['output'][0]['content'][0]['text'];

$openAI->createEmbedding([
    'model' => 'text-embedding-3-small',
    'input' => 'A sentence to embed.',
]);

$openAI->updateConversation([
    'conversation_id' => 'conv_abc123',
    'metadata' => ['customer' => 'acme'],
]);

$openAI->updateConversation(
    ['conversation_id' => 'conv_abc123'],
    ['metadata' => ['customer' => 'acme']],
);

$response = $openAI->request(
    'listFiles',
    ['limit' => 20, 'after' => 'file_abc123'],
    customHeaders: ['X-Trace-Id' => 'trace_abc123'],
);

$openAI->createResponse(
    [
        'model' => 'gpt-5.4-mini',
        'input' => 'Write a short haiku about PHP.',
        'stream' => true,
    ],
    static function (array $event): void {
        if ($event['type'] === 'response.output_text.delta') {
            echo $event['delta'];
        }
    },
);

$response = $openAI->uploadFile([
    'file' => __DIR__ . '/data.jsonl',
    'purpose' => 'user_data',
]);

use SoftCreatR\OpenAI\Exception\OpenAIException;

try {
    $openAI->retrieveModel(['model' => 'missing-model']);
} catch (OpenAIException $exception) {
    error_log(sprintf(
        'OpenAI request %s failed (%d): %s',
        $exception->getRequestId() ?? 'unknown',
        $exception->getCode(),
        $exception->getMessage(),
    ));
}

use SoftCreatR\OpenAI\Webhook\WebhookVerifier;

$rawBody = (string) $request->getBody();
$event = (new WebhookVerifier((string) getenv('OPENAI_WEBHOOK_SECRET')))
    ->unwrap($rawBody, $request->getHeaders());

if ($event['type'] === 'response.completed') {
    // Handle the completed response idempotently.
}

$openAI = new OpenAI(
    requestFactory: $factory,
    streamFactory: $factory,
    uriFactory: $factory,
    httpClient: new Client(['stream' => true]),
    apiKey: (string) getenv('OPENAI_API_KEY'),
    origin: 'https://gateway.example/openai/v1',
);
bash
composer 
bash
cp .env.example .env
php examples/responses/createResponse.php
bash
composer test
composer analyse
vendor/bin/php-cs-fixer fix --dry-run --diff
composer audit