PHPackages                             lmromax/laravel-ai-sentinel - 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. lmromax/laravel-ai-sentinel

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

lmromax/laravel-ai-sentinel
===========================

AI prompt optimization and cost tracking for Laravel

1.1.0(3mo ago)06MITPHPPHP ^8.2CI passing

Since Feb 18Pushed 3mo agoCompare

[ Source](https://github.com/LMRomax/laravel-ai-sentinel)[ Packagist](https://packagist.org/packages/lmromax/laravel-ai-sentinel)[ Docs](https://github.com/lmromax/laravel-ai-sentinel)[ RSS](/packages/lmromax-laravel-ai-sentinel/feed)WikiDiscussions main Synced 3w ago

READMEChangelogDependencies (18)Versions (3)Used By (0)

🤖 Laravel AI Sentinel
=====================

[](#-laravel-ai-sentinel)

[![Latest Version on Packagist](https://camo.githubusercontent.com/af9bcce8bf04f32892c4d9a0fc0e14d0fd59e2602c18dcb4ec1b9116c8e6f933/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f6c6d726f6d61782f6c61726176656c2d61692d73656e74696e656c2e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/lmromax/laravel-ai-sentinel)[![GitHub Tests Action Status](https://camo.githubusercontent.com/1ae68730233df2097cd66a67480cdf3c1d61b6df687f7d517a0e101f1d028a7a/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f616374696f6e732f776f726b666c6f772f7374617475732f6c6d726f6d61782f6c61726176656c2d61692d73656e74696e656c2f74657374732e796d6c3f6272616e63683d6d61696e266c6162656c3d7465737473267374796c653d666c61742d737175617265)](https://github.com/lmromax/laravel-ai-sentinel/actions?query=workflow%3Atests+branch%3Amain)[![GitHub Code Style Action Status](https://camo.githubusercontent.com/6a974800a1ff27f33c926d413ae916f504470e0e4c752b858759a8a69963b558/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f616374696f6e732f776f726b666c6f772f7374617475732f6c6d726f6d61782f6c61726176656c2d61692d73656e74696e656c2f636f64652d7374796c652e796d6c3f6272616e63683d6d61696e266c6162656c3d636f64652532307374796c65267374796c653d666c61742d737175617265)](https://github.com/lmromax/laravel-ai-sentinel/actions?query=workflow%3A%22code-style%22+branch%3Amain)[![Total Downloads](https://camo.githubusercontent.com/28226475851221a51274d30654428a21997b2f3ef818ed5e98b146da0a660d16/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f6c6d726f6d61782f6c61726176656c2d61692d73656e74696e656c2e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/lmromax/laravel-ai-sentinel)[![License](https://camo.githubusercontent.com/bc2557713d01bad7e2fbf45706eb43c45daaa8af27351695568f47fb7d980ff2/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f6c2f6c6d726f6d61782f6c61726176656c2d61692d73656e74696e656c2e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/lmromax/laravel-ai-sentinel)

**Track, optimize and control your AI API costs in Laravel.**

Laravel AI Sentinel gives you full visibility over your AI spending (OpenAI, Anthropic, Groq, Google, Mistral...) with a beautiful real-time dashboard, prompt logging, cost calculation, AI-powered optimization and spending alerts.

---

✨ Features
----------

[](#-features)

- 📊 **Real-time Dashboard** — Beautiful Livewire dashboard with cost analytics and historical trends
- 💰 **Cost tracking** — Automatic cost calculation per request (input + output tokens)
- 🤖 **AI-powered optimization** — Intelligent prompt compression using GPT-4o-mini (saves up to 70% tokens)
- 📈 **Analytics** — Daily/monthly reports, provider breakdown, top models, historical charts (3M/6M/12M)
- 🔔 **Alerts** — Email notifications when you exceed spending limits
- 🧪 **Optimizer UI** — Interactive tool to test prompt compression with before/after comparison
- 🔄 **Auto-sync pricing** — Always up-to-date pricing from a maintained remote source
- 🛠️ **Artisan commands** — Manage and inspect your AI usage from the CLI
- 🧩 **Provider agnostic** — Works with any AI provider

---

📦 Requirements
--------------

[](#-requirements)

- PHP 8.2+
- Laravel 11.0+ or 12.0+
- Livewire 3.0+

---

🚀 Installation
--------------

[](#-installation)

```
composer require lmromax/laravel-ai-sentinel
```

### Quick install (recommended)

[](#quick-install-recommended)

```
php artisan ai-sentinel:install
```

This will:

- Publish config file
- Publish and run migrations
- Publish views (optional)

### Manual installation

[](#manual-installation)

```
# Publish config
php artisan vendor:publish --tag=ai-sentinel-config

# Publish and run migrations
php artisan vendor:publish --tag=ai-sentinel-migrations
php artisan migrate

# (Optional) Publish views for customization
php artisan vendor:publish --tag=ai-sentinel-views
```

---

⚙️ Configuration
----------------

[](#️-configuration)

Add the following variables to your `.env` file:

```
# Enable tracking
AI_SENTINEL_ENABLED=true
AI_SENTINEL_AUTO_SYNC=true

# Spending alerts
AI_SENTINEL_ALERTS_ENABLED=true
AI_SENTINEL_DAILY_LIMIT=100
AI_SENTINEL_MONTHLY_LIMIT=1000
AI_SENTINEL_ALERT_EMAILS=admin@example.com,billing@example.com

# AI-powered prompt compression (optional but recommended)
AI_SENTINEL_USE_AI_COMPRESSION=true
AI_SENTINEL_COMPRESSION_PROVIDER=openai
AI_SENTINEL_COMPRESSION_MODEL=gpt-4o-mini

# API Keys (only for providers you use)
OPENAI_API_KEY=sk-...
ANTHROPIC_API_KEY=sk-ant-...
GROQ_API_KEY=gsk_...
GOOGLE_AI_API_KEY=...
MISTRAL_API_KEY=...
```

---

📊 Dashboard
-----------

[](#-dashboard)

Access the beautiful real-time dashboard at:

```
http://your-app.com/ai-sentinel

```

**Features:**

- Today's spending &amp; monthly totals
- Cost charts (last 30 days)
- Provider breakdown (pie chart)
- Top models by cost (with medals 🥇🥈🥉)
- Historical trends (3M/6M/12M interactive charts)
- Recent activity logs
- Monthly limit progress bar

---

🧪 Prompt Optimizer
------------------

[](#-prompt-optimizer)

Test prompt compression in real-time at:

```
http://your-app.com/ai-sentinel/optimizer

```

**Features:**

- Before/after comparison
- Token count (original vs optimized)
- Compression ratio percentage
- Estimated cost savings
- Copy optimized prompt button

---

📖 Usage
-------

[](#-usage)

### Auto-tracking with Facades (recommended)

[](#auto-tracking-with-facades-recommended)

```
use Lmromax\LaravelAiSentinel\Facades\AI;

// Automatically optimizes and tracks in one call
$response = AI::openai('gpt-4o', 'Your prompt here');
$response = AI::anthropic('claude-3-5-sonnet-20241022', 'Your prompt');
$response = AI::groq('llama-3.3-70b-versatile', 'Your prompt');
```

### Manual tracking

[](#manual-tracking)

```
use Lmromax\LaravelAiSentinel\Facades\AiSentinel;

// After calling your AI provider, track the request
AiSentinel::track([
    'provider'      => 'anthropic',
    'model'         => 'claude-3-5-sonnet-20241022',
    'prompt'        => 'Explain Laravel in 50 words',
    'response'      => 'Laravel is a PHP framework...',
    'tokens_input'  => 120,
    'tokens_output' => 95,
    'duration_ms'   => 1200,
]);
```

### Optimize a prompt before sending

[](#optimize-a-prompt-before-sending)

```
$result = AiSentinel::optimize('Please can you help me to explain what Laravel is ?');

// Returns:
// [
//     'original'          => 'Please can you help me to explain what Laravel is ?',
//     'optimized'         => 'Explain what Laravel is',
//     'tokens_original'   => 14,
//     'tokens_optimized'  => 5,
//     'tokens_saved'      => 9,
//     'compression_ratio' => 64.29,
// ]

// Use the optimized prompt
$response = $yourAiClient->send($result['optimized']);
```

**Note:** AI-powered compression requires `openai-php/laravel` package:

```
composer require openai-php/laravel
```

### Get cost statistics

[](#get-cost-statistics)

```
// Today
$stats = AiSentinel::getCostStats('day');

// This week
$stats = AiSentinel::getCostStats('week');

// This month
$stats = AiSentinel::getCostStats('month');

// Returns:
// [
//     'total_requests'     => 142,
//     'total_cost'         => 4.23,
//     'total_tokens_input' => 58000,
//     'total_tokens_output'=> 32000,
//     'avg_cost_per_request' => 0.029,
//     'by_provider'        => [...],
//     'by_model'           => [...],
// ]
```

### Get total cost

[](#get-total-cost)

```
$monthlyCost = AiSentinel::getTotalCost('month'); // 4.23
$dailyCost   = AiSentinel::getTotalCost('day');   // 0.87
```

### Calculate cost manually

[](#calculate-cost-manually)

```
$cost = AiSentinel::calculateCost(
    provider: 'openai',
    model: 'gpt-4o',
    tokensInput: 500,
    tokensOutput: 300
);
// Returns: 0.004250 (USD)
```

### Estimate tokens

[](#estimate-tokens)

```
$tokens = AiSentinel::estimateTokens('Hello, how are you today?');
// Returns: ~8
```

---

🔄 Pricing Sync
--------------

[](#-pricing-sync)

Laravel AI Sentinel automatically fetches up-to-date pricing from [lmromax/ai-pricing-data](https://github.com/lmromax/ai-pricing-data) every 24 hours.

### Manual sync

[](#manual-sync)

```
# Sync pricing
php artisan ai-sentinel:sync-pricing

# Force refresh cache
php artisan ai-sentinel:sync-pricing --force

# Display all available models
php artisan ai-sentinel:sync-pricing --show
```

### Add a custom model

[](#add-a-custom-model)

If your model is not in the remote pricing source, add it to `config/ai-sentinel.php`:

```
'custom_models' => [
    'my-provider' => [
        'my-custom-model' => [
            'input'  => 0.01,
            'output' => 0.02,
        ],
    ],
],
```

---

📊 Real-world example with OpenAI
--------------------------------

[](#-real-world-example-with-openai)

```
use OpenAI\Laravel\Facades\OpenAI;
use Lmromax\LaravelAiSentinel\Facades\AiSentinel;

public function askAi(string $question): string
{
    // 1. Optimize the prompt (AI-powered compression)
    $optimized = AiSentinel::optimize($question);

    $start = microtime(true);

    // 2. Call OpenAI
    $response = OpenAI::chat()->create([
        'model'    => 'gpt-4o',
        'messages' => [
            ['role' => 'user', 'content' => $optimized['optimized']],
        ],
    ]);

    $duration = (int) ((microtime(true) - $start) * 1000);

    // 3. Track the request
    AiSentinel::track([
        'provider'      => 'openai',
        'model'         => 'gpt-4o',
        'prompt'        => $optimized['optimized'],
        'response'      => $response->choices[0]->message->content,
        'tokens_input'  => $response->usage->promptTokens,
        'tokens_output' => $response->usage->completionTokens,
        'duration_ms'   => $duration,
        'metadata'      => [
            'tokens_saved' => $optimized['tokens_saved'],
        ],
    ]);

    return $response->choices[0]->message->content;
}
```

**Or use the auto-tracking facade (even simpler):**

```
use Lmromax\LaravelAiSentinel\Facades\AI;

public function askAi(string $question): string
{
    // Automatically optimizes + tracks in one call
    return AI::openai('gpt-4o', $question);
}
```

---

📊 Real-world example with Anthropic
-----------------------------------

[](#-real-world-example-with-anthropic)

```
use Anthropic\Laravel\Facades\Anthropic;
use Lmromax\LaravelAiSentinel\Facades\AiSentinel;

public function askClaude(string $question): string
{
    $optimized = AiSentinel::optimize($question);

    $start = microtime(true);

    $response = Anthropic::messages()->create([
        'model'      => 'claude-3-5-sonnet-20241022',
        'max_tokens' => 1024,
        'messages'   => [
            ['role' => 'user', 'content' => $optimized['optimized']],
        ],
    ]);

    $duration = (int) ((microtime(true) - $start) * 1000);

    AiSentinel::track([
        'provider'      => 'anthropic',
        'model'         => 'claude-3-5-sonnet-20241022',
        'prompt'        => $optimized['optimized'],
        'response'      => $response->content[0]->text,
        'tokens_input'  => $response->usage->inputTokens,
        'tokens_output' => $response->usage->outputTokens,
        'duration_ms'   => $duration,
    ]);

    return $response->content[0]->text;
}
```

---

🔔 Spending Alerts
-----------------

[](#-spending-alerts)

Configure spending limits in your `.env`:

```
AI_SENTINEL_DAILY_LIMIT=50      # Alert when daily spend exceeds $50
AI_SENTINEL_MONTHLY_LIMIT=500   # Alert when monthly spend exceeds $500
AI_SENTINEL_ALERT_EMAILS=admin@example.com,billing@example.com
```

Alerts are sent via Laravel's notification system. Supported channels: `mail`, `slack`, `discord`.

**Customize notifications:**

Publish notification views:

```
php artisan vendor:publish --tag=ai-sentinel-views
```

Edit `resources/views/vendor/ai-sentinel/notifications/`.

---

🛠️ Artisan Commands
-------------------

[](#️-artisan-commands)

CommandDescription`ai-sentinel:install`Quick install (config + migrations)`ai-sentinel:sync-pricing`Sync pricing from remote source`ai-sentinel:sync-pricing --force`Force refresh cache`ai-sentinel:sync-pricing --show`Display all available models`ai-sentinel:cost-summary`Display cost summary in terminal`ai-sentinel:cleanup`Clear old logs (90+ days)---

🧩 Supported Providers
---------------------

[](#-supported-providers)

ProviderStatusOpenAI (GPT-4o, o1, o3...)✅Anthropic (Claude 3.5, 3.7...)✅Groq (Llama, Mixtral...)✅Google (Gemini 2.0, 1.5...)✅Mistral✅DeepSeek✅xAI (Grok)✅Custom provider✅ via `custom_models`---

🎨 Customization
---------------

[](#-customization)

### Customize dashboard views

[](#customize-dashboard-views)

```
php artisan vendor:publish --tag=ai-sentinel-views
```

Views are published to `resources/views/vendor/ai-sentinel/`.

### Customize routes

[](#customize-routes)

Add to your `routes/web.php`:

```
use Lmromax\LaravelAiSentinel\Http\Controllers\DashboardController;

Route::middleware(['web', 'auth'])->group(function () {
    Route::get('/my-custom-path', [DashboardController::class, 'index']);
});
```

---

🧪 Testing
---------

[](#-testing)

```
composer test
```

---

🤝 Contributing
--------------

[](#-contributing)

Contributions are welcome! Please feel free to submit a Pull Request.

---

📜 License
---------

[](#-license)

MIT — [Maxence Lemaitre](https://github.com/LMRomax)

---

🙏 Credits
---------

[](#-credits)

- **Pricing Data:** Automatically synced from [lmromax/ai-pricing-data](https://github.com/lmromax/ai-pricing-data)
- **Built with:** Laravel, Livewire, Chart.js, Tailwind CSS

###  Health Score

37

—

LowBetter than 81% of packages

Maintenance82

Actively maintained with recent releases

Popularity4

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

Every ~33 days

Total

2

Last Release

95d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/848cec1eeb9897eec487c91906729876e4c2798a267d0929407a5af2243166fc?d=identicon)[LMRomax](/maintainers/LMRomax)

---

Top Contributors

[![MaxLemRM](https://avatars.githubusercontent.com/u/185774823?v=4)](https://github.com/MaxLemRM "MaxLemRM (29 commits)")

---

Tags

laravelaiopenaiclaudeanthropiccost-trackingprompt

###  Code Quality

TestsPest

Code StyleLaravel Pint

### Embed Badge

![Health badge](/badges/lmromax-laravel-ai-sentinel/health.svg)

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

###  Alternatives

[psalm/plugin-laravel

Psalm plugin for Laravel

3345.1M337](/packages/psalm-plugin-laravel)[larastan/larastan

Larastan - Discover bugs in your code without running it. A phpstan/phpstan extension for Laravel

6.4k51.0M7.6k](/packages/larastan-larastan)[laravel/ai

The official AI SDK for Laravel.

9782.1M162](/packages/laravel-ai)[api-platform/laravel

API Platform support for Laravel

59156.3k11](/packages/api-platform-laravel)[simplestats-io/laravel-client

Analytics for Laravel. Track visitors, registrations, and payments. Discover which channels actually drive revenue, not just traffic. Server-side, GDPR compliant, ad-blocker proof.

5019.3k](/packages/simplestats-io-laravel-client)[calebdw/larastan

Larastan - Discover bugs in your code without running it. A phpstan/phpstan extension for Laravel

15104.9k4](/packages/calebdw-larastan)

PHPackages © 2026

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