PHP code example of imrandevbd / laravel-ai-hub

1. Go to this page and download the library: Download imrandevbd/laravel-ai-hub 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/ */

    

imrandevbd / laravel-ai-hub example snippets

                                                                                                           │
│     User::query()                                                                                                    │
│         ->where('active', 1)                                                                                         │
│         ->with(['orders' => fn ($q) => $q->select('id', 'user_id', 'total_usd'), 'orders.items'])                    │
│         ->lazyById(250)                                                                                              │
│         ->each(function (User $user) {                                                                               │
│             // Process batch with constant memory consumption                                                        │
│         });                                                                                                          │
│     

use ImranDevBd\AiHub\Facades\AIHub;

// 1. Basic Prompt (uses default provider & model)
$response = AIHub::prompt('Explain quantum computing in simple terms')->send();

echo $response->content;       // Generated text
echo $response->costUsd;       // Calculated token cost (e.g. 0.000412)
echo $response->latencyMs;     // Request duration (e.g. 312.4ms)
echo $response->totalTokens;   // Prompt + completion tokens

// 2. Specific Provider & Model Shortcuts
$response = AIHub::gemini('gemini-3.8-flash')
    ->prompt('Write a concise summary')
    ->send();

$response = AIHub::openai('gpt-5.6-luna')
    ->prompt('Write a high-performance database query')
    ->send();

$response = AIHub::claude('claude-3-7-sonnet-latest')
    ->prompt('Refactor this architecture')
    ->send();

$response = AIHub::deepseek('deepseek-reasoner')
    ->prompt('Solve this complex mathematical problem')
    ->send();

use ImranDevBd\AiHub\Facades\AIHub;

// Daily Driver: Ultra-fast, ultra-cheap GPT-6 Luna ($0.10 / $0.50 per 1M tokens)
$tag = AIHub::openai('gpt-6-luna')
    ->prompt('Classify this incoming email category in one word: "Can I get a tax invoice?"')
    ->send();

// Frontier Reasoning: Gemini 4 Argon with 1M context & hybrid thinking
$audit = AIHub::gemini('gemini-4-argon')
    ->thinking(8192)
    ->prompt('Analyze this entire multi-file codebase for race conditions, auth bypasses, and security flaws: ...')
    ->send();

use ImranDevBd\AiHub\Facades\AIHub;

// Global default remains OpenAI, but this specific task runs on Gemini
$response = AIHub::gemini('gemini-4-argon')
    ->prompt('Audit this contract for compliance risks')
    ->send();

// Automatically routes to Gemini Argon (even when OpenAI is global default!)
$response = AIHub::model('gemini-4-argon')
    ->prompt('Analyze complex multi-step data')
    ->send();

// Automatically routes to OpenAI GPT-6 Luna
$response = AIHub::model('gpt-6-luna')
    ->prompt('Quickly categorize user feedback')
    ->send();

// Automatically routes to Claude
$response = AIHub::model('claude-3-7-sonnet-latest')
    ->prompt('Refactor this architecture cleanly')
    ->send();

// Automatically routes to DeepSeek
$response = AIHub::model('deepseek-reasoner')
    ->prompt('Solve this algorithmic puzzle')
    ->send();

$response = AIHub::using('gemini', 'gemini-3.8-pro')
    ->image('https://example.com/receipt.jpg')
    ->prompt('Itemize all line items and tax amounts on this receipt')
    ->send();

$response = AIHub::priority(['gemini', 'openai'])
    ->prompt('Process high-volume user query')
    ->send();

// Or using the fallback() alias:
$response = AIHub::gemini('gemini-3.8-flash')
    ->fallback(['openai', 'claude'])
    ->prompt('Analyze customer sentiment')
    ->send();

$response = AIHub::gemini('gemini-3.8-flash')
    ->withoutFailover()
    ->image('https://example.com/schematic.png')
    ->prompt('Analyze this circuit diagram')
    ->send();

$response = AIHub::promptTemplate('receipt-ocr', ['receipt_text' => $rawText])->send();

$response = AIHub::gemini('gemini-3.8-flash')
    ->forJob('invoice-ocr')
    ->prompt('Extract invoice data')
    ->send();

// Chat with Gemini while keeping OpenAI as your application's global default
$chat = AIHub::chat('gemini', 'gemini-3.8-flash')
    ->system('You are an expert document assistant.');

$reply = $chat->reply('Can you summarize this invoice?');

// 1. Google Gemini 3.8 with 4,096 thinking tokens
$response = AIHub::gemini('gemini-3.8-flash')
    ->thinking(4096)
    ->prompt('Solve this algorithmic challenge step-by-step')
    ->send();

// 2. Turn off thinking for ultra-fast, lowest latency responses
$response = AIHub::gemini('gemini-3.8-flash')
    ->withoutThinking()
    ->prompt('Return a quick greeting')
    ->send();

// 3. Anthropic Claude 3.7 Sonnet extended thinking
$response = AIHub::claude('claude-3-7-sonnet-latest')
    ->thinking(2048)
    ->prompt('Analyze this distributed database failure scenario')
    ->send();

// 4. OpenAI o3-mini or GPT-5 with reasoning effort
$response = AIHub::openai('o3-mini')
    ->reasoningEffort('high')
    ->prompt('Verify this formal mathematical proof')
    ->send();

$data = AIHub::gemini()
    ->prompt('Return a user profile JSON object')
    ->recoverJson()
    ->send()
    ->json(); // Returns clean PHP array

$schema = [
    'type' => 'object',
    'properties' => [
        'sentiment' => ['type' => 'string', 'enum' => ['positive', 'negative', 'neutral']],
        'confidence' => ['type' => 'number'],
        'key_topics' => ['type' => 'array', 'items' => ['type' => 'string']],
    ],
    'ta = $response->json(); // ['sentiment' => 'positive', 'confidence' => 0.99, ...]

// 2. Shortcut helper
$response = AIHub::structured($schema)
    ->prompt('Customer feedback text...')
    ->generate();

// In a Laravel Controller
public function stream(Request $request)
{
    return AIHub::gemini('gemini-3.8-flash')
        ->prompt($request->input('prompt'))
        ->streamResponse();
}

// Or consume stream chunks using a closure
AIHub::openai()->prompt('Generate report')->streamRaw(function (string $chunk) {
    echo $chunk;
});

// Generator loop
foreach (AIHub::openai()->prompt('Write essay')->stream() as $chunk) {
    echo $chunk;
}

use ImranDevBd\AiHub\Facades\AIHub;

// Initialize a session (optionally specify provider and model)
$chat = AIHub::chat('claude', 'claude-3-7-sonnet-latest')
    ->system('You are an expert Laravel and Pest PHP architect.');

// Turn 1
$reply1 = $chat->send('How do I mock external APIs cleanly in Pest?');
echo $reply1->content;

// Turn 2 (Context of Turn 1 is automatically preserved)
$reply2 = $chat->send('Can you convert that snippet into an architectural action class?');
echo $reply2->content;

// Cumulative token & cost telemetry
echo $chat->totalTokens(); // Total tokens across all turns
echo $chat->totalCost();   // Total USD cost across all turns

// Stream a chat turn directly as SSE to browser
return $chat->streamResponse('Explain how it works step-by-step');

// Export or restore chat history (e.g. for database persistence)
$history = $chat->export(); // Array of messages, system prompt, tokens, etc.
$chat->load($history);

use ImranDevBd\AiHub\Facades\AIHub;

public function test_user_summary_generation(): void
{
    // 1. Mock a simple string response
    AIHub::fake('This is a simulated AI summary.');

    // Or mock with sequential responses or per-provider responses:
    // AIHub::fake([
    //     'gemini' => 'Gemini simulated response',
    //     'openai' => AIHub::response(['key' => 'value']),
    // ]);

    // Execute your application code
    $response = AIHub::gemini('gemini-3.8-flash')
        ->prompt('Summarize account history')
        ->send();

    $this->assertSame('This is a simulated AI summary.', $response->content);

    // Assert that a matching request was dispatched
    AIHub::assertSent(function ($request) {
        return $request->getProvider() === 'gemini'
            && str_contains($request->getPrompt(), 'Summarize account history');
    });

    AIHub::assertSentCount(1);
    AIHub::assertNotSent(fn ($req) => $req->getProvider() === 'openai');
}

// Vision
$response = AIHub::openai()
    ->prompt('Describe this image')
    ->image('https://example.com/photo.jpg')
    ->send();

// Function tools (OpenAI-style schema; mapped for Claude & Gemini)
$response = AIHub::openai()->tools([[
    'type' => 'function',
    'function' => [
        'name' => 'get_weather',
        'description' => 'Get the weather for a city',
        'parameters' => [
            'type' => 'object',
            'properties' => [
                'city' => ['type' => 'string'],
            ],
            'send();
AIHub::fireworks()->prompt('Hello from Fireworks')->send();
AIHub::perplexity('sonar-pro')->prompt('What shipped this week?')->send();

$vector = AIHub::openai()
    ->model('text-embedding-3-small')
    ->embed('Laravel AI Hub semantic search')
    ->first(); // Returns float array vector

AIHub::gemini()
    ->forJob('invoice-ocr')
    ->prompt($invoicePrompt)
    ->send();

'priority' => [
    'gemini',      // #1 Tried first
    'openai',      // #2 If Gemini is rate-limited or down
    'claude',      // #3
    'grok',        // #4
    'deepseek',    // #5
    'mistral',     // #6
    'groq',        // #7
    'ollama',      // #8
    'openrouter',  // #9
    'azure',       // #10
    'together',    // #11
    'fireworks',   // #12
    'perplexity',  // #13
],
'failover_enabled' => true,

// config/ai-hub.php
'logging' => [
    'enabled' => env('AI_HUB_LOGGING', true),
    'async' => env('AI_HUB_LOGGING_ASYNC', 'after_response'), // 'after_response', 'queue', or 'sync'
    'prune_days' => 90, // Automatic log pruning
],

use ImranDevBd\AiHub\Models\AiRequestLog;
use Illuminate\Support\Facades\Schedule;

Schedule::command('model:prune', ['--model' => [AiRequestLog::class]])->daily();

use ImranDevBd\AiHub\Facades\AIHub;

public function boot(): void
{
    AIHub::auth(function ($request) {
        return app()->environment('local') ||
               ($request->user() && in_array($request->user()->email, ['[email protected]'])) ||
               ($request->user() && $request->user()->hasRole('admin'));
    });
}

use App\Models\User;
use Illuminate\Support\Facades\Gate;

public function boot(): void
{
    Gate::define('viewAiHub', function (User $user) {
        return in_array($user->role, ['admin', 'developer']);
    });
}

use ImranDevBd\AiHub\Filament\AiHubPlugin;

$panel->plugin(AiHubPlugin::make()); // optional — auto-registered if omitted

// 30-day overview summary
$summary = AIHub::analytics()->summary(now()->subDays(30));
// ['total_cost_usd' => 12.45, 'requests' => 1420, 'failure_rate' => 0.4, 'json_recovery_rate' => 3.2]

// Breakdown of spend per provider
$costs = AIHub::analytics()->costByProvider();

// Latency percentiles
$latency = AIHub::analytics()->latencyPercentiles('gemini');
// ['p50' => 240, 'p95' => 580, 'p99' => 890]

// Top tracked jobs by token volume
$topJobs = AIHub::analytics()->topJobs(10);

// Daily spending trend
$daily = AIHub::analytics()->dailyCost(30);
bash
composer update imrandevbd/laravel-ai-hub
php artisan config:clear
php artisan cache:clear
php artisan view:clear
bash
php artisan vendor:publish --tag=ai-hub-config --force
bash
php artisan vendor:publish --tag=ai-hub-views --force
php artisan view:clear
bash
# Interactive configuration wizard
php artisan ai-hub:configure

# Direct provider setup
php artisan ai-hub:configure gemini --key=YOUR_KEY --model=gemini-4-argon --default
php artisan ai-hub:configure openai --key=YOUR_KEY --model=gpt-6-luna
php artisan ai-hub:configure deepseek --key=YOUR_KEY --model=deepseek-v4.1-flash

# View current masked configuration
php artisan ai-hub:configure --show