PHPackages                             whilesmart/eloquent-agent-metrics - 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. [Utility &amp; Helpers](/categories/utility)
4. /
5. whilesmart/eloquent-agent-metrics

ActiveLibrary[Utility &amp; Helpers](/categories/utility)

whilesmart/eloquent-agent-metrics
=================================

Metrics for AI agent runs in Laravel, starting with a polymorphic, cost-aware LLM token-usage ledger.

1.0.0(1mo ago)0292MITPHP ^8.2

Since Jul 6Compare

[ Source](https://github.com/whilesmartphp/eloquent-agent-metrics)[ Packagist](https://packagist.org/packages/whilesmart/eloquent-agent-metrics)[ RSS](/packages/whilesmart-eloquent-agent-metrics/feed)WikiDiscussions Synced 1w ago

READMEChangelog (1)Dependencies (5)Versions (4)Used By (0)

Eloquent Agent Metrics
======================

[](#eloquent-agent-metrics)

Metrics for AI agent runs in Laravel. Its first metric is a polymorphic, cost-aware LLM token-usage ledger: attribute every model call to any owner (user, workspace, organization) and, optionally, to the thing that produced it (a chat message, a report, an enriched record), derive cost from configurable per-model pricing, and query usage and spend per owner. It is built to grow into other agent-run measurements (latency, tool calls, outcomes) over time.

Built to be reused across projects: the ledger is provider-neutral and stores plain `provider`/`model` strings, so it works with any LLM stack (Prism, a raw SDK, anything) that can hand you prompt and completion token counts.

Install
-------

[](#install)

```
composer require whilesmart/eloquent-agent-metrics
php artisan vendor:publish --tag=token-usage-config
php artisan vendor:publish --tag=token-usage-migrations
php artisan migrate
```

Record usage
------------

[](#record-usage)

`TokenMeter` is the single write path. Give it the owner, the provider and model that ran, and the raw usage counts; it derives the total and the cost and writes one immutable row.

```
use Whilesmart\AgentMetrics\Facades\TokenMeter;

TokenMeter::record(
    owner: $workspace,
    provider: 'gemini',
    model: 'gemini-2.0-flash',
    usage: ['prompt_tokens' => 1200, 'completion_tokens' => 300],
    operation: 'report.narrative',
    subject: $report,            // optional: what produced the usage
    metadata: ['harness' => 'report-writer'],
);
```

The `usage` array matches the shape most engines already return (`prompt_tokens`, `completion_tokens`, and an optional `total_tokens`).

Query an owner
--------------

[](#query-an-owner)

Add the trait to any owner model:

```
use Whilesmart\AgentMetrics\Traits\HasTokenUsage;

class Workspace extends Model
{
    use HasTokenUsage;
}

$workspace->tokensUsed(now()->startOfMonth());   // tokens this month
$workspace->tokenCost(now()->startOfMonth());    // cost in currency micro-units
```

Pricing
-------

[](#pricing)

`config/token-usage.php` holds a per-model pricing map. Each rate is the price in currency micro-units (1e-6 of one unit) per 1,000,000 tokens. A model with no entry records a null cost while still counting tokens.

API
---

[](#api)

Read endpoints, scoped to the owners the authenticated user may access (via `whilesmart/eloquent-owner-access`):

- `GET /api/token-usage` paginated ledger, filterable by `owner_type`/`owner_id`, `operation`, `provider`, `model`, `since`, `until`.
- `GET /api/token-usage/{id}` a single row.
- `GET /api/token-usage/summary` aggregated totals plus breakdowns by operation and model.

Set `TOKEN_USAGE_REGISTER_ROUTES=false` to register your own routes instead.

Customization
-------------

[](#customization)

Three seams let a host adapt the package without forking it.

**Response formatter.** Point `response_formatter` at your own class implementing `Whilesmart\AgentMetrics\Interfaces\ResponseFormatterInterface` to change the API envelope:

```
// config/token-usage.php
'response_formatter' => \App\Http\AgentMetrics\MyFormatter::class,
```

**Middleware hooks.** Register classes implementing `Whilesmart\AgentMetrics\Interfaces\MiddlewareHookInterface`; each runs `before` (may return a replacement `Request`) and `after` (returns the `JsonResponse`) around every read action, keyed by a `HookAction` (`index`, `show`, `summary`):

```
// config/token-usage.php
'middleware_hooks' => [
    \App\Http\AgentMetrics\UsageHook::class,
],
```

**Events.** `Whilesmart\AgentMetrics\Events\TokenUsageRecorded` fires after every recorded row, so you can enforce quotas or fan out to your own analytics from a listener.

###  Health Score

42

—

FairBetter than 88% of packages

Maintenance90

Actively maintained with recent releases

Popularity16

Limited adoption so far

Community2

Small or concentrated contributor base

Maturity48

Maturing project, gaining track record

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

48d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/a1ca6f6e01ecbfe6640ff410c4f0321054fb48d05a5f843c2b89887b90369bcd?d=identicon)[whilesmart](/maintainers/whilesmart)

###  Code Quality

Code StyleLaravel Pint

### Embed Badge

![Health badge](/badges/whilesmart-eloquent-agent-metrics/health.svg)

```
[![Health](https://phpackages.com/badges/whilesmart-eloquent-agent-metrics/health.svg)](https://phpackages.com/packages/whilesmart-eloquent-agent-metrics)
```

###  Alternatives

[crumbls/layup

A visual page builder plugin for Filament 5 — Divi-style grid layouts with extensible widgets.

604.0k2](/packages/crumbls-layup)[duncanmcclean/statamic-cargo

Comprehensive e-commerce addon for Statamic. Build bespoke e-commerce sites without the complexity.

3622.8k](/packages/duncanmcclean-statamic-cargo)[tomshaw/electricgrid

A feature-rich Livewire package designed for projects that require dynamic, interactive data tables.

119.8k](/packages/tomshaw-electricgrid)

PHPackages © 2026

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