PHPackages                             israrminhas/filament-aimonitor - 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. israrminhas/filament-aimonitor

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

israrminhas/filament-aimonitor
==============================

AI API cost monitoring and key management plugin for Filament

9988↓25%6PHP

Since Dec 5Pushed 5mo ago1 watchersCompare

[ Source](https://github.com/Israrminhas1/filament-aimonitor)[ Packagist](https://packagist.org/packages/israrminhas/filament-aimonitor)[ RSS](/packages/israrminhas-filament-aimonitor/feed)WikiDiscussions main Synced 1mo ago

READMEChangelogDependenciesVersions (1)Used By (0)

Filament AI Monitor
===================

[](#filament-ai-monitor)

A Filament 4 plugin for monitoring AI API usage, costs, and managing API keys across multiple providers (OpenAI, Anthropic, Gemini, Perplexity).

Features
--------

[](#features)

- Track AI API requests with token counts and automatic cost calculation
- Manage API keys for multiple providers with priority-based rotation
- Configure model-specific pricing with fallback support
- Dashboard with usage analytics and cost trends
- Per-user spending tracking and limits
- Multi-tenancy support (works with `tenant()` helper)

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

[](#requirements)

- PHP 8.2+
- Laravel 11+
- Filament 4.0+

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

[](#installation)

```
composer require israrminhas/filament-aimonitor
```

Publish and run migrations:

```
php artisan vendor:publish --tag="ai-monitor-migrations"
php artisan migrate
```

Publish config (optional):

```
php artisan vendor:publish --tag="ai-monitor-config"
```

Register the Plugin
-------------------

[](#register-the-plugin)

Add the plugin to your Filament panel in `app/Providers/Filament/AdminPanelProvider.php`:

```
use Filament\AiMonitor\AiMonitorPlugin;

public function panel(Panel $panel): Panel
{
    return $panel
        ->plugins([
            AiMonitorPlugin::make(),
        ]);
}
```

---

Helper Functions
----------------

[](#helper-functions)

The package provides three global helper functions:

### `ai_log()` - Log AI Requests

[](#ai_log---log-ai-requests)

```
// Log any AI request
ai_log([
    'provider' => 'openai',
    'model' => 'gpt-4o',
    'request_type' => 'chat',
    'prompt_tokens' => 150,
    'completion_tokens' => 50,
    'status' => 'success',
    'user_id' => auth()->id(),
]);
```

Cost is **automatically calculated** from your pricing configuration. The `total_tokens` and `occurred_at` are auto-filled if not provided.

### `ai_key()` - Get API Key

[](#ai_key---get-api-key)

```
// Get the highest priority active API key for a provider
$apiKey = ai_key('openai');
$apiKey = ai_key('anthropic');
$apiKey = ai_key('gemini');
```

### `ai_cost()` - Calculate Cost

[](#ai_cost---calculate-cost)

```
// Calculate cost for tokens without logging
$cost = ai_cost('openai', 'gpt-4o', 1000, 500);
// Returns cost in USD based on your pricing config
```

---

Using the Services
------------------

[](#using-the-services)

### AiUsageLogger

[](#aiusagelogger)

```
use Filament\AiMonitor\Services\AiUsageLogger;

$logger = app(AiUsageLogger::class);

// Generic log
$logger->log([
    'provider' => 'openai',
    'model' => 'gpt-4o',
    'prompt_tokens' => 100,
    'completion_tokens' => 50,
    'status' => 'success',
    'user_id' => auth()->id(),
    'meta' => ['conversation_id' => 123],
]);

// Provider-specific shortcuts
$logger->logOpenAi([...]);
$logger->logAnthropic([...]);
$logger->logGemini([...]);
$logger->logPerplexity([...]);
```

### AiKeyManager

[](#aikeymanager)

```
use Filament\AiMonitor\Services\AiKeyManager;

$keyManager = app(AiKeyManager::class);

// Get single key (highest priority)
$key = $keyManager->getKey('openai');

// Get all active keys for a provider
$keys = $keyManager->getAllKeys('openai');

// Check if provider has any active keys
if ($keyManager->hasProvider('anthropic')) {
    // ...
}
```

### AiPricingService

[](#aipricingservice)

```
use Filament\AiMonitor\Services\AiPricingService;

$pricing = app(AiPricingService::class);

// Get pricing for a model
$rates = $pricing->getPricing('openai', 'gpt-4o');
// Returns: ['input_per_1k' => 0.005, 'output_per_1k' => 0.015]

// Check if pricing exists
if ($pricing->hasPricing('anthropic', 'claude-3-opus')) {
    // ...
}

// Calculate cost
$cost = $pricing->calculateCost('openai', 'gpt-4o', 1000, 500);

// Get all configured providers
$providers = $pricing->getProviders();

// Get models for a provider
$models = $pricing->getModelsForProvider('openai');
```

### AiUsageLimitService

[](#aiusagelimitservice)

```
use Filament\AiMonitor\Services\AiUsageLimitService;

$limitService = app(AiUsageLimitService::class);

// Get user's monthly spend
$spent = $limitService->getUserMonthlySpend($userId);

// Get full limit status
$status = $limitService->getUserLimitStatus($user);
// Returns:
// [
//     'limit' => 100.00,
//     'spent' => 45.50,
//     'remaining' => 54.50,
//     'percent_used' => 45.5,
//     'state' => 'ok', // 'ok', 'warning', 'over', 'no-limit'
// ]
```

---

Usage Examples
--------------

[](#usage-examples)

### OpenAI Integration

[](#openai-integration)

```
use OpenAI\Laravel\Facades\OpenAI;

$response = OpenAI::chat()->create([
    'model' => 'gpt-4o',
    'messages' => [
        ['role' => 'user', 'content' => 'Hello!'],
    ],
]);

// Log the request
ai_log([
    'provider' => 'openai',
    'model' => $response->model,
    'request_type' => 'chat',
    'prompt_tokens' => $response->usage->promptTokens,
    'completion_tokens' => $response->usage->completionTokens,
    'status' => 'success',
    'user_id' => auth()->id(),
]);
```

### Anthropic Integration

[](#anthropic-integration)

```
$response = Http::withHeaders([
    'x-api-key' => ai_key('anthropic'),
    'anthropic-version' => '2023-06-01',
])->post('https://api.anthropic.com/v1/messages', [
    'model' => 'claude-3-5-sonnet-20241022',
    'max_tokens' => 1024,
    'messages' => [['role' => 'user', 'content' => 'Hello!']],
]);

$data = $response->json();

ai_log([
    'provider' => 'anthropic',
    'model' => $data['model'],
    'request_type' => 'chat',
    'prompt_tokens' => $data['usage']['input_tokens'],
    'completion_tokens' => $data['usage']['output_tokens'],
    'status' => $response->successful() ? 'success' : 'failed',
    'user_id' => auth()->id(),
]);
```

### With Error Handling

[](#with-error-handling)

```
try {
    $response = OpenAI::chat()->create([...]);

    ai_log([
        'provider' => 'openai',
        'model' => 'gpt-4o',
        'prompt_tokens' => $response->usage->promptTokens,
        'completion_tokens' => $response->usage->completionTokens,
        'status' => 'success',
        'user_id' => auth()->id(),
    ]);
} catch (\Exception $e) {
    ai_log([
        'provider' => 'openai',
        'model' => 'gpt-4o',
        'prompt_tokens' => 0,
        'completion_tokens' => 0,
        'status' => 'failed',
        'user_id' => auth()->id(),
        'meta' => ['error' => $e->getMessage()],
    ]);
}
```

---

User Spending Limits
--------------------

[](#user-spending-limits)

### Add Columns to Users Table

[](#add-columns-to-users-table)

```
php artisan make:migration add_ai_limits_to_users_table
```

```
Schema::table('users', function (Blueprint $table) {
    $table->decimal('ai_monthly_limit_usd', 10, 4)->nullable();
    $table->integer('ai_alert_threshold_percent')->default(80);
});
```

### Check Limits Before AI Calls

[](#check-limits-before-ai-calls)

```
use Filament\AiMonitor\Services\AiUsageLimitService;

$limitService = app(AiUsageLimitService::class);
$status = $limitService->getUserLimitStatus(auth()->user());

if ($status['state'] === 'over') {
    throw new \Exception('Monthly AI spending limit reached.');
}

if ($status['state'] === 'warning') {
    // Notify user they're approaching limit
}
```

---

Multi-Tenancy Support
---------------------

[](#multi-tenancy-support)

The package automatically scopes data to the current tenant when `tenant()` helper is available (e.g., with Filament multi-tenancy or Stancl/Tenancy).

### Configuration

[](#configuration)

```
// config/ai-monitor.php
return [
    'tenant_support' => true, // Enable/disable tenant scoping
];
```

### How It Works

[](#how-it-works)

- All models use the `IsTenantScoped` trait
- When `tenant()` returns a tenant, `tenant_id` is automatically set on create
- Queries are automatically scoped to the current tenant

---

Dashboard Widgets
-----------------

[](#dashboard-widgets)

The plugin includes these dashboard widgets:

WidgetDescriptionStats OverviewTotal requests, tokens, cost, success rateCost &amp; Request Trends30-day line chartCost by ProviderDoughnut chart breakdownTop Models by CostTable of most expensive modelsUsage by UserTable of user spendingRecent RequestsLatest API calls with details---

License
-------

[](#license)

MIT License. See [LICENSE](LICENSE) for details.

###  Health Score

26

—

LowBetter than 43% of packages

Maintenance49

Moderate activity, may be stable

Popularity28

Limited adoption so far

Community10

Small or concentrated contributor base

Maturity13

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.

### Community

Maintainers

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

---

Top Contributors

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

### Embed Badge

![Health badge](/badges/israrminhas-filament-aimonitor/health.svg)

```
[![Health](https://phpackages.com/badges/israrminhas-filament-aimonitor/health.svg)](https://phpackages.com/packages/israrminhas-filament-aimonitor)
```

###  Alternatives

[litecms/page

Page package for litecms.

1851.8k1](/packages/litecms-page)

PHPackages © 2026

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