PHP code example of tibor-src / xai-sdk-php

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

    

tibor-src / xai-sdk-php example snippets


use TiborSrc\XaiSdkPhp\SpaceXAI;

$client = new SpaceXAI();

$response = $client->responses->create([
    'model' => 'grok-4.7',
    'input' => 'Explain why the sky is blue in one sentence.',
]);

echo $response->toText();

$stream = $client->responses->create([
    'model' => 'grok-4.7',
    'input' => 'Write a short story about a curious robot.',
    'stream' => true,
]);

$response = $stream
    ->on('text', function (string $text): void {
        echo $text;
    })
    ->done();

echo "\n{$response->usage->total_tokens} tokens\n";

$response = $stream
    ->on('reasoning', function (string $text): void {
        fwrite(STDERR, $text);
    })
    ->on('text', function (string $text): void {
        echo $text;
    })
    ->on('tool_call', function (array $call): void {
        fwrite(STDERR, "\n{$call['type']} {$call['status']}");
    })
    ->done();

foreach ($stream as $event) {
    if (($event['type'] ?? null) === 'response.function_call_arguments.delta') {
        echo $event['delta'];
    }
}

$response = $stream->done();
echo $response->toText();

use TiborSrc\XaiSdkPhp\SpaceXAI;

$client = new SpaceXAI();
$promptCacheKey = 'conversation:' . sprintf(
    '%04x%04x-%04x-%04x-%04x-%04x%04x%04x',
    random_int(0, 0xffff),
    random_int(0, 0xffff),
    random_int(0, 0xffff),
    random_int(0, 0x0fff) | 0x4000,
    random_int(0, 0x3fff) | 0x8000,
    random_int(0, 0xffff),
    random_int(0, 0xffff),
    random_int(0, 0xffff),
);
$input = [
    ['role' => 'user', 'content' => 'My name is Ada. Remember it.'],
];

$first = $client->responses->create([
    'model' => 'grok-4.7',
    'input' => $input,
    'prompt_cache_key' => $promptCacheKey,
]);

$second = $client->responses->create([
    'model' => 'grok-4.7',
    'input' => [
        ...$input,
        ...$first->toInput(),
        ['role' => 'user', 'content' => 'What is my name?'],
    ],
    'prompt_cache_key' => $promptCacheKey,
]);

echo $second->toText();

$first = $client->responses->create([
    'model' => 'grok-4.7',
    'input' => 'My name is Ada. Remember it.',
    'store' => true,
]);

$second = $client->responses->create([
    'model' => 'grok-4.7',
    'input' => 'What is my name?',
    'previous_response_id' => $first->id,
    'store' => true,
]);

$compacted = $client->responses->compact([
    'model' => 'grok-4.7',
    'input' => [
        ...$input,
        ...$first->toInput(),
        ['role' => 'user', 'content' => 'What is my name?'],
        ...$second->toInput(),
    ],
]);

$third = $client->responses->create([
    'model' => 'grok-4.7',
    'input' => [
        ...$compacted->output,
        ['role' => 'user', 'content' => 'Spell my name backwards.'],
    ],
    'prompt_cache_key' => $promptCacheKey,
]);

echo $third->toText();

$response = $client->responses->create([
    'model' => 'grok-4.7',
    'input' => [
        [
            'role' => 'user',
            'content' => [
                ['type' => 'input_text', 'text' => 'Describe this image.'],
                [
                    'type' => 'input_image',
                    'image_url' => 'https://example.com/image.jpg',
                    'detail' => 'high',
                ],
            ],
        ],
    ],
]);

echo $response->toText();

use TiborSrc\XaiSdkPhp\Http\Blob;

$image = new Blob(file_get_contents('./image.png'), 'image/png');

$response = $client->responses->create([
    'model' => 'grok-4.7',
    'input' => [
        [
            'role' => 'user',
            'content' => [
                ['type' => 'input_text', 'text' => 'What is in this image?'],
                ['type' => 'input_image', 'image' => $image],
            ],
        ],
    ],
]);

$response = $client->responses->create([
    'model' => 'grok-4.7',
    'input' => 'Give me a city to visit in Japan.',
    'text' => [
        'format' => [
            'type' => 'json_schema',
            'name' => 'travel_suggestion',
            'schema' => [
                'type' => 'object',
                'properties' => [
                    'city' => ['type' => 'string'],
                    'reason' => ['type' => 'string'],
                ],
                '

['title' => 'Why the']
['title' => 'Why the sky is blue', 'lines' => [['speaker' => 'host', 'text' => 'Wel']]]
['title' => 'Why the sky is blue', 'lines' => [['speaker' => 'host', 'text' => 'Welcome back! Today a simple question.'], ['speaker' => 'gu']]]
['title' => 'Why the sky is blue', 'lines' => [['speaker' => 'host', 'text' => 'Welcome back! Today a simple question.'], ['speaker' => 'guest', 'text' => 'Why is the sky blue?']]]

$stream = $client->responses->create([
    'model' => 'grok-4.7',
    'input' => 'Write a short two-person podcast script about why the sky is blue.',
    'reasoning' => ['effort' => 'low'],
    'text' => [
        'format' => [
            'type' => 'json_schema',
            'name' => 'podcast_script',
            'schema' => [
                'type' => 'object',
                'properties' => [
                    'title' => ['type' => 'string'],
                    'lines' => [
                        'type' => 'array',
                        'items' => [
                            'type' => 'object',
                            'properties' => [
                                'speaker' => ['type' => 'string', 'enum' => ['host', 'guest']],
                                'text' => ['type' => 'string'],
                            ],
                            '

use function TiborSrc\XaiSdkPhp\parsePartialJson;

parsePartialJson('{"title":"Why the'); // ['title' => 'Why the']
parsePartialJson('{"title":"Why the sky is blue","minutes":1'); // ['title' => 'Why the sky is blue']
parsePartialJson('{"title":"Why the sky is blue","minutes":12}'); // ['title' => 'Why the sky is blue', 'minutes' => 12]
parsePartialJson('{"title" "oops"}'); // null

use function TiborSrc\XaiSdkPhp\parsePartialJson;

$text = '';
foreach ($stream as $event) {
    if (($event['type'] ?? null) === 'response.output_text.delta') {
        $text .= $event['delta'];
        var_export(parsePartialJson($text));
    }
}

use TiborSrc\XaiSdkPhp\SpaceXAI;

use function TiborSrc\XaiSdkPhp\isFunctionCall;

$client = new SpaceXAI();
$prompt = 'What is the weather in San Francisco?';
$input = [['role' => 'user', 'content' => $prompt]];
$getWeatherTool = [
    'type' => 'function',
    'name' => 'get_weather',
    'description' => 'Get the current weather for a location.',
    'parameters' => [
        'type' => 'object',
        'properties' => [
            'location' => ['type' => 'string'],
        ],
        'etWeatherTool],
]);

$call = null;
foreach ($response->output as $item) {
    if (isFunctionCall($item)) {
        $call = $item;
        break;
    }
}
if ($call === null) {
    throw new RuntimeException('The model did not call get_weather');
}
$result = $getWeather(json_decode($call['arguments'], true));

$answer = $client->responses->create([
    'model' => 'grok-4.7',
    'input' => [
        ...$input,
        ...$response->toInput(),
        [
            'type' => 'function_call_output',
            'call_id' => $call['call_id'],
            'output' => json_encode($result),
        ],
    ],
]);

echo $answer->toText();

use TiborSrc\XaiSdkPhp\SpaceXAI;

$client = new SpaceXAI();
$tools = [$getWeatherTool];
$handlers = [
    'get_weather' => $getWeather,
];

$runTool = function (array $call) use ($handlers): array {
    try {
        $handler = $handlers[$call['name']] ?? null;
        if ($handler === null) {
            throw new RuntimeException('Unknown tool: ' . $call['name']);
        }
        $output = $handler(json_decode($call['arguments'], true));
    } catch (Throwable $exception) {
        $output = ['error' => $exception->getMessage()];
    }

    return [
        'type' => 'function_call_output',
        'call_id' => $call['call_id'],
        'output' => json_encode($output),
    ];
};

$input = [
    ['role' => 'user', 'content' => 'Compare the weather in Paris and Tokyo.'],
];

for ($turn = 0; $turn < 10; $turn++) {
    $toolOutputs = [];
    $stream = $client->responses->create([
        'model' => 'grok-4.7',
        'input' => $input,
        'tools' => $tools,
        'stream' => true,
    ]);
    $response = $stream
        ->on('text', function (string $text): void {
            echo $text;
        })
        ->on('client_tool_call', function (array $call) use (&$toolOutputs, $runTool): void {
            if (($call['type'] ?? null) === 'function_call') {
                $toolOutputs[] = $runTool($call);
            }
        })
        ->done();
    if ($toolOutputs === []) {
        break;
    }

    array_push($input, ...$response->toInput(), ...$toolOutputs);
}

use TiborSrc\XaiSdkPhp\SpaceXAI;

$client = new SpaceXAI();

$stream = $client->responses->create([
    'model' => 'grok-4.7',
    'input' => 'How much free disk space does this machine have?',
    'tools' => [['type' => 'shell', 'environment' => ['type' => 'local']]],
    'stream' => true,
]);

$stream
    ->on('client_tool_call', function (array $call): void {
        if (($call['type'] ?? null) !== 'shell_call') {
            return;
        }
        foreach ($call['action']['commands'] as $command) {
            echo shell_exec($command);
        }
    })
    ->done();

$shell = [
    'type' => 'shell',
    'environment' => [
        'type' => 'local',
        'skills' => [
            [
                'name' => 'release-notes',
                'description' => "Write release notes from this repo's git log in our house style.",
                'path' => './skills/release-notes',
            ],
        ],
    ],
];

use TiborSrc\XaiSdkPhp\SpaceXAI;

use function TiborSrc\XaiSdkPhp\webSearch;

$client = new SpaceXAI();

$response = $client->responses->create([
    'model' => 'grok-4.7',
    'input' => 'What are the latest developments in commercial spaceflight?',
    'tools' => [webSearch()],
]);

echo $response->toText();
echo $response->usage->num_server_side_tools_used;

use function TiborSrc\XaiSdkPhp\xSearch;

$response = $client->responses->create([
    'model' => 'grok-4.7',
    'input' => 'What has SpaceXAI announced on X this month?',
    'tools' => [xSearch(['allowed_x_handles' => ['xai'], 'from_date' => '2026-09-01'])],
]);

$stream
    ->on('server_tool_call', function (array $call): void {
        if (($call['type'] ?? null) === 'custom_tool_call') {
            echo $call['name'], ' ', $call['input'], "\n";
        }
    })
    ->done();

use function TiborSrc\XaiSdkPhp\codeExecution;

$response = $client->responses->create([
    'model' => 'grok-4.7',
    'input' => 'What is the standard deviation of 12, 15, 19, 22, and 31?',
    'tools' => [codeExecution()],
]);

use function TiborSrc\XaiSdkPhp\collectionsSearch;

$response = $client->responses->create([
    'model' => 'grok-4.7',
    'input' => 'What does our refund policy say about digital purchases?',
    'tools' => [collectionsSearch(['vector_store_ids' => ['your-collection-id'], 'max_num_results' => 10])],
]);

use function TiborSrc\XaiSdkPhp\mcp;

$response = $client->responses->create([
    'model' => 'grok-4.7',
    'input' => 'What is the modelcontextprotocol/typescript-sdk repository for?',
    'tools' => [mcp(['server_url' => 'https://mcp.deepwiki.com/mcp', 'server_label' => 'deepwiki'])],
]);

use TiborSrc\XaiSdkPhp\SpaceXAI;

use function TiborSrc\XaiSdkPhp\imageGeneration;
use function TiborSrc\XaiSdkPhp\isImageGenerationCall;

$client = new SpaceXAI();

$response = $client->responses->create([
    'model' => 'grok-4.7',
    'input' => 'Generate an image of a corgi surfing a big wave, in the style of a Japanese woodblock print.',
    'tools' => [imageGeneration()],
]);

echo $response->toText();

foreach ($response->output as $item) {
    if (isImageGenerationCall($item) && is_string($item['result'] ?? null)) {
        file_put_contents('corgi.jpg', base64_decode($item['result']));
    }
}

use function TiborSrc\XaiSdkPhp\isFunctionCall;
use function TiborSrc\XaiSdkPhp\isMessage;
use function TiborSrc\XaiSdkPhp\isReasoning;

foreach ($response->output as $item) {
    if (isMessage($item)) {
        var_export($item['content']);
    } elseif (isFunctionCall($item)) {
        echo $item['name'], ' ', $item['arguments'], "\n";
    } elseif (isReasoning($item)) {
        echo 'reasoning item ', $item['id'], "\n";
    }
}

$result = $client->images->generate([
    'model' => 'grok-imagine-image-2.0',
    'prompt' => 'A collage of London landmarks in a stenciled street-art style',
]);

echo $result->data[0]['url'] ?? '';
echo $result->usage?->cost_usd;

$result = $client->images->generate([
    'model' => 'grok-imagine-image-2.0',
    'prompt' => 'A futuristic city skyline at night',
    'n' => 4,
    'aspect_ratio' => '16:9',
    'resolution' => '2k',
    'response_format' => 'b64_json',
]);

foreach ($result->data as $index => $image) {
    if (is_string($image['b64_json'] ?? null)) {
        file_put_contents("skyline-{$index}.jpg", base64_decode($image['b64_json']));
    }
}

$result = $client->images->generate(
    [
        'model' => 'grok-imagine-image-2.0',
        'prompt' => 'A futuristic city skyline at night',
        'n' => 10,
        'resolution' => '2k',
        'response_format' => 'b64_json',
    ],
    ['maxResponseBodyBytes' => 128 * 1024 * 1024],
);

$result = $client->images->generate([
    'model' => 'grok-imagine-image-2.0',
    'prompt' => 'A lighthouse at dawn',
    'n' => 2,
    'output' => [
        'upload_urls' => [
            'https://storage.example.com/lighthouse-1.jpg?signature=...',
            'https://storage.example.com/lighthouse-2.jpg?signature=...',
        ],
    ],
]);

foreach ($result->data as $image) {
    echo $image['url'] ?? '', "\n";
}

use TiborSrc\XaiSdkPhp\Http\Blob;

$photo = new Blob(file_get_contents('./photo.png'), 'image/png');

$result = $client->images->edit([
    'model' => 'grok-imagine-image-2.0',
    'prompt' => 'Render this as a pencil sketch with detailed shading',
    'image' => $photo,
]);

echo $result->data[0]['url'] ?? '';

$result = $client->images->edit([
    'model' => 'grok-imagine-image-2.0',
    'prompt' => 'Place the cat from <IMAGE_0> on the sofa from <IMAGE_1>',
    'images' => [
        ['url' => 'https://example.com/cat.png'],
        ['file_id' => 'file_abc123'],
    ],
    'aspect_ratio' => '16:9',
]);

$started = $client->videos->generate([
    'model' => 'grok-imagine-video-1.5',
    'prompt' => 'A paper boat drifting down a rain-soaked street',
    'duration' => 8,
    'aspect_ratio' => '16:9',
    'resolution' => '720p',
]);

$result = $client->videos->wait($started->request_id);
if ($result->status === 'done') {
    echo $result->video['url'] ?? '';
    echo $result->usage?->cost_usd;
} else {
    fwrite(STDERR, $result->status . ' ' . ($result->error['code'] ?? '') . ' ' . ($result->error['message'] ?? ''));
}

use TiborSrc\XaiSdkPhp\Http\Blob;

$started = $client->videos->generate([
    'model' => 'grok-imagine-video-1.5',
    'prompt' => 'Make the water crash down and slowly pan out the camera',
    'image' => new Blob(file_get_contents('./waterfall.png'), 'image/png'),
]);

use TiborSrc\XaiSdkPhp\Http\Blob;

$edit = $client->videos->edit([
    'model' => 'grok-imagine-video',
    'prompt' => 'Give the woman a silver necklace',
    'video' => new Blob(file_get_contents('portrait.mp4'), 'video/mp4'),
]);

$extension = $client->videos->extend([
    'model' => 'grok-imagine-video',
    'prompt' => 'The camera slowly zooms out to reveal the city skyline',
    'video' => ['file_id' => 'file_abc123'],
    'duration' => 6,
]);

use TiborSrc\XaiSdkPhp\Http\File;

$file = $client->files->upload([
    'file' => new File(file_get_contents('./report.pdf'), 'report.pdf', 'application/pdf'),
    'filename' => 'report.pdf',
]);

$response = $client->responses->create([
    'model' => 'grok-4.7',
    'input' => [
        [
            'role' => 'user',
            'content' => [
                ['type' => 'input_text', 'text' => 'Summarize the key findings in this report.'],
                ['type' => 'input_file', 'file_id' => $file->id],
            ],
        ],
    ],
]);

echo $response->toText();

foreach ($client->files->list() as $stored) {
    echo $stored['id'], ' ', $stored['filename'], ' ', $stored['bytes'], "\n";
}

$content = $client->files->content($file->id);
file_put_contents('report-copy.pdf', $content->bytes());

$shared = $client->files->createPublicUrl($file->id, [
    'expires_after' => 86_400,
]);
echo $shared->public_url;

$client->files->revokePublicUrl($file->id);
$client->files->delete($file->id);

$batch = $client->batches->create(['name' => 'feedback_sentiment']);

$feedback = [
    ['id' => 'feedback_001', 'text' => 'The product exceeded my expectations!'],
    ['id' => 'feedback_002', 'text' => 'Shipping took way too long.'],
];

$client->batches->requests->add($batch->batch_id, [
    'batch_requests' => array_map(fn (array $item): array => [
        'batch_request_id' => $item['id'],
        'batch_request' => [
            'responses' => [
                'model' => 'grok-4.7',
                'input' => [
                    ['role' => 'system', 'content' => 'Classify the sentiment as positive, negative, or neutral.'],
                    ['role' => 'user', 'content' => $item['text']],
                ],
            ],
        ],
    ], $feedback),
]);

$client->batches->wait($batch->batch_id);

foreach ($client->batches->results($batch->batch_id) as $row) {
    $batchResult = $row['batch_result'];
    if (isset($batchResult['error'])) {
        fwrite(STDERR, $row['batch_request_id'] . ' ' . json_encode($batchResult['error']) . "\n");
    } else {
        echo $row['batch_request_id'], ' ', json_encode($batchResult['response']), "\n";
    }
}

$speech = $client->voice->speak([
    'text' => 'Welcome to SpaceX. [pause] How can I help you today?',
    'language' => 'en',
    'voice_id' => 'eve',
]);

file_put_contents('welcome.mp3', $speech->bytes());

use TiborSrc\XaiSdkPhp\INLINE_SPEECH_TAGS;

use function TiborSrc\XaiSdkPhp\checkSpeechText;
use function TiborSrc\XaiSdkPhp\stripInvalidSpeechTags;

$tags = implode(', ', array_map(fn (string $tag): string => "[{$tag}]", INLINE_SPEECH_TAGS));
$response = $client->responses->create([
    'model' => 'grok-4.7',
    'input' => "Write the opening line of a podcast about volcanoes. You can use these speech tags: {$tags}.",
]);
$line = $response->toText();

$problems = checkSpeechText($line); // For example: ['Unknown speech tag [laff], did you mean [laugh]?']
if ($problems !== []) {
    fwrite(STDERR, implode("\n", $problems));
}

$client->voice->speak(['text' => stripInvalidSpeechTags($line), 'language' => 'en']);

use TiborSrc\XaiSdkPhp\Http\Blob;

$transcript = $client->voice->transcribe([
    'file' => new Blob(file_get_contents('./meeting.mp3'), 'audio/mpeg'),
    'language' => 'en',
    'format' => true,
]);

echo $transcript->text;

use TiborSrc\XaiSdkPhp\Http\Blob;

$voice = $client->voice->custom->create([
    'file' => new Blob(file_get_contents('./reference.wav'), 'audio/wav'),
    'name' => 'Friendly Narrator',
    'language' => 'en',
]);

echo $voice->voice_id;

$secret = $client->voice->clientSecrets->create([
    'expires_after' => ['seconds' => 300],
]);

$encoded = $client->tokenizer->encode([
    'model' => 'grok-4.7',
    'text' => 'Hello world!',
]);

echo count($encoded->token_ids), "\n";
foreach ($encoded->token_ids as $token) {
    echo $token['token_id'], ' ', $token['string_token'], "\n";
}

$bytes = '';
foreach ($encoded->token_ids as $token) {
    foreach ($token['token_bytes'] as $byte) {
        $bytes .= chr($byte);
    }
}
$text = $bytes;

use TiborSrc\XaiSdkPhp\KNOWN_MODEL_IDS;

$model = 'grok-4.7';

$available = $client->models->list();
foreach ($available->data as $availableModel) {
    echo $availableModel['id'], "\n";
}

$modelInfo = $client->models->get($model);

$imageModels = $client->models->image->list();
foreach ($imageModels->models as $availableImageModel) {
    echo $availableImageModel['id'], ' ', json_encode($availableImageModel['aliases']), "\n";
}

$imageModelInfo = $client->models->image->get('grok-imagine-image-2.0');

$languageModels = $client->models->language->list();
foreach ($languageModels->models as $languageModel) {
    echo $languageModel['id'], ' ', json_encode($languageModel['input_modalities']), "\n";
}

$languageModelInfo = $client->models->language->get('grok-4.7');
var_export($languageModelInfo->capabilities['reasoning_effort'] ?? null);

$apiKeyInfo = $client->account->apiKey();
echo $apiKeyInfo->name, ' ', json_encode($apiKeyInfo->acls), ' ', json_encode($apiKeyInfo->api_key_disabled);

$stored = $client->responses->create([
    'model' => 'grok-4.7',
    'input' => 'Save this response.',
    'store' => true,
]);

$fetched = $client->responses->get($stored->id);
$inputItems = $client->responses->inputItems->list($stored->id);
$client->responses->delete($stored->id);

$response = $client->responses->create([
    'model' => 'grok-4.7',
    'input' => 'Hello',
    'guidelines' => [
        ['type' => 'policy', 'category' => 'violence', 'behavior' => 'decline'],
        ['type' => 'policy', 'category' => 'self_harm', 'behavior' => 'offer_support'],
    ],
]);

$response = $client->responses->create([
    'model' => 'grok-4.7',
    'input' => 'Explain the Riemann hypothesis in one paragraph.',
    'service_tier' => 'fast',
]);

echo $response->service_tier;

foreach ($client->files->list() as $file) {
    echo $file['id'], "\n";
}

$client = new SpaceXAI([
    'timeout' => 60_000,
    'idleTimeout' => 30_000,
    'maxRetries' => 2,
]);

use TiborSrc\XaiSdkPhp\Http\AbortController;

$controller = new AbortController();

$response = $client->responses->create(
    [
        'model' => 'grok-4.7',
        'input' => 'Write a detailed report.',
    ],
    [
        'signal' => $controller->signal,
        'timeout' => 120_000,
        'maxRetries' => 0,
    ],
);

use TiborSrc\XaiSdkPhp\APIError;
use TiborSrc\XaiSdkPhp\AuthenticationError;
use TiborSrc\XaiSdkPhp\RateLimitError;

try {
    $client->responses->create([
        'model' => 'grok-4.7',
        'input' => 'Hello',
    ]);
} catch (AuthenticationError) {
    fwrite(STDERR, "Check XAI_API_KEY\n");
} catch (RateLimitError) {
    fwrite(STDERR, "Rate limited. Retry later.\n");
} catch (APIError $error) {
    fwrite(STDERR, "{$error->status} {$error->code} {$error->param} {$error->requestId} {$error->getMessage()}\n");
}
bash
XAI_DEBUG=1 php app.php