### Install Filament AI Monitor Source: https://github.com/israrminhas1/filament-aimonitor/blob/main/README.md Installs the Filament AI Monitor package using Composer and publishes necessary migrations and configuration files. ```bash composer require israrminhas/filament-aimonitor php artisan vendor:publish --tag="ai-monitor-migrations" php artisan migrate php artisan vendor:publish --tag="ai-monitor-config" ``` -------------------------------- ### Log OpenAI API Request and Usage Source: https://github.com/israrminhas1/filament-aimonitor/blob/main/README.md An example demonstrating how to integrate with the OpenAI SDK, make a chat completion request, and then log the usage details using the `ai_log` helper function. ```php 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(), ]); ``` -------------------------------- ### Multi-Tenancy Setup for AI Monitoring Data Source: https://context7.com/israrminhas1/filament-aimonitor/llms.txt Enable automatic tenant scoping for AI monitoring data. This configuration supports Filament's built-in multi-tenancy and external packages like Stancl/Tenancy. Tenant ID is automatically inferred or can be manually overridden. ```php // config/ai-monitor.php return [ 'user_model' => App\Models\User::class, 'navigation_group' => 'AI Monitor', 'tenant_support' => true, // Enable tenant scoping ]; // Tenant scope is automatically applied when tenant() helper exists use Filament\AiMonitor\Services\AiUsageLogger; // In a multi-tenant context $logger = app(AiUsageLogger::class); $logger->log([ 'provider' => 'openai', 'model' => 'gpt-4o', 'prompt_tokens' => 100, 'completion_tokens' => 50, 'status' => 'success', 'user_id' => auth()->id(), // tenant_id is automatically set from tenant() helper ]); // Queries are automatically scoped to current tenant $requests = AiRequest::all(); // Only returns current tenant's requests // Manual tenant override (if needed) $logger->log([ 'provider' => 'openai', 'model' => 'gpt-4o', 'prompt_tokens' => 100, 'completion_tokens' => 50, 'status' => 'success', 'user_id' => auth()->id(), 'tenant_id' => $specificTenantId, // Override automatic scoping ]); ``` -------------------------------- ### Create Migration for User AI Spending Limits Source: https://github.com/israrminhas1/filament-aimonitor/blob/main/README.md This command generates a new migration file to add columns for managing user AI spending limits to the 'users' table. It will create columns for monthly limit in USD and an alert threshold percentage. This is a prerequisite for implementing spending controls. ```bash php artisan make:migration add_ai_limits_to_users_table ``` -------------------------------- ### Access Pricing Information with `AiPricingService` Source: https://github.com/israrminhas1/filament-aimonitor/blob/main/README.md The `AiPricingService` allows retrieval of pricing details for AI models, checking pricing existence, calculating costs, and listing available providers and their models. ```php 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'); ``` -------------------------------- ### Manage AI Model Pricing with AiPricingService Source: https://context7.com/israrminhas1/filament-aimonitor/llms.txt The AiPricingService handles AI model pricing configurations. It supports fallback mechanisms for pricing, allows for automatic cost calculation based on token usage, and can discover available providers and models. Dependencies include the service container for instantiation. It takes provider and model identifiers as input and returns pricing details or null if not found. ```php use Filament\AiMonitor\Services\AiPricingService; $pricing = app(AiPricingService::class); // Get pricing for specific 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')) { $cost = $pricing->calculateCost('anthropic', 'claude-3-opus', 1000, 500); echo "Cost: ${$cost}"; } // Check if any pricing configured (for setup alerts) if (!$pricing->hasAnyPricing()) { Log::warning('No pricing configured in AI Monitor'); } // Calculate cost with pricing fallback // 1. Tries exact model match // 2. Falls back to provider default // 3. Falls back to global fallback $cost = $pricing->calculateCost('openai', 'gpt-4o', 1000, 500); // Returns null if no pricing found at any level // Get all configured providers $providers = $pricing->getProviders(); // Returns: ['openai', 'anthropic', 'gemini', 'perplexity'] // Get models for a provider $models = $pricing->getModelsForProvider('openai'); // Returns: ['gpt-4o', 'gpt-4-turbo', 'gpt-3.5-turbo'] // Build dynamic provider selector $providers = $pricing->getProviders(); foreach ($providers as $provider) { echo "Provider: {$provider}\n"; $models = $pricing->getModelsForProvider($provider); foreach ($models as $model) { echo " - {$model}\n"; $rates = $pricing->getPricing($provider, $model); echo " Input: ${$rates['input_per_1k']}/1k tokens\n"; echo " Output: ${$rates['output_per_1k']}/1k tokens\n"; } } ``` -------------------------------- ### Configure Filament AI Monitor Plugin Source: https://context7.com/israrminhas1/filament-aimonitor/llms.txt Registers the AiMonitorPlugin with the Filament admin panel. This involves adding the plugin to the panel's configuration in the `AdminPanelProvider.php` file and setting up general configurations in `config/ai-monitor.php`. ```php // app/Providers/Filament/AdminPanelProvider.php use FilamentAiMonitorAiMonitorPlugin; use FilamentPanel; public function panel(Panel $panel): Panel { return $panel ->id('admin') ->path('admin') ->plugins([ AiMonitorPlugin::make(), ]); } // Configure in config/ai-monitor.php return [ 'user_model' => App\Models\User::class, 'navigation_group' => 'AI Monitor', 'tenant_support' => true, ]; ``` -------------------------------- ### Configure Filament AI Monitor Plugin Source: https://context7.com/israrminhas1/filament-aimonitor/llms.txt Register and configure the AiMonitorPlugin within your Filament panel. Customize navigation grouping, resource visibility, and feature enablement. Supports conditional features based on user roles. ```php use Filament\AiMonitor\AiMonitorPlugin; use Filament\Panel; // Basic registration in AdminPanelProvider public function panel(Panel $panel): Panel { return $panel ->plugins([ AiMonitorPlugin::make(), ]); } // Advanced configuration public function panel(Panel $panel): Panel { return $panel ->plugins([ AiMonitorPlugin::make() ->navigationGroup('Analytics') ->requestsResource(true) ->pricingResource(true) ->apiKeysResource(true) ->dashboard(true), ]); } // Disable specific resources public function panel(Panel $panel): Panel { return $panel ->plugins([ AiMonitorPlugin::make() ->navigationGroup(null) // No grouping ->requestsResource(true) ->pricingResource(false) // Hide pricing management ->apiKeysResource(false) // Hide API key management ->dashboard(true), ]); } // Conditional features based on user role public function panel(Panel $panel): Panel { $isAdmin = auth()->user()?->hasRole('admin'); return $panel ->plugins([ AiMonitorPlugin::make() ->navigationGroup('AI Monitor') ->requestsResource(true) ->pricingResource($isAdmin) ->apiKeysResource($isAdmin) ->dashboard(true), ]); } ``` -------------------------------- ### Implement User Spending Limits for AI Source: https://context7.com/israrminhas1/filament-aimonitor/llms.txt Add spending limits and alert thresholds to users. This includes database migrations for new columns, setting limits programmatically, and checking limits before API calls to prevent overspending. ```php // Migration: add_ai_limits_to_users_table use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; return new class extends Migration { public function up() { Schema::table('users', function (Blueprint $table) { $table->decimal('ai_monthly_limit_usd', 10, 4)->nullable(); $table->integer('ai_alert_threshold_percent')->default(80); }); } public function down() { Schema::table('users', function (Blueprint $table) { $table->dropColumn(['ai_monthly_limit_usd', 'ai_alert_threshold_percent']); }); } }; // Set user limits $user = User::find(1); $user->ai_monthly_limit_usd = 100.00; // $100/month limit $user->ai_alert_threshold_percent = 85; // Alert at 85% usage $user->save(); // Check before API calls use Filament\AiMonitor\Services\AiUsageLimitService; $limitService = app(AiUsageLimitService::class); $status = $limitService->getUserLimitStatus(auth()->user()); if ($status['state'] === 'over') { return response()->json([ 'error' => 'Monthly AI spending limit reached', 'spent' => $status['spent'], 'limit' => $status['limit'], ], 429); } if ($status['state'] === 'warning') { // Send warning notification auth()->user()->notify(new AiLimitWarning($status)); } // Proceed with API call $response = OpenAI::chat()->create([...]); ai_log([...]); ``` -------------------------------- ### Calculate AI Cost with `ai_cost()` Helper Source: https://github.com/israrminhas1/filament-aimonitor/blob/main/README.md Calculates the cost for a given AI request based on provider, model, prompt tokens, and completion tokens, returning the cost in USD according to the pricing configuration. ```php // Calculate cost for tokens without logging $cost = ai_cost('openai', 'gpt-4o', 1000, 500); // Returns cost in USD based on your pricing config ``` -------------------------------- ### Manage Usage Limits with `AiUsageLimitService` Source: https://github.com/israrminhas1/filament-aimonitor/blob/main/README.md The `AiUsageLimitService` helps manage and track AI usage limits for users. It can retrieve a user's monthly spend, and the full status of their limit, including remaining quota and usage percentage. ```php 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' // ] ``` -------------------------------- ### Retrieve API Key with `ai_key()` Helper Source: https://github.com/israrminhas1/filament-aimonitor/blob/main/README.md Retrieves the highest priority active API key for a specified AI provider (e.g., 'openai', 'anthropic', 'gemini'). ```php // Get the highest priority active API key for a provider $apiKey = ai_key('openai'); $apiKey = ai_key('anthropic'); $apiKey = ai_key('gemini'); ``` -------------------------------- ### Register Filament AI Monitor Plugin Source: https://github.com/israrminhas1/filament-aimonitor/blob/main/README.md Registers the AiMonitorPlugin with your Filament panel by adding it to the `plugins` array in `AdminPanelProvider.php`. ```php use Filament\AiMonitor\AiMonitorPlugin; public function panel(Panel $panel): Panel { return $panel ->plugins([ AiMonitorPlugin::make(), ]); } ``` -------------------------------- ### Track User Spending Limits with AiUsageLimitService Source: https://context7.com/israrminhas1/filament-aimonitor/llms.txt The AiUsageLimitService tracks user spending against configurable AI usage limits. It calculates monthly spend, checks limit status, and provides alerts. This service requires user authentication and a configured limit. Inputs include user identifiers and optional dates, with outputs detailing spend, limits, and status states like 'ok', 'warning', or 'over'. ```php use Filament\AiMonitor\Services\AiUsageLimitService; $limitService = app(AiUsageLimitService::class); // Get user's current month spend $spent = $limitService->getUserMonthlySpend(auth()->id()); echo "You've spent ${$spent} this month"; // Get spend for specific month $lastMonth = now()->subMonth(); $lastMonthSpend = $limitService->getUserMonthlySpend(auth()->id(), $lastMonth); // Get full limit status $user = auth()->user(); $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' // ] // Pre-flight limit check $status = $limitService->getUserLimitStatus(auth()->user()); if ($status['state'] === 'over') { return response()->json([ 'error' => 'Monthly AI spending limit reached', 'limit' => $status['limit'], 'spent' => $status['spent'], ], 429); } if ($status['state'] === 'warning') { Log::info("User {$user->id} at {$status['percent_used']}% of limit"); // Send notification to user } // Display to user echo "AI Usage This Month:\n"; echo "Spent: ${$status['spent']}\n"; if ($status['limit']) { echo "Limit: ${$status['limit']}\n"; echo "Remaining: ${$status['remaining']}\n"; echo "Usage: {$status['percent_used']}%\n"; } // Middleware implementation if ($status['state'] === 'over') { abort(429, 'Monthly AI spending limit exceeded'); } ``` -------------------------------- ### Log AI Requests with `ai_log()` Helper Source: https://github.com/israrminhas1/filament-aimonitor/blob/main/README.md Logs AI requests, including provider, model, token counts, and status. Cost is automatically calculated based on configuration. Supports optional `total_tokens` and `occurred_at`. ```php // 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(), ]); ``` -------------------------------- ### Configure Tenant Support for AI Monitor Source: https://github.com/israrminhas1/filament-aimonitor/blob/main/README.md This configuration snippet shows how to enable or disable tenant scoping for the AI Monitor package. Setting 'tenant_support' to true ensures that AI usage data is automatically scoped to the current tenant when multi-tenancy is active. This file is located at config/ai-monitor.php. ```php // config/ai-monitor.php return [ 'tenant_support' => true, // Enable/disable tenant scoping ]; ``` -------------------------------- ### Seed Pricing Data Source: https://context7.com/israrminhas1/filament-aimonitor/llms.txt Seeds the pricing data for AI models. This is an optional command to populate the system with initial pricing information. ```bash php artisan ai-monitor:seed-pricing ``` -------------------------------- ### Add Spending Limits to User Model Source: https://context7.com/israrminhas1/filament-aimonitor/llms.txt Extends the User model to include fields for managing AI spending limits and alert thresholds. This is optional and used for enforcing per-user budget controls. ```php // Add to User model (optional, for spending limits) use Illuminate\Database\Eloquent\Model; class User extends Model { protected $fillable = [ // ... existing fields 'ai_monthly_limit_usd', 'ai_alert_threshold_percent', ]; protected $casts = [ 'ai_monthly_limit_usd' => 'decimal:4', 'ai_alert_threshold_percent' => 'integer', ]; } ``` -------------------------------- ### Manage API Keys with `AiKeyManager` Service Source: https://github.com/israrminhas1/filament-aimonitor/blob/main/README.md The `AiKeyManager` service provides functionality to retrieve API keys. It can fetch the highest priority active key for a provider, all active keys, or check if a provider has any active keys. ```php 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')) { // ... } ``` -------------------------------- ### Define User AI Spending Limit Columns in Migration Source: https://github.com/israrminhas1/filament-aimonitor/blob/main/README.md This PHP code snippet defines the schema changes within a migration file. It adds two columns to the 'users' table: 'ai_monthly_limit_usd' for tracking the monthly spending limit and 'ai_alert_threshold_percent' for setting a notification threshold. ```php Schema::table('users', function (Blueprint $table) { $table->decimal('ai_monthly_limit_usd', 10, 4)->nullable(); $table->integer('ai_alert_threshold_percent')->default(80); }); ``` -------------------------------- ### Integrate Anthropic API Messages Source: https://github.com/israrminhas1/filament-aimonitor/blob/main/README.md This snippet demonstrates how to send messages to the Anthropic API using the 'Http' facade. It includes setting up headers for authentication and versioning, sending the POST request, and logging the response details. Assumes the availability of 'ai_key()' and 'ai_log()' helper functions. ```php $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(), ]); ``` -------------------------------- ### Check User AI Spending Limits Before API Calls Source: https://github.com/israrminhas1/filament-aimonitor/blob/main/README.md This PHP code demonstrates how to check a user's AI spending limit status before making an API call. It uses the 'AiUsageLimitService' to determine if the user has exceeded their limit or is approaching it, throwing an exception if the limit is reached. Requires dependency injection of 'AiUsageLimitService'. ```php use FilamentAiMonitorServicesAiUsageLimitService; $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 } ``` -------------------------------- ### Log AI Usage with `AiUsageLogger` Service Source: https://github.com/israrminhas1/filament-aimonitor/blob/main/README.md Uses the `AiUsageLogger` service for generic or provider-specific AI usage logging. Allows detailed logging including metadata and supports specific methods for OpenAI, Anthropic, Gemini, and Perplexity. ```php 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([...]); ``` -------------------------------- ### Handle OpenAI API Calls with Error Handling Source: https://github.com/israrminhas1/filament-aimonitor/blob/main/README.md This code block shows how to interact with the OpenAI API for chat completions and includes robust error handling using a try-catch block. It logs usage statistics upon success or logs the error message if an exception occurs. Requires the 'OpenAI' facade and 'ai_log()' helper function. ```php 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()], ]); } ``` -------------------------------- ### Log AI Requests with AiUsageLoggerService Source: https://context7.com/israrminhas1/filament-aimonitor/llms.txt The AiUsageLoggerService facilitates logging of AI requests, including automatic cost calculation and support for multiple providers via specific shortcuts. It can also handle tenant scoping. All logging methods return an AiRequest model instance. ```php log([ 'provider' => 'openai', 'model' => 'gpt-4o', 'request_type' => 'chat', 'prompt_tokens' => 100, 'completion_tokens' => 50, 'status' => 'success', 'user_id' => auth()->id(), 'meta' => ['conversation_id' => 123], ]); // Provider-specific shortcuts $logger->logOpenAi([ 'model' => 'gpt-4o', 'request_type' => 'chat', 'prompt_tokens' => 150, 'completion_tokens' => 75, 'status' => 'success', 'user_id' => auth()->id(), ]); $logger->logAnthropic([ 'model' => 'claude-3-5-sonnet-20241022', 'request_type' => 'chat', 'prompt_tokens' => 200, 'completion_tokens' => 100, 'status' => 'success', 'user_id' => auth()->id(), ]); $logger->logGemini([ 'model' => 'gemini-pro', 'request_type' => 'chat', 'prompt_tokens' => 180, 'completion_tokens' => 90, 'status' => 'success', 'user_id' => auth()->id(), ]); $logger->logPerplexity([ 'model' => 'pplx-7b-online', 'request_type' => 'chat', 'prompt_tokens' => 120, 'completion_tokens' => 60, 'status' => 'success', 'user_id' => auth()->id(), ]); // All methods return AiRequest model instance $request = $logger->log([...]); echo "Cost: ${$request->cost_usd}"; echo "Total tokens: {$request->total_tokens}"; ``` -------------------------------- ### Log AI API Requests with ai_log() - PHP Source: https://context7.com/israrminhas1/filament-aimonitor/llms.txt The `ai_log()` function records AI API requests, automatically calculating costs and tracking tokens. It supports various providers and includes error handling and metadata. Dependencies include the relevant AI SDKs (e.g., OpenAI) and Laravel's Http client for other providers. Inputs are an associative array containing request details. Outputs are logged records. ```php use OpenAI\Laravel\Facades\OpenAI; // Basic usage with OpenAI $response = OpenAI::chat()->create([ 'model' => 'gpt-4o', 'messages' => [ ['role' => 'user', 'content' => 'Explain quantum computing'] ], ]); 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(), ]); // With error handling and metadata try { $response = OpenAI::chat()->create([ 'model' => 'gpt-4o', 'messages' => [['role' => 'user', 'content' => 'Hello']], ]); ai_log([ 'provider' => 'openai', 'model' => 'gpt-4o', 'request_type' => 'chat', 'prompt_tokens' => $response->usage->promptTokens, 'completion_tokens' => $response->usage->completionTokens, 'status' => 'success', 'user_id' => auth()->id(), 'meta' => [ 'conversation_id' => $conversationId, 'temperature' => 0.7, ], ]); } catch (\Exception $e) { ai_log([ 'provider' => 'openai', 'model' => 'gpt-4o', 'request_type' => 'chat', 'prompt_tokens' => 0, 'completion_tokens' => 0, 'status' => 'failed', 'user_id' => auth()->id(), 'meta' => ['error' => $e->getMessage()], ]); throw $e; } // 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 Claude!']], ]); $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', 'http_code' => $response->status(), 'user_id' => auth()->id(), ]); ``` -------------------------------- ### Calculate API Costs with ai_cost() Source: https://context7.com/israrminhas1/filament-aimonitor/llms.txt The ai_cost() function calculates the estimated cost in USD for API requests based on the provider, model, and token usage. It's useful for pre-call budget checks and does not create log entries. Returns null if pricing is not configured for the specified provider or model. ```php 0.50) { return response()->json([ 'error' => 'Request too expensive', 'estimated_cost' => $estimatedCost, ], 400); } // Calculate for Anthropic Claude $cost = ai_cost('anthropic', 'claude-3-5-sonnet-20241022', 2000, 1000); // Returns null if pricing not configured if (ai_cost('gemini', 'gemini-pro', 1000, 500) === null) { Log::warning('Pricing not configured for Gemini'); } ``` -------------------------------- ### ai_log() - Log AI API Requests Source: https://context7.com/israrminhas1/filament-aimonitor/llms.txt Records AI API requests with automatic cost calculation, token tracking, and tenant scoping. This function is the primary interface for logging all AI interactions. ```APIDOC ## ai_log() - Log AI API Requests ### Description Records AI API requests with automatic cost calculation, token tracking, and tenant scoping. This helper function is the primary interface for logging all AI interactions across your application. ### Method Function call (PHP) ### Parameters #### Request Body (Array) - **provider** (string) - Required - The AI provider (e.g., 'openai', 'anthropic'). - **model** (string) - Required - The AI model used for the request. - **request_type** (string) - Required - The type of request (e.g., 'chat', 'completion'). - **prompt_tokens** (integer) - Required - The number of tokens used in the prompt. - **completion_tokens** (integer) - Required - The number of tokens generated in the completion. - **status** (string) - Required - The status of the request ('success' or 'failed'). - **http_code** (integer) - Optional - The HTTP status code of the response. - **user_id** (integer) - Optional - The ID of the user making the request. - **meta** (array) - Optional - Additional metadata about the request (e.g., conversation ID, error messages, temperature). ### Request Example ```php ai_log([ 'provider' => 'openai', 'model' => 'gpt-4o', 'request_type' => 'chat', 'prompt_tokens' => 100, 'completion_tokens' => 200, 'status' => 'success', 'user_id' => auth()->id(), 'meta' => [ 'conversation_id' => 'conv_123', 'temperature' => 0.7, ], ]); ``` ### Response This function does not return a value; it logs the AI request details. ``` -------------------------------- ### ai_key() - Retrieve API Keys Source: https://context7.com/israrminhas1/filament-aimonitor/llms.txt Retrieves the highest-priority active API key for a specified provider. This function facilitates automatic key rotation and failover strategies. ```APIDOC ## ai_key() - Retrieve API Keys ### Description Retrieves the highest-priority active API key for a specified provider, enabling automatic key rotation and failover strategies across multiple API keys. ### Method Function call (PHP) ### Parameters #### Path Parameters - **provider** (string) - Required - The name of the AI provider (e.g., 'openai', 'anthropic', 'gemini', 'perplexity'). ### Request Example ```php // Get OpenAI API key $openaiKey = ai_key('openai'); // Use with Anthropic SDK $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 Claude!']], ]); ``` ### Response #### Success Response - **api_key** (string) - The active API key for the specified provider. #### Response Example ```json "sk-****************************************" ``` #### Error Response - **api_key** (null) - Returns null if no active key exists for the provider. #### Response Example ```json null ``` ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.