PHPackages                             sulimanbenhalim/laravel-ai-cost - 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. sulimanbenhalim/laravel-ai-cost

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

sulimanbenhalim/laravel-ai-cost
===============================

Cost reporting and budget guardrails for the Laravel AI SDK.

v0.1.0(yesterday)00MITPHPPHP ^8.3CI passing

Since Jun 18Pushed todayCompare

[ Source](https://github.com/sulimanbenhalim/laravel-ai-cost)[ Packagist](https://packagist.org/packages/sulimanbenhalim/laravel-ai-cost)[ Docs](https://github.com/sulimanbenhalim/laravel-ai-cost)[ RSS](/packages/sulimanbenhalim-laravel-ai-cost/feed)WikiDiscussions main Synced today

READMEChangelogDependencies (7)Versions (2)Used By (0)

Laravel AI Cost
===============

[](#laravel-ai-cost)

Cost reporting and budget guardrails for the [Laravel AI SDK](https://github.com/laravel/ai).

Turn the raw token counts the SDK already returns into real dollars, and give any agent a hard spend budget that stops it before it blows past the limit. It is purely additive: no changes to the AI SDK, just a service provider, a few value objects, and two event listeners.

[![Cost & budget dashboard](art/cost-dashboard.png)](art/cost-dashboard.png)

Installation
------------

[](#installation)

```
composer require sulimanbenhalim/laravel-ai-cost
```

The package auto-registers. Optionally publish the config:

```
php artisan vendor:publish --tag=ai-cost-config
```

Cost reporting
--------------

[](#cost-reporting)

`AiCost::for()` prices a text or agent response from its usage and model:

```
use SulimanBenhalim\AiCost\Facades\AiCost;

$response = (new ResearchAgent)->prompt('Summarize Q3 earnings', provider: 'anthropic');

$cost = AiCost::for($response);

$cost->total();      // 0.0032
$cost->format();     // "$0.0032"
$cost->breakdown();  // ['input' => 0.000174, 'output' => 0.00303, ...]
```

[![The cost API](art/cost-card.png)](art/cost-card.png)

Pricing is config driven. The package ships a small default table (USD per 1M tokens); add or override models in `config/ai-cost.php`, or at runtime:

```
use SulimanBenhalim\AiCost\Pricing\ModelPricing;
use SulimanBenhalim\AiCost\Pricing\PriceList;

app(PriceList::class)->register('openai', 'my-fine-tune', new ModelPricing(input: 5.0, output: 15.0));
```

A model with no known price returns an unknown cost (`isKnown()` is `false`, total `0`) instead of throwing, so reporting is always safe.

`breakdown()` also includes `cache_read`, `cache_write`, and `reasoning` components. If you have raw usage without a response, price it directly:

```
use Laravel\Ai\Responses\Data\Usage;

AiCost::forUsage(new Usage(promptTokens: 1_000, completionTokens: 500), 'openai', 'gpt-4o');
```

Budgets
-------

[](#budgets)

Tag an agent with `#[MaxCost]`. Once it has spent that budget within the current request or queued job, the next prompt is blocked with a `BudgetExceededException`, before any model call is made:

```
use Laravel\Ai\Contracts\Agent;
use Laravel\Ai\Promptable;
use SulimanBenhalim\AiCost\Attributes\MaxCost;

#[MaxCost(0.50)]
class ResearchAgent implements Agent
{
    use Promptable;
}
```

Inspect spend at any time:

```
use SulimanBenhalim\AiCost\Facades\Budget;

Budget::spent(ResearchAgent::class); // 0.38
Budget::total();                     // across all agents
Budget::reset();                     // e.g. between queue jobs
```

Set `ai-cost.budget.enabled` to `false` to keep cost reporting while turning enforcement off.

### Scope and caveats

[](#scope-and-caveats)

- **Spend is scoped to the request or queued job.** The meter is a scoped binding, so it resets per HTTP request and per queue job. In a long-lived worker that batches many prompts in one job, call `Budget::reset()` between units of work.
- **Budgets only guard models with known pricing.** An unpriced model records `$0`, so its budget never trips; the package logs a warning when a `#[MaxCost]` agent runs on an unpriced model. Register pricing for every budgeted model.
- **Pricing keys match the connection name.** Rates are looked up by `meta->provider`, which is the connection name from your `ai.php` config. Keep connection names equal to the driver (`openai`, `anthropic`, ...) or register pricing under your custom name.
- **A few SDK-level flows are outside this package's reach:** an exception thrown by a sub-agent used as a tool is caught by the SDK and returned as a tool result, so give the parent agent its own budget; streamed spend is recorded only once the stream is fully consumed; and the SDK's automatic conversation-title generation makes its own model call that is not tracked.

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

[](#how-it-works)

The package never touches the AI SDK's classes. It listens to the lifecycle events the SDK already fires:

- `PromptingAgent` / `StreamingAgent` run **before** the model call, so the budget check can abort a request without spending.
- `AgentPrompted` / `AgentStreamed` run **after**, recording the response cost against the agent.

Cost itself is computed from data already public on every response: `usage` (token counts) plus the `provider` and `model` on `meta`. That is why it works across every provider with zero gateway changes.

Testing
-------

[](#testing)

```
composer test
```

Notes
-----

[](#notes)

This started as a proposal to the AI SDK itself ([laravel/ai#721](https://github.com/laravel/ai/pull/721)). The maintainers prefer to keep that package lean and suggested releasing it standalone, which is what this is. The price table in particular is better maintained here, where it can be versioned independently of the SDK.

License
-------

[](#license)

MIT. See [LICENSE.md](LICENSE.md).

###  Health Score

37

—

LowBetter than 81% of packages

Maintenance100

Actively maintained with recent releases

Popularity0

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity38

Early-stage or recently created project

 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

1d ago

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/44615499?v=4)[Suliman Benhalim](/maintainers/sulimanbenhalim)[@sulimanbenhalim](https://github.com/sulimanbenhalim)

---

Top Contributors

[![sulimanbenhalim](https://avatars.githubusercontent.com/u/44615499?v=4)](https://github.com/sulimanbenhalim "sulimanbenhalim (1 commits)")

---

Tags

laraveltokensaillmcostpricingbudget

###  Code Quality

TestsPest

Static AnalysisPHPStan

Code StyleLaravel Pint

Type Coverage Yes

### Embed Badge

![Health badge](/badges/sulimanbenhalim-laravel-ai-cost/health.svg)

```
[![Health](https://phpackages.com/badges/sulimanbenhalim-laravel-ai-cost/health.svg)](https://phpackages.com/packages/sulimanbenhalim-laravel-ai-cost)
```

###  Alternatives

[psalm/plugin-laravel

Psalm plugin for Laravel

3325.1M337](/packages/psalm-plugin-laravel)[laravel/ai

The official AI SDK for Laravel.

9782.1M157](/packages/laravel-ai)[moonshine/moonshine

Laravel administration panel

1.3k239.9k74](/packages/moonshine-moonshine)[linkxtr/laravel-qrcode

A clean, modern, and easy-to-use QR code generator for Laravel

3614.9k](/packages/linkxtr-laravel-qrcode)[tomshaw/electricgrid

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

119.2k](/packages/tomshaw-electricgrid)[mohamed-ashraf-elsaed/claude-agent-sdk-laravel

Anthropic Claude Agent SDK for PHP &amp; Laravel — build AI agents with tool use, sandboxing, MCP servers, subagents, hooks, and structured output via the Claude Code CLI

151.1k](/packages/mohamed-ashraf-elsaed-claude-agent-sdk-laravel)

PHPackages © 2026

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