PHP code example of aisdk / xai

1. Go to this page and download the library: Download aisdk/xai 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/ */

    

aisdk / xai example snippets


use AiSdk\Generate;
use AiSdk\XAI;

$result = Generate::text()
    ->model(XAI::model('grok-4.3'))
    ->instructions('Write short, clear answers.')
    ->prompt('Explain closures in PHP.')
    ->run();

echo $result->text;

XAI::create([
    'apiKey' => 'xai-...',
    'baseUrl' => 'https://api.x.ai/v1',
]);

use AiSdk\Generate;
use AiSdk\XAI;

$result = Generate::image()
    ->model(XAI::model('grok-imagine-image-quality'))
    ->prompt('A clean app icon for a PHP AI SDK')
    ->aspectRatio('1:1')
    ->run();

$result->output->save(__DIR__.'/icon.png');

use AiSdk\Generate;
use AiSdk\XAI;

$result = Generate::speech()
    ->model(XAI::model('grok-voice'))
    ->input('Hello from xAI voice.')
    ->voice('eve')
    ->format('mp3')
    ->providerOptions('xai', [
        'language' => 'auto',
        'speed' => 1.1,
    ])
    ->run();

$result->output->save(__DIR__.'/speech.mp3');

use AiSdk\Content;
use AiSdk\Generate;
use AiSdk\XAI;

$result = Generate::transcription(Content::audio(__DIR__.'/meeting.mp3'))
    ->model(XAI::model('grok-transcribe'))
    ->providerOptions('xai', [
        'language' => 'en',
        'diarize' => true,
        'keyterm' => ['PHP', 'AI SDK'],
    ])
    ->run();

echo $result->output->text;

use AiSdk\Live;
use AiSdk\Live\AudioDelta;
use AiSdk\Live\ResponseCompleted;
use AiSdk\Transport;
use AiSdk\XAI;
use function Amp\async;

$session = Live::voice()
    ->model(XAI::model('grok-voice-latest'))
    ->instructions('Be concise and helpful.')
    ->voice('eve')
    ->language('en')
    ->turnDetection('disabled')
    ->inputAudioFormat('pcm16')
    ->outputAudioFormat('pcm16')
    ->connect(Transport::auto());

$sender = async(function () use ($session): void {
    while (! feof(STDIN)) {
        $bytes = fread(STDIN, 4096);
        if ($bytes !== false && $bytes !== '') {
            $session->sendAudio($bytes);
        }
    }

    $session->commitAudio();
    $session->requestResponse();
});

foreach ($session->events() as $event) {
    if ($event instanceof AudioDelta) {
        fwrite(STDOUT, $event->bytes);
    }

    if ($event instanceof ResponseCompleted) {
        break;
    }
}

$sender->await();
$session->close();

$session = Live::voice()
    ->model(XAI::model('grok-voice-latest'))
    ->providerOptions('xai', [
        'resumption' => ['enabled' => true],
        'query' => ['conversation_id' => $conversationId],
    ])
    ->connect(Transport::auto());

use App\Ai\AppWebSocketTransport;

$session = Live::voice()
    ->model(XAI::model('grok-voice-latest'))
    ->voice('eve')
    ->connect(new AppWebSocketTransport());

use AiSdk\Live\ToolCallEvent;
use AiSdk\Schema;
use AiSdk\Tool;

$weather = Tool::make('weather', 'Get current weather')
    ->input(Schema::string(name: 'city')->her)
    ->connect(Transport::auto());

foreach ($session->events() as $event) {
    if ($event instanceof ToolCallEvent && $event->name === 'approval') {
        $session->sendToolResult($event->callId, ['approved' => true]);
    }
}

use AiSdk\Live\LiveClosed;
use AiSdk\Live\TranscriptCompleted;
use AiSdk\Live\TranscriptUpdate;

$session = Live::transcribe()
    ->model(XAI::model('grok-transcribe'))
    ->language('en')
    ->audioFormat('pcm16')
    ->providerOptions('xai', [
        'sample_rate' => 16000,
        'keyterm' => ['PHP', 'AI SDK'],
        'smart_turn' => 0.7,
    ])
    ->connect(Transport::auto());

$session->sendAudio($pcmBytes);
$session->commitAudio(); // Requests a finalized segment.
$session->close();       // Sends audio.done; keep receiving the final result.

foreach ($session->events() as $event) {
    if ($event instanceof TranscriptUpdate) {
        echo "\r{$event->text}";
    }
    if ($event instanceof TranscriptCompleted) {
        echo "\nFinal: {$event->text}\n";
    }
    if ($event instanceof LiveClosed) {
        break;
    }
}

$secret = Live::voice()
    ->model(XAI::model('grok-voice-latest'))
    ->providerOptions('xai', [
        'expires_after' => ['seconds' => 300],
    ])
    ->clientSecret();

return json_encode([
    'value' => $secret->value,
    'expires_at' => $secret->expiresAt,
]);

$rawBody = file_get_contents('php://input');
$event = XAI::verifyWebhook(
    $rawBody,
    getallheaders(),
    $_ENV['XAI_WEBHOOK_SECRET'],
);

if (($event['type'] ?? null) === 'realtime.call.incoming') {
    $call = Live::voice()
        ->model(XAI::model('grok-voice-latest'))
        ->instructions('You are the phone support agent.')
        ->voice('eve')
        ->call($event['data']['call_id']);

    $call->accept(); // Deliberate no-op for xAI.
    $control = $call->connect(Transport::auto());

    foreach ($control->events() as $controlEvent) {
        // Handle normalized events and tools on the server.
    }

    $call->hangup();
}

$result = Generate::video('A rocket launching from Mars')
    ->model(XAI::model('grok-imagine-video'))
    ->aspectRatio('16:9')
    ->resolution('720p')
    ->duration(8)
    ->run(timeout: 600);

use AiSdk\Reasoning;

$result = Generate::text('Explain the tradeoff.')
    ->model(XAI::model('grok-4.3'))
    ->reasoning(Reasoning::effort('low'))
    ->run();

$result = Generate::text('Hello')
    ->model(XAI::model('grok-4.3'))
    ->providerOptions('xai', [
        'raw' => ['search_parameters' => ['mode' => 'auto']],
    ])
    ->run();