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";
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();
$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'])],
]);
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']));
}
}
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,
]);
$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;