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-6-luna',
'input' => 'Give me a one-sentence summary of PSR-18.',
]);
$result = json_decode((string) $response->getBody(), true, 512, JSON_THROW_ON_ERROR);
foreach ($result['output'] as $item) {
foreach ($item['content'] ?? [] as $content) {
if (($content['type'] ?? null) === 'output_text') {
echo $content['text'];
}
}
}
$openAI->createAgentSession(
[
'agent' => [
'model' => 'gpt-6-astra',
'instructions' => 'Write clean code, run it, and report the actual output.',
],
'environment' => ['type' => 'openai_hosted'],
'input' => 'Create tree.php and use it to print a readable directory tree.',
'stream' => true,
],
static function (array $event): void {
echo json_encode($event, JSON_THROW_ON_ERROR) . PHP_EOL;
},
);
$openAI->createEmbedding([
'model' => 'text-embedding-3-small',
'input' => 'A sentence to embed.',
]);
use SoftCreatR\OpenAI\Response\ModelResponse;
$dto = ModelResponse::fromResponse($response);
if ($dto->isCompleted()) {
echo $dto->getOutputText();
}
$refusals = $dto->getRefusals();
use SoftCreatR\JsonPayloadContract\Contract;
use SoftCreatR\JsonPayloadContract\Field;
use SoftCreatR\OpenAI\Response\JsonResponse;
$contract = Contract::define([
'responseId' => Field::son($contract->applyJson(...));
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.
}