PHPackages                             sanjayacloud/ai-model-usage-tracker - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. sanjayacloud/ai-model-usage-tracker

ActiveLibrary

sanjayacloud/ai-model-usage-tracker
===================================

Accurately track AI model usage, tokens, and cost in Laravel with automatic instrumentation, reporting, and an Inertia dashboard.

v1.0.0(today)00MITPHPPHP ^8.3CI passing

Since Aug 14Pushed todayCompare

[ Source](https://github.com/sanjayacloud/ai-model-usage-tracker)[ Packagist](https://packagist.org/packages/sanjayacloud/ai-model-usage-tracker)[ Docs](https://github.com/sanjayacloud/ai-model-usage-tracker)[ GitHub Sponsors](https://github.com/sanjayacloud)[ RSS](/packages/sanjayacloud-ai-model-usage-tracker/feed)WikiDiscussions main Synced today

READMEChangelog (1)Dependencies (11)Versions (2)Used By (0)

AI Model Usage Tracker
======================

[](#ai-model-usage-tracker)

 [![Packagist](https://camo.githubusercontent.com/3ff0385a1e1ab4c084a3cd6c295d1fc4ca0177230934668652e2be55d87b7711/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f73616e6a617961636c6f75642f61692d6d6f64656c2d75736167652d747261636b65722e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/sanjayacloud/ai-model-usage-tracker) [![PHP from Packagist](https://camo.githubusercontent.com/a49c57c7537477387b4db3a8dee5a32e87212155fdb3bcc8ce3611c9e0831e89/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f7068702d762f73616e6a617961636c6f75642f61692d6d6f64656c2d75736167652d747261636b65722e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/sanjayacloud/ai-model-usage-tracker) [![GitHub Workflow Status (main)](https://camo.githubusercontent.com/0b7b0856eda77f68d40ff64a76d3483a5736d4da221590aadf89fbb0881cba1e/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f616374696f6e732f776f726b666c6f772f7374617475732f73616e6a617961636c6f75642f61692d6d6f64656c2d75736167652d747261636b65722f74657374732e796d6c3f6272616e63683d6d61696e266c6162656c3d5465737473267374796c653d666c61742d737175617265)](https://github.com/sanjayacloud/ai-model-usage-tracker/actions) [![Total Downloads](https://camo.githubusercontent.com/7f6380d7be770f7285a3b57cb325c7011cbad30419e0d14349e2a37c94641c13/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f73616e6a617961636c6f75642f61692d6d6f64656c2d75736167652d747261636b65722e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/sanjayacloud/ai-model-usage-tracker)

Accurately track AI model usage in your Laravel app: token counts, **computed cost**, latency, success/failure, per-user attribution, and per-conversation attribution. Capture usage automatically from the first-party [`laravel/ai`](https://github.com/laravel/ai) SDK (plus Prism and raw HTTP clients), or record it manually with a fluent API. Includes a headless reporting layer, budget alerts, and an optional Inertia/Vue dashboard.

Features
--------

[](#features)

- **Automatic capture** for the `laravel/ai` SDK — no code changes required.
- **Computed cost** from a configurable per-model pricing table (input, output, cache read/write, reasoning).
- **Per-request, per-user, and per-conversation** attribution.
- **Reporting API** — totals, breakdowns by model/provider/operation, daily trends, top consumers.
- **Budgets** with threshold events, **retention** pruning, and an optional **Inertia/Vue dashboard**.
- **Sync or queued** persistence.

Requirements
------------

[](#requirements)

- PHP 8.3+
- Laravel 12 or 13
- (Optional) [`laravel/ai`](https://github.com/laravel/ai) for automatic instrumentation
- (Optional) Inertia + Vue for the bundled dashboard

How it works
------------

[](#how-it-works)

Every AI request becomes one row in the `ai_usage_records` table, written through a single pipeline regardless of how it was captured:

```
manual API ─┐
laravel/ai ─┤
Prism      ─┼─▶ UsageTracker ─▶ CostCalculator ─▶ (sync | queue) ─▶ ai_usage_records
raw HTTP   ─┘

```

---

Getting started
---------------

[](#getting-started)

### Step 1 — Install

[](#step-1--install)

```
composer require sanjayacloud/ai-model-usage-tracker
```

The service provider and `AiModelUsageTracker` facade are auto-discovered.

### Step 2 — Publish and run the migration

[](#step-2--publish-and-run-the-migration)

```
php artisan vendor:publish --tag="ai-model-usage-tracker-migrations"
php artisan migrate
```

This creates the `ai_usage_records` table.

### Step 3 — Publish the config (recommended)

[](#step-3--publish-the-config-recommended)

```
php artisan vendor:publish --tag="ai-model-usage-tracker-config"
```

This writes `config/ai-model-usage-tracker.php`, where you control pricing, recording mode, instrumentation, budgets, retention, and the dashboard.

### Step 4 — Capture your first usage

[](#step-4--capture-your-first-usage)

If you use `laravel/ai`, you're already done — the next agent prompt or embedding call is recorded automatically (see [Automatic capture](#automatic-capture-laravelai)).

To record manually from anywhere:

```
use AiModelUsageTracker\AiModelUsageTracker\Facades\AiModelUsageTracker;

AiModelUsageTracker::track()
    ->provider('openai')
    ->model('gpt-4o')
    ->tokens(prompt: 1200, completion: 350)
    ->record();
```

### Step 5 — Read it back

[](#step-5--read-it-back)

```
use AiModelUsageTracker\AiModelUsageTracker\Reporting\UsageReporter;

app(UsageReporter::class)->totals(); // ['records' => 1, 'total_tokens' => 1550, 'total_cost' => 0.0065, ...]
```

That's the full loop: capture → cost → report.

---

Capturing usage
---------------

[](#capturing-usage)

### Automatic capture (laravel/ai)

[](#automatic-capture-laravelai)

Enabled by default. The package listens to the SDK's events (`AgentPrompted`, `AgentStreamed`, `EmbeddingsGenerated`, `ImageGenerated`, `AudioGenerated`, `TranscriptionGenerated`, `ProviderFailedOver`) and records tokens, model, provider, latency, failures — and the conversation id when the call is part of a `laravel/ai` conversation.

Toggle it in config:

```
'instrumentation' => [
    'laravel-ai' => true,
    'prism' => false,
    'http' => false,
],
```

### Manual API (fluent builder)

[](#manual-api-fluent-builder)

```
use AiModelUsageTracker\AiModelUsageTracker\Facades\AiModelUsageTracker;
use AiModelUsageTracker\AiModelUsageTracker\Enums\Operation;

AiModelUsageTracker::for($user) // attribute to any Eloquent model
    ->provider('openai')
    ->model('gpt-4o')
    ->operation(Operation::Chat)
    ->tokens(prompt: 1200, completion: 350, cacheRead: 800, reasoning: 120)
    ->conversation($conversationId) // optional, for per-conversation reporting
    ->latency(840)
    ->meta(['feature' => 'support-bot'])
    ->record();
```

Available builder methods: `provider()`, `model()`, `operation()`, `tokens()`, `latency()`, `status()`, `failed()`, `streamed()`, `for()`, `conversation()`, `invocation()`, `meta()`, `startedAt()`, `endedAt()`, `record()`.

### Prism

[](#prism)

```
$response = Prism::text()->using('openai', 'gpt-4o')->withPrompt('...')->generate();

AiModelUsageTracker::capturePrism($response, $user);
```

Enable it in config (`instrumentation.prism => true`).

### Raw HTTP clients

[](#raw-http-clients)

Set `instrumentation.http => true` to parse OpenAI/Anthropic-style `usage` blocks from outgoing HTTP responses automatically.

---

Attribution
-----------

[](#attribution)

### Per-user (or any model)

[](#per-user-or-any-model)

Use `for()` on the manual builder, or set a global resolver so *every* recorded row is attributed automatically (great for auto-instrumentation):

```
use AiModelUsageTracker\AiModelUsageTracker\Facades\AiModelUsageTracker;

// e.g. in a service provider or middleware
AiModelUsageTracker::resolveTrackableUsing(fn () => auth()->user());
```

### Per-conversation

[](#per-conversation)

When you use `laravel/ai` conversations, the conversation id is captured automatically on each recorded row (`conversation_id`). You can then aggregate usage for a single conversation:

```
use AiModelUsageTracker\AiModelUsageTracker\Reporting\UsageReporter;

$summary = app(UsageReporter::class)->forConversation($conversationId);

$summary['totals'];   // ['records' => 5, 'total_tokens' => 8120, 'total_cost' => 0.0123, ...]
$summary['by_model']; // per-model breakdown for that conversation
```

For manual records, pass the id explicitly with `->conversation($conversationId)`.

---

Per-request usage in your responses
-----------------------------------

[](#per-request-usage-in-your-responses)

Each request is recorded individually, so you can surface its cost inline:

```
use AiModelUsageTracker\AiModelUsageTracker\Facades\AiModelUsageTracker;
use AiModelUsageTracker\AiModelUsageTracker\Http\Resources\UsageResource;

$record = AiModelUsageTracker::forInvocation($invocationId); // or ::latest()

return response()->json([
    'answer' => $answer,
    'usage' => $record ? (new UsageResource($record))->toArray($request) : null,
]);
```

`$record->toUsageArray()` returns a compact block of tokens, cost, currency, and latency.

---

Cost accuracy
-------------

[](#cost-accuracy)

Costs are computed from a configurable pricing table in `config/ai-model-usage-tracker.php`, with bundled rates for common OpenAI, Anthropic, and Gemini models, expressed **per 1,000,000 tokens**. Cached read/write and reasoning tokens are priced separately when rates are provided.

> Requests for models **not** in the table are recorded with a **zero cost** and a `pricing_missing` flag in `metadata`, so gaps are auditable rather than silently wrong.

### Adding pricing for a model

[](#adding-pricing-for-a-model)

If a model shows `$0` cost, add its rates.

1. Publish the config (Step 3 above) if you haven't.
2. Add the model under its provider in `pricing.models`. Rates are per 1M tokens:

```
'pricing' => [
    'currency' => 'USD',
    'models' => [
        'gemini' => [
            'gemini-3.1-flash-lite' => ['input' => 0.25, 'output' => 1.50, 'cache_read' => 0.025],
        ],
    ],
],
```

3. Clear the config cache so the new rate is picked up:

```
php artisan config:clear
```

New records for that model will now be priced. Existing zero-cost rows are left untouched (recompute them yourself if you need a backfill).

Supported rate keys: `input`, `output`, `cache_write`, `cache_read`, `reasoning`. Missing `cache_write`/`cache_read` fall back to `input`; missing `reasoning` falls back to `output`.

---

Reporting
---------

[](#reporting)

```
use AiModelUsageTracker\AiModelUsageTracker\Reporting\UsageReporter;

$reporter = app(UsageReporter::class);

$reporter->totals();                 // records, tokens, cost, failures
$reporter->forConversation($id);     // totals + per-model breakdown for one conversation
$reporter->byModel();                // grouped by model
$reporter->byProvider();             // grouped by provider
$reporter->byOperation();            // grouped by operation
$reporter->dailyTrend();             // cost/tokens per day
$reporter->topConsumers();           // biggest spenders (attributed models)
```

Every method except `forConversation()` accepts optional `$from`/`$to` `DateTimeInterface` bounds.

CLI summary:

```
php artisan ai-usage:report --days=30
```

---

Budgets
-------

[](#budgets)

Define spending caps in config; a `BudgetThresholdReached` event fires the moment a threshold is crossed:

```
'budgets' => [
    'monthly' => ['period' => 'month', 'limit' => 500.0, 'thresholds' => [0.8, 1.0]],
],
```

Listen for the event to send alerts:

```
use AiModelUsageTracker\AiModelUsageTracker\Events\BudgetThresholdReached;

Event::listen(BudgetThresholdReached::class, function (BudgetThresholdReached $event) {
    // notify your team
});
```

---

Recording mode
--------------

[](#recording-mode)

Set `recording.mode` to `sync` (default, always exact) or `queue` to offload writes to a job for high-throughput apps:

```
'recording' => [
    'mode' => 'queue',
    'queue' => ['connection' => null, 'queue' => null],
],
```

---

Retention
---------

[](#retention)

```
php artisan ai-usage:prune --days=90
```

Set `retention_days` in config and schedule the command in `routes/console.php` (or `app/Console/Kernel.php`):

```
use Illuminate\Support\Facades\Schedule;

Schedule::command('ai-usage:prune')->daily();
```

---

Dashboard (Inertia/Vue)
-----------------------

[](#dashboard-inertiavue)

Requires a host app using Inertia + Vue.

### Step 1 — Publish the page component

[](#step-1--publish-the-page-component)

```
php artisan vendor:publish --tag="ai-model-usage-tracker-assets"
```

### Step 2 — Build assets

[](#step-2--build-assets)

```
npm run build
```

### Step 3 — Define the access gate

[](#step-3--define-the-access-gate)

The dashboard is served at the configured `dashboard.path` (default `/ai-usage`) and is protected by the `viewAiUsageDashboard` gate:

```
use Illuminate\Support\Facades\Gate;

Gate::define('viewAiUsageDashboard', fn ($user) => $user->isAdmin());
```

Adjust `dashboard.path` and `dashboard.middleware` in config as needed.

---

Testing
-------

[](#testing)

```
composer test
```

This runs static analysis (PHPStan/Larastan), code style (Pint), 100% type coverage, and the Pest test suite.

Changelog
---------

[](#changelog)

Please see [CHANGELOG](CHANGELOG.md) for more information on what has changed recently.

License
-------

[](#license)

AI Model Usage Tracker is open-sourced software licensed under the [MIT license](LICENSE.md).

###  Health Score

40

—

FairBetter than 86% of packages

Maintenance100

Actively maintained with recent releases

Popularity0

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity48

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Unknown

Total

1

Last Release

0d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/bfc06db8336e75704fabcfa9a9159de32c1b510af7516fc5bd52e9fb803a93f0?d=identicon)[sanjayaprasanna20@gmail.com](/maintainers/sanjayaprasanna20@gmail.com)

---

Top Contributors

[![sanjayacloud](https://avatars.githubusercontent.com/u/34233059?v=4)](https://github.com/sanjayacloud "sanjayacloud (2 commits)")

---

Tags

laraveltokensaiopenaiusageanthropiccostsanjayacloudai-model-usage-tracker

###  Code Quality

TestsPest

Static AnalysisPHPStan

Code StyleLaravel Pint

### Embed Badge

![Health badge](/badges/sanjayacloud-ai-model-usage-tracker/health.svg)

```
[![Health](https://phpackages.com/badges/sanjayacloud-ai-model-usage-tracker/health.svg)](https://phpackages.com/packages/sanjayacloud-ai-model-usage-tracker)
```

###  Alternatives

[laravel/ai

The official AI SDK for Laravel.

1.1k4.6M307](/packages/laravel-ai)[fomvasss/laravel-ai-tasks

AI task orchestrator for Laravel: routing, queue, audit, budget, webhooks

381.6k1](/packages/fomvasss-laravel-ai-tasks)[spectra-php/laravel-spectra

Comprehensive observability for AI/LLM operations in Laravel applications

203.6k](/packages/spectra-php-laravel-spectra)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
