Monitor and analyze token consumption metrics from AI model responses in LarAgent
Usage tracking in LarAgent automatically captures token consumption metrics, helping you monitor API usage, estimate costs, and optimize your AI agent implementations.
Enable or disable tracking dynamically at runtime:
Copy
// Enable tracking for a specific request$agent = SupportAgent::for('session-123') ->trackUsage(true) ->respond('Hello!');// Disable tracking$agent->trackUsage(false);
The methods below allow you to access and analyze usage data tracked by LarAgent for any driver, but if you use the EloquentUsageDriver (or "database" alias), you also have direct access to the underlying database model for advanced queries.
// Get the usage storage instance$usageStorage = $agent->usageStorage();// Returns null if tracking is disabledif ($usageStorage === null) { // Tracking is disabled}
// Get all usage records for this agent/user$usage = $agent->getUsage();// Get usage with filters$usage = $agent->getUsage([ 'model_name' => 'gpt-4', 'date' => '2024-01-15',]);
The model includes convenient query scopes for filtering:
Copy
use LarAgent\Usage\Models\LaragentUsage;// Filter by agentLaragentUsage::forAgent('SupportAgent')->get();// Filter by userLaragentUsage::forUser('user-123')->get();// Filter by modelLaragentUsage::forModel('gpt-4')->get();// Filter by providerLaragentUsage::forProvider('openai')->get();// Filter by groupLaragentUsage::forGroup('premium-users')->get();// Filter by date rangeLaragentUsage::betweenDates('2024-01-01', '2024-01-31')->get();// Filter by specific dateLaragentUsage::onDate('2024-01-15')->get();// Chain multiple scopesLaragentUsage::forAgent('SupportAgent') ->forProvider('openai') ->betweenDates('2024-01-01', '2024-01-31') ->get();
use LarAgent\Usage\Models\LaragentUsage;// Get aggregate totals for all records$totals = LaragentUsage::aggregate();// Returns:// [// 'total_prompt_tokens' => 15000,// 'total_completion_tokens' => 8000,// 'total_tokens' => 23000,// 'record_count' => 150,// ]// Aggregate with filters (pass a query builder)$query = LaragentUsage::forAgent('SupportAgent') ->betweenDates('2024-01-01', '2024-01-31');$totals = LaragentUsage::aggregate($query);// Group by a column$byModel = LaragentUsage::groupByColumn('model_name');// Returns Collection keyed by model_name
Leverage Laravel’s query builder for complex analytics:
Daily Usage
Top Users
Cost Estimation
Copy
// Get daily token usage for the last 30 days$dailyUsage = LaragentUsage::query() ->where('recorded_at', '>=', now()->subDays(30)) ->selectRaw('DATE(recorded_at) as date, SUM(total_tokens) as tokens') ->groupBy('date') ->orderBy('date') ->get();
Copy
// Get top users by token consumption$topUsers = LaragentUsage::query() ->whereNotNull('user_id') ->selectRaw('user_id, SUM(total_tokens) as total_tokens, COUNT(*) as requests') ->groupBy('user_id') ->orderByDesc('total_tokens') ->limit(10) ->get();
Copy
// Calculate estimated costs$costs = LaragentUsage::query() ->forProvider('openai') ->betweenDates('2024-01-01', '2024-01-31') ->selectRaw(" model_name, SUM(prompt_tokens) as prompt_tokens, SUM(completion_tokens) as completion_tokens, CASE model_name WHEN 'gpt-4' THEN (SUM(prompt_tokens) / 1000 * 0.03) + (SUM(completion_tokens) / 1000 * 0.06) WHEN 'gpt-3.5-turbo' THEN (SUM(prompt_tokens) / 1000 * 0.001) + (SUM(completion_tokens) / 1000 * 0.002) ELSE 0 END as estimated_cost ") ->groupBy('model_name') ->get();
<?phpnamespace App\Jobs;use App\Services\UsageAnalyticsService;use App\Notifications\UsageThresholdExceeded;use Illuminate\Bus\Queueable;use Illuminate\Contracts\Queue\ShouldQueue;class CheckUsageThresholds implements ShouldQueue{ use Queueable; protected int $dailyThreshold = 1000000; // 1M tokens public function handle(UsageAnalyticsService $analytics): void { $today = now()->format('Y-m-d'); $usage = $analytics->getTotalUsage($today, $today); if ($usage['total_tokens'] > $this->dailyThreshold) { $admin = \App\Models\User::find(1); $admin->notify(new UsageThresholdExceeded($usage)); } }}
5
Schedule the Alert
app/Console/Kernel.php
Copy
protected function schedule(Schedule $schedule){ $schedule->job(new CheckUsageThresholds)->hourly();}
Your cost monitoring dashboard is now ready to track usage and alert on thresholds.
For production applications, consider setting up usage alerts at different thresholds (50%, 75%, 90%) to proactively manage costs before hitting limits.