承接 lmromax/laravel-ai-sentinel 相关项目开发

从需求分析到上线部署,全程专人跟进,保证项目质量与交付效率

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

lmromax/laravel-ai-sentinel

Composer 安装命令:

composer require lmromax/laravel-ai-sentinel

包简介

AI prompt optimization and cost tracking for Laravel

README 文档

README

Latest Version on Packagist GitHub Tests Action Status GitHub Code Style Action Status Total Downloads License

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

  • 📊 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

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

🚀 Installation

composer require lmromax/laravel-ai-sentinel

Quick install (recommended)

php artisan ai-sentinel:install

This will:

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

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

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

Access the beautiful real-time dashboard at:

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

Features:

  • Today's spending & 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

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

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

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

$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

// 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

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

Calculate cost manually

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

Estimate tokens

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

🔄 Pricing Sync

Laravel AI Sentinel automatically fetches up-to-date pricing from lmromax/ai-pricing-data every 24 hours.

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

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

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

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

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

Command Description
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

Provider Status
OpenAI (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

Customize dashboard views

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

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

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

composer test

🤝 Contributing

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

📜 License

MIT — Maxence Lemaitre

🙏 Credits

  • Pricing Data: Automatically synced from lmromax/ai-pricing-data
  • Built with: Laravel, Livewire, Chart.js, Tailwind CSS

lmromax/laravel-ai-sentinel 适用场景与选型建议

lmromax/laravel-ai-sentinel 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 6 次下载、GitHub Stars 达 0, 最近一次更新时间为 2026 年 03 月 18 日, 在 PHP 生态内属于活跃度较高的组件。

它主要适用于以下技术方向: 「laravel」 「prompt」 「ai」 「openai」 「claude」 「anthropic」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。

我们在过去多个企业项目中使用过 lmromax/laravel-ai-sentinel 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。

围绕 lmromax/laravel-ai-sentinel 我们能提供哪些服务?
定制开发 / 二次开发

基于 lmromax/laravel-ai-sentinel 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。

BUG 修复 & 性能优化

线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。

项目外包 & 长期维护

承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。

yvsm@zunyunkeji.com QQ:316430983 微信:yvsm316 西安尊云信息科技 · 专注 PHP / Go / 分布式系统研发

统计信息

  • 总下载量: 6
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 0
  • 点击次数: 35
  • 依赖项目数: 0
  • 推荐数: 0

GitHub 信息

  • Stars: 0
  • Watchers: 0
  • Forks: 0
  • 开发语言: PHP

其他信息

  • 授权协议: MIT
  • 更新时间: 2026-03-18