PHP code example of amirkateb / ai-core-client

1. Go to this page and download the library: Download amirkateb/ai-core-client 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/ */

    

amirkateb / ai-core-client example snippets




use AmirKateb\AiCoreClient\Client;

$ai = new Client(
    'https://ai.katebsaber.ir',
    getenv('AI_CORE_API_KEY'),
);

$request = $ai->chat([
    'model' => 'ollama:qwen2.5-coder:3b',
    'message' => 'سلام، پاسخ کوتاه بده.',
], Client::idempotencyKey());

$result = $request->wait();

echo $result['result']['content'] ?? '';

$profiles = $ai->autoSwitchProfiles('chat');

foreach ($profiles['data'] as $profile) {
    echo $profile['name'].' — '.$profile['model_count']." models\n";

    foreach ($profile['models'] as $candidate) {
        printf(
            "#%d %s / %s | available=%s | direct_access=%s\n",
            $candidate['position'],
            $candidate['provider'],
            $candidate['model'],
            $candidate['available'] ? 'yes' : 'no',
            $candidate['direct_access'] ? 'yes' : 'no',
        );
    }
}

$profileId = 'f667da3d-b798-453a-9d68-1b03ed13a789';

$request = $ai->chatWithProfile($profileId, [
    'message' => 'این درخواست را با زنجیره اضطراری اجرا کن.',
], Client::idempotencyKey('failover'));

$result = $request->wait();

// The requested model remains the profile identity:
echo $result['model']; // auto_switch:<profile_uuid>

// The actual winning provider/model is explicit:
echo $result['resolved_model'];

// Full failover diagnostics:
print_r($result['auto_switch']['attempts'] ?? []);

$request = $ai->textWithProfile($profileId, [
    'text' => 'یک عنوان کوتاه بساز.',
]);

use AmirKateb\AiCoreClient\Value\SseEvent;

$request = $ai->chatStreamWithProfile($profileId, [
    'message' => 'مرحله‌ای توضیح بده.',
]);

$request->stream(function (SseEvent $event): void {
    if ($event->event === 'attempt_start') {
        echo "Trying {$event->data['provider']} / {$event->data['model']}\n";
    }

    if ($event->event === 'attempt_failed') {
        echo "Candidate failed, switching…\n";
    }

    if ($event->event === 'delta') {
        echo $event->data['text'] ?? '';
    }
});

$all = $ai->models();
$chat = $ai->models('chat');
$profile = $ai->autoSwitchProfile($profileId, 'chat');
$capabilities = $ai->capabilities();
$health = $ai->health();

use AmirKateb\AiCoreClient\Client;

final class SummarizeArticle
{
    public function __construct(private Client $ai) {}

    public function __invoke(string $text): array
    {
        return $this->ai->chat([
            'message' => 'خلاصه کن: '.$text,
        ])->wait();
    }
}

use AiCore;

$result = AiCore::chat([
    'message' => 'سلام',
])->wait();

$handle = $ai->chat(['message' => 'Hello']);

$handle->get();            // Current state
$handle->wait();           // Poll until terminal
$handle->stream($listener); // Resumable SSE
$handle->cancel();         // Cancel queued/retry/processing
$retry = $handle->retry(); // New request from a failed/cancelled request

$vision = $ai->visionAnalyze(
    __DIR__.'/invoice.jpg',
    ['model' => 'provider:vision-model', 'prompt' => 'فاکتور را تحلیل کن'],
);

$result = $vision->wait();

$image = $ai->imageGeneration([
    'model' => 'provider:image-model',
    'prompt' => 'A minimal AI gateway icon',
]);

$image->wait();
$image->downloadMedia(__DIR__.'/output.webp');

$batch = $ai->batchBuilder()
    ->metadata(['job' => 'nightly-enrichment'])
    ->chat('provider:model', ['message' => 'خلاصه کن: ...'], 'item_1')
    ->chat('auto_switch:'.$profileId, ['message' => 'با failover خلاصه کن: ...'], 'item_2')
    ->embeddings('provider:embedding-model', ['input' => ['متن اول', 'متن دوم']], 'item_3')
    ->send(Client::idempotencyKey('batch'));

$result = $batch->wait();

use AmirKateb\AiCoreClient\WebhookVerifier;

$payload = WebhookVerifier::fromHeaders(
    getenv('AI_CORE_WEBHOOK_SECRET'),
    getallheaders(),
    file_get_contents('php://input'),
);

use AmirKateb\AiCoreClient\Exception\ApiException;
use AmirKateb\AiCoreClient\Exception\TransportException;

try {
    $result = $ai->chat(['message' => 'سلام'])->wait();
} catch (ApiException $e) {
    error_log('HTTP '.$e->statusCode.' / '.($e->errorCode ?? 'unknown'));
    error_log($e->getMessage());
} catch (TransportException $e) {
    error_log('Network error: '.$e->getMessage());
}