PHP code example of backtik-ch / laravel-ai-usage

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

    

backtik-ch / laravel-ai-usage example snippets


// config/ai-usage.php
'prices' => [
    'openai' => [
        'gpt-4o' => ['prompt' => 2.50, 'completion' => 10.00],
        'gpt-4o-mini' => ['prompt' => 0.15, 'completion' => 0.60],
        // ...
    ],
    'anthropic' => [
        'claude-sonnet-4-5' => [
            'prompt' => 3.00, 'completion' => 15.00,
            'cache_read' => 0.30, 'cache_write' => 3.75,
        ],
        // ...
    ],
    'gemini' => [
        'gemini-2.0-flash' => ['prompt' => 0.10, 'completion' => 0.40],
        // ...
    ],
],

use BacktikCh\LaravelAiUsage\Facades\AiUsage;

AiUsage::driver('openai')
    ->model('gpt-4o')
    ->label('summarize-article')
    ->agentClass(MyAgent::class)          // optional — FQCN of the agent
    ->tokens(
        prompt: 512,
        completion: 256,
        cacheWrite: 0,                    // optional
        cacheRead: 0,                     // optional
        reasoning: 0,                     // optional
    )
    ->duration(milliseconds: 1200)
    ->prompt('Summarize this article...')
    ->response('The article discusses...')
    ->status('completed')
    ->requestMeta(['temperature' => 0.7]) // optional arbitrary metadata
    ->responseMeta(['finish_reason' => 'stop'])
    ->log();

AiUsage::driver('openai')
    ->model('gpt-4o')
    ->tokens(300, 150)
    ->owner($user) // any Eloquent model
    ->log();

AiUsage::driver('openai')
    ->model('gpt-4o')
    ->tokens(300, 150)
    ->costPrices(['prompt' => 2.50, 'completion' => 10.00])
    ->log();

$log = AiUsageLog::find(1);
echo $log->estimated_cost; // e.g. 0.003450

use BacktikCh\LaravelAiUsage\Filament\AiUsagePlugin;

public function panel(Panel $panel): Panel
{
    return $panel
        // ...
        ->plugin(AiUsagePlugin::make());
}

use BacktikCh\LaravelAiUsage\Filament\Widgets\AiUsageSummaryWidget;

protected function getHeaderWidgets(): array
{
    return [AiUsageSummaryWidget::class];
}

Schedule::command('ai-usage:mark-stale-failed')->hourly();
Schedule::command('ai-usage:prune')->daily();
bash
php artisan vendor:publish --tag=ai-usage-config
php artisan migrate
bash
php artisan ai-usage:prune --days=90
bash
php artisan ai-usage:mark-stale-failed
bash
php artisan ai-usage:mark-stale-failed --minutes=30