PHP code example of mohammed94 / ai-ledger

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

    

mohammed94 / ai-ledger example snippets


use Mohammed94\AiLedger\Facades\AiLedger;

AiLedger::record(
    provider: 'openai',
    model: 'gpt-4o',
    inputTokens: 1_200,
    outputTokens: 350,
    latencyMs: 840,
    tag: 'chatbot',          // which feature this call belongs to
    userId: auth()->id(),    // who triggered it
);

// Prism
$response = Prism::text()->using('openai', 'gpt-4o')->withPrompt($prompt)->generate();
AiLedger::recordUsage($response->usage, provider: 'openai', model: 'gpt-4o', tag: 'chatbot');

// OpenAI SDK
$result = OpenAI::chat()->create([...]);
AiLedger::recordUsage($result->usage->toArray(), provider: 'openai', model: 'gpt-4o');

AiLedger::cost()->today();                    // 12.46  (USD)
AiLedger::cost()->thisMonth();                // 318.90
AiLedger::cost()->forUser(5)->thisMonth();    // 7.21
AiLedger::cost()->tag('chatbot')->total();    // 96.40
AiLedger::cost()->byModel();                  // ['gpt-4o' => 210.5, 'gpt-4o-mini' => 12.3]
AiLedger::cost()->byUser();                   // ['5' => 7.21, '9' => 3.10]

if (AiLedger::overBudget()) {
    abort(429, 'AI budget exhausted for this period.');
}

AiLedger::remainingBudget(); // 41.60 (USD left this period)

'capture_content' => env('AI_LEDGER_CAPTURE_CONTENT', false), // store raw prompt/response?

'budgets' => [
    'daily'   => env('AI_LEDGER_BUDGET_DAILY'),
    'monthly' => env('AI_LEDGER_BUDGET_MONTHLY'),
],

'pricing' => [
    'openai' => [
        'gpt-4o'      => ['input' => 2.50, 'output' => 10.00], // USD per 1M tokens
        'gpt-4o-mini' => ['input' => 0.15, 'output' => 0.60],
    ],
    // ...
],
bash
composer vendor:publish --tag=ai-ledger-migrations
php artisan vendor:publish --tag=ai-ledger-config
php artisan migrate