PHPackages                             cattyneo/laravel-genai - 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. [API Development](/categories/api)
4. /
5. cattyneo/laravel-genai

ActiveLibrary[API Development](/categories/api)

cattyneo/laravel-genai
======================

A comprehensive Laravel package for integrating multiple AI providers (OpenAI, Gemini, Claude, Grok) with unified API

v1.0.0(11mo ago)02MITPHPPHP ^8.2CI passing

Since Jun 13Pushed 11mo agoCompare

[ Source](https://github.com/cattyneo/genai-laravel)[ Packagist](https://packagist.org/packages/cattyneo/laravel-genai)[ RSS](/packages/cattyneo-laravel-genai/feed)WikiDiscussions main Synced 1mo ago

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

Laravel GenAI
=============

[](#laravel-genai)

[![PHP Version](https://camo.githubusercontent.com/c9f64f714c636ba27a3bba6dfd52f98426832db1262747efa54b212d16943651/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f7068702d253545382e322d626c7565)](https://camo.githubusercontent.com/c9f64f714c636ba27a3bba6dfd52f98426832db1262747efa54b212d16943651/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f7068702d253545382e322d626c7565)[![Laravel Version](https://camo.githubusercontent.com/fbcc00bb6481a4fd959f225b19c62a0af617cb5b95918a44a66e8b66f424043e/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f6c61726176656c2d25354531312e3025374325354531322e302d726564)](https://camo.githubusercontent.com/fbcc00bb6481a4fd959f225b19c62a0af617cb5b95918a44a66e8b66f424043e/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f6c61726176656c2d25354531312e3025374325354531322e302d726564)[![License](https://camo.githubusercontent.com/f8df3091bbe1149f398a5369b2c39e896766f9f6efba3477c63e9b4aa940ef14/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f6c6963656e73652d4d49542d677265656e)](https://camo.githubusercontent.com/f8df3091bbe1149f398a5369b2c39e896766f9f6efba3477c63e9b4aa940ef14/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f6c6963656e73652d4d49542d677265656e)

A comprehensive Laravel package for integrating multiple AI providers (OpenAI, Gemini, Claude, Grok) with unified API, advanced caching, cost tracking, and detailed analytics.

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

[](#-features)

### **Core Features**

[](#core-features)

- **🤖 Multiple AI Providers**: OpenAI, Google Gemini, Anthropic Claude, xAI Grok
- **🔄 Unified API**: Single interface for all providers with fluent chain syntax
- **📊 Cost Tracking**: Detailed cost analysis, budget management, and alerts
- **⚡ Advanced Caching**: Redis-based caching with TTL, tagging, and hit/miss tracking
- **📈 Analytics**: Comprehensive request logging and usage statistics
- **🎯 Preset Management**: Reusable prompt presets with variable substitution
- **⚙️ Rate Limiting**: Provider and model-specific rate limits with distributed control

### **Advanced Services**

[](#advanced-services)

- **🔔 NotificationService**: Multi-channel alerts (Email, Slack, Discord, Teams)
- **📈 PerformanceMonitoringService**: Real-time monitoring with P95/P99 tracking
- **💰 CostOptimizationService**: Intelligent optimization recommendations
- **🔄 PresetAutoUpdateService**: Automated preset optimization with versioning

### **Development Tools**

[](#development-tools)

- **🔧 Artisan Commands**: 11 commands for installation, testing, model management
- **🧪 Testing Tools**: Built-in mocking, assertions, and verification commands
- **📥 Assistant Import**: OpenAI Assistant import to GenAI format
- **🌐 REST API**: 7 controllers with comprehensive endpoints
- **📋 Model Management**: YAML-based configuration with API fetching

📋 Requirements
--------------

[](#-requirements)

- PHP 8.2 or higher
- Laravel 11.0+ or 12.0+
- Redis (recommended for caching)

📦 Installation
--------------

[](#-installation)

Install the package via Composer:

```
composer require cattyneo/laravel-genai
```

Run the installation command:

```
php artisan genai:install
```

This will:

- Publish configuration files
- Run database migrations
- Create necessary directories
- Display setup instructions

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

[](#️-configuration)

### Environment Variables

[](#environment-variables)

Add these to your `.env` file:

```
# GenAI Configuration
GENAI_DEFAULT_PROVIDER=openai
GENAI_DEFAULT_MODEL=gpt-4.1-mini
GENAI_CACHE_ENABLED=true
GENAI_CACHE_DRIVER=redis

# API Keys
OPENAI_API_KEY=sk-...
GEMINI_API_KEY=...
CLAUDE_API_KEY=sk-ant-...
GROK_API_KEY=xai-...

# Optional: Custom API endpoints
OPENAI_MODELS_ENDPOINT=https://api.openai.com/v1/models
GEMINI_MODELS_ENDPOINT=https://generativelanguage.googleapis.com/v1beta/models
CLAUDE_MODELS_ENDPOINT=https://api.anthropic.com/v1/models
GROK_MODELS_ENDPOINT=https://api.x.ai/v1/models
```

### Configuration File

[](#configuration-file)

The main configuration is in `config/genai.php`. The comprehensive 279-line configuration includes:

#### **Core Settings**

[](#core-settings)

- **defaults**: Default provider, model, timeout, async options, and request parameters
- **providers**: API endpoints, authentication, headers for OpenAI, Gemini, Claude, Grok
- **cache**: Redis/file caching with TTL, prefix, and tagging support
- **paths**: Configurable paths for presets and prompts storage

#### **Advanced Features**

[](#advanced-features)

- **pricing**: Currency settings, exchange rates, decimal precision for cost tracking
- **retry**: Retry attempts, exponential backoff, exception handling
- **logging**: Request/response logging, database optimization, batch processing
- **analytics**: History retention, cleanup policies, detailed analytics toggles

#### **Monitoring &amp; Automation**

[](#monitoring--automation)

- **scheduled\_tasks**: Automated model updates, deprecation checks with configurable frequency
- **notifications**: Multi-channel alerts (Email, Slack, Discord, Teams) with custom thresholds
- **preset\_auto\_update**: Automatic preset optimization with confidence thresholds and backup retention
- **rate\_limits**: Provider-specific and model-specific rate limiting

#### **Advanced Services**

[](#advanced-services-1)

- **advanced\_services**: Configuration for NotificationService, PerformanceMonitoringService, CostOptimizationService, and PresetAutoUpdateService

**Example core configuration:**

```
'defaults' => [
    'timeout' => 30,
    'async' => true,
    'provider' => 'openai',
    'model' => 'gpt-4.1-mini',
    'options' => [
        'temperature' => 0.7,
        'max_tokens' => 2000,
        // ... additional options
    ],
],

'cache' => [
    'enabled' => true,
    'driver' => 'redis',
    'ttl' => 3600,
    'prefix' => 'genai_cache',
    'tags' => ['genai'],
],

'notifications' => [
    'deprecation_channels' => ['log', 'mail'],
    'cost_alert_channels' => ['log', 'mail'],
    'cost_thresholds' => [
        'warning' => 10000,  // ¥10,000
        'critical' => 50000, // ¥50,000
    ],
],
```

🚀 Quick Start
-------------

[](#-quick-start)

### Basic Usage

[](#basic-usage)

```
use CattyNeo\LaravelGenAI\Facades\GenAI;

// Simple question
$response = GenAI::ask('Hello, how are you?');

// With specific provider and model
$response = GenAI::provider('openai')
    ->model('gpt-4o')
    ->ask('Explain Laravel in simple terms');

// Using presets
$response = GenAI::preset('blog')
    ->prompt('Write about AI and Laravel')
    ->request();
```

### Advanced Usage

[](#advanced-usage)

```
// With custom options
$response = GenAI::provider('claude')
    ->model('claude-3-opus')
    ->options([
        'temperature' => 0.7,
        'max_tokens' => 1000,
    ])
    ->ask('Create a detailed project plan');

// With streaming
$response = GenAI::provider('openai')
    ->options(['stream' => true])
    ->ask('Generate a long story')
    ->stream();

// Async requests
$response = GenAI::preset('analysis')
    ->options(['async' => true])
    ->prompt('Analyze this data: ' . $data)
    ->request();
```

📋 Preset Management
-------------------

[](#-preset-management)

Create reusable prompt presets:

```
---
title: Blog Generator
variables: [topic, tone]
model: gpt-4o
temperature: 0.8
---
Write a blog post about {{topic}} with a {{tone}} tone.
Include an introduction, main content, and conclusion.
```

Use presets in your code:

```
$response = GenAI::preset('blog')
    ->vars(['topic' => 'AI Ethics', 'tone' => 'professional'])
    ->request();
```

🔧 Artisan Commands
------------------

[](#-artisan-commands)

### Installation and Setup

[](#installation-and-setup)

```
# Install the package
php artisan genai:install

# Install with options
php artisan genai:install --force --skip-migration
```

### Testing and Verification

[](#testing-and-verification)

```
# Test all providers
php artisan genai:test

# Test specific provider
php artisan genai:test --provider=openai

# Test with custom prompt
php artisan genai:test --prompt="Hello, world!" --provider=claude
```

### Statistics and Analytics

[](#statistics-and-analytics)

```
# Show usage statistics
php artisan genai:stats

# Statistics for specific period
php artisan genai:stats --days=30

# Detailed breakdown
php artisan genai:stats --detailed --provider=openai
```

### Model Management

[](#model-management)

```
# List available models from YAML and/or API
php artisan genai:model-list
php artisan genai:model-list --source=api --provider=openai
php artisan genai:model-list --format=json --details

# Add new model to YAML configuration
php artisan genai:model-add openai gpt-5 \
  --features=vision --features=reasoning \
  --max-tokens=32000 \
  --pricing-input=2.50 \
  --pricing-output=10.00

# Update model information from APIs
php artisan genai:model-update
php artisan genai:model-update --provider=openai --force

# Validate YAML configuration
php artisan genai:model-validate --verbose --fix

# Generate preset templates
php artisan genai:preset-generate "creative-writer" \
  --template=creative \
  --provider=openai \
  --model=gpt-4.1
```

### Advanced Analytics

[](#advanced-analytics)

```
# Advanced analytics with custom metrics
php artisan genai:analytics --period=weekly
php artisan genai:analytics --export=csv --provider=openai
php artisan genai:analytics --cost-analysis --threshold=1000

# Scheduled updates and automation
php artisan genai:scheduled-update --dry-run
php artisan genai:scheduled-update --force --backup
```

### OpenAI Assistant Import

[](#openai-assistant-import)

Import OpenAI Assistants from your account:

```
# List available assistants
php artisan genai:assistant-import --list

# Import specific assistant
php artisan genai:assistant-import --id=asst_xxxxx

# Import all assistants
php artisan genai:assistant-import --all

# Check import status
php artisan genai:assistant-import --status

# Cleanup imported files
php artisan genai:assistant-import --cleanup
```

📊 Advanced Services
-------------------

[](#-advanced-services)

The package includes four advanced services for production-ready monitoring and optimization:

### 🔔 NotificationService

[](#-notificationservice)

Multi-channel alert system for monitoring and notifications:

- **Email**: Cost alerts, performance warnings, deprecation notices
- **Slack**: Real-time notifications with formatted messages
- **Discord**: Community alerts and bot integration
- **Microsoft Teams**: Enterprise notifications with rich cards

```
use CattyNeo\LaravelGenAI\Services\GenAI\NotificationService;

$notificationService = app(NotificationService::class);

// Send cost alert
$notificationService->sendCostAlert([
    'current_cost' => 150.0,
    'budget' => 100.0,
    'period' => 'daily'
]);

// Send performance alert
$notificationService->sendPerformanceAlert([
    'metric' => 'response_time',
    'current_value' => 5500,
    'threshold' => 5000,
    'degradation_percent' => 10.0
]);
```

### 📈 PerformanceMonitoringService

[](#-performancemonitoringservice)

Real-time performance monitoring and metrics collection:

- Response time tracking (P95, P99 percentiles)
- Throughput analysis (RPS)
- Error rate monitoring
- Token usage analysis

### 💰 CostOptimizationService

[](#-costoptimizationservice)

Intelligent cost analysis and optimization recommendations:

- Model cost comparison
- Usage pattern analysis
- Budget management
- Optimization suggestions

### 🔄 PresetAutoUpdateService

[](#-presetautoupdateservice)

Automated preset management with versioning:

- Automatic preset optimization
- Backup and restore capabilities
- Version control
- Confidence-based updates

🌐 REST API Endpoints
--------------------

[](#-rest-api-endpoints)

The package provides comprehensive REST API for integration:

### **Cost Analysis API**

[](#cost-analysis-api)

```
GET /api/genai/cost/reports/monthly/{month?}  - Monthly cost report
GET /api/genai/cost/reports/weekly/{week?}    - Weekly cost report
GET /api/genai/cost/summary                   - Cost summary
GET /api/genai/cost/optimization-opportunities - Optimization opportunities
GET /api/genai/cost/budget-status             - Budget usage status

```

### **Performance Monitoring API**

[](#performance-monitoring-api)

```
GET /api/genai/performance/metrics/realtime   - Real-time metrics
GET /api/genai/performance/trends             - Performance trends
GET /api/genai/performance/history/{days?}    - Performance history
GET /api/genai/performance/alerts             - Performance alerts
GET /api/genai/performance/comparison         - Performance comparison
PUT /api/genai/performance/settings           - Update settings

```

### **Notification Management API**

[](#notification-management-api)

```
GET /api/genai/notifications/history          - Notification history
GET /api/genai/notifications/alerts/active    - Active alerts
PUT /api/genai/notifications/alerts/{alert}/acknowledge - Acknowledge alert
GET /api/genai/notifications/settings         - Notification settings
PUT /api/genai/notifications/settings         - Update settings
POST /api/genai/notifications/test            - Test notification

```

### **Model Recommendations API**

[](#model-recommendations-api)

```
GET /api/genai/recommendations                - General recommendations
GET /api/genai/recommendations/deprecated     - Deprecated model alternatives
POST /api/genai/recommendations/compare       - Model comparison
GET /api/genai/recommendations/optimization   - Optimization recommendations

```

📊 Analytics and Monitoring
--------------------------

[](#-analytics-and-monitoring)

The package provides comprehensive analytics:

### Cost Tracking

[](#cost-tracking)

- Per-request cost calculation
- Provider-specific pricing
- Daily/monthly cost breakdowns
- Budget alerts and limits

### Usage Statistics

[](#usage-statistics)

- Request counts and success rates
- Response time analysis
- Token usage tracking
- Error monitoring

### Database Tables

[](#database-tables)

- `genai_requests`: Individual request logs
- `genai_stats`: Daily aggregated statistics

🔄 Caching
---------

[](#-caching)

Intelligent caching with multiple strategies:

```
// Cache configuration
'cache' => [
    'enabled' => true,
    'driver' => 'redis',
    'ttl' => 3600,
    'prefix' => 'genai:',
]
```

Cache keys are generated based on:

- Prompt content
- Model and provider
- Options and parameters

⚡ Rate Limiting
---------------

[](#-rate-limiting)

Configure rate limits per provider:

```
'rate_limits' => [
    'default' => ['requests' => 100, 'per' => 'minute'],
    'openai' => ['requests' => 60, 'per' => 'minute'],
    'claude' => ['requests' => 40, 'per' => 'minute'],
]
```

🧪 Testing
---------

[](#-testing)

The package includes comprehensive testing tools:

```
// In your tests
GenAI::fake([
    'ask' => 'Mocked response',
    'request' => 'Another mock',
]);

// Assert requests
GenAI::assertRequested('ask', 'Hello');
```

🔒 Security
----------

[](#-security)

- API keys are never logged
- Request sanitization
- Rate limiting protection
- Input validation

📄 License
---------

[](#-license)

This package is open-sourced software licensed under the [MIT license](LICENSE).

🆘 Support
---------

[](#-support)

- **Documentation**: [Full documentation](https://github.com/cattyneo/laravel-genai/wiki)
- **Issues**: [GitHub Issues](https://github.com/cattyneo/laravel-genai/issues)
- **Discussions**: [GitHub Discussions](https://github.com/cattyneo/laravel-genai/discussions)

🙏 Credits
---------

[](#-credits)

- Built with ❤️ by [CattyNeo](https://github.com/cattyneo)
- Inspired by the Laravel community
- Thanks to all contributors

###  Health Score

29

—

LowBetter than 60% of packages

Maintenance52

Moderate activity, may be stable

Popularity2

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity49

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

Unknown

Total

1

Last Release

333d ago

### Community

Maintainers

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

---

Top Contributors

[![cattyneo](https://avatars.githubusercontent.com/u/21125215?v=4)](https://github.com/cattyneo "cattyneo (25 commits)")

---

Tags

laravelaiopenaiGeminiclaudellmChatGptgenaigrok

###  Code Quality

TestsPHPUnit

Code StyleLaravel Pint

### Embed Badge

![Health badge](/badges/cattyneo-laravel-genai/health.svg)

```
[![Health](https://phpackages.com/badges/cattyneo-laravel-genai/health.svg)](https://phpackages.com/packages/cattyneo-laravel-genai)
```

###  Alternatives

[cognesy/instructor-php

The complete AI toolkit for PHP: unified LLM API, structured outputs, agents, and coding agent control

310107.9k1](/packages/cognesy-instructor-php)[vizra/vizra-adk

Vizra Agent Development Kit - A comprehensive Laravel package for building intelligent AI agents.

29026.1k](/packages/vizra-vizra-adk)[sbsaga/toon

🧠 TOON for Laravel — a compact, human-readable, and token-efficient data format for AI prompts &amp; LLM contexts. Perfect for ChatGPT, Gemini, Claude, Mistral, and OpenAI integrations (JSON ⇄ TOON).

6115.6k](/packages/sbsaga-toon)[claude-php/claude-php-sdk-laravel

Laravel integration for the Claude PHP SDK - Anthropic Claude API

5010.8k](/packages/claude-php-claude-php-sdk-laravel)[vectorifyai/vectorify-laravel

Vectorify package for Laravel. The fastest way to ask AI about your data.

206.1k](/packages/vectorifyai-vectorify-laravel)

PHPackages © 2026

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