PHPackages                             edfavieljr/laravel-ai-bridge - 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. edfavieljr/laravel-ai-bridge

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

edfavieljr/laravel-ai-bridge
============================

LaravelAIBridge provides a unified and fluid API to implement advanced AI capabilities in Laravel applications, including text generation, embedding, sentiment analysis, classification and image generation, all following Laravel conventions and style.

v2.0.0.x-dev(1mo ago)12[1 PRs](https://github.com/edfavieljr/laravel-ai-bridge/pulls)MITPHPPHP ^8.1

Since Mar 4Pushed 1mo ago1 watchersCompare

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

READMEChangelog (1)Dependencies (5)Versions (4)Used By (0)

Laravel AI Bridge
=================

[](#laravel-ai-bridge)

A powerful, elegant library for integrating multiple AI providers into Laravel applications through a unified API.

Introduction
------------

[](#introduction)

Laravel AI Bridge provides seamless integration with leading AI providers (OpenAI, Anthropic Claude, Google Gemini, and Hugging Face) through a consistent, Laravel-style interface. The library abstracts away the complexities of working with different AI APIs, allowing developers to focus on building features rather than managing API implementations.

Features
--------

[](#features)

- **Unified API** for multiple AI providers
- **Provider-specific facades** for direct access to specialized features
- **Intelligent caching** to reduce API costs
- **Automatic fallback** between providers for increased reliability
- **Laravel-style syntax** with facades, helpers, and fluent interfaces
- **Eloquent integration** with model traits for AI capabilities
- **Comprehensive logging** and error handling

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

[](#installation)

### Requirements

[](#requirements)

- PHP 8.1 or higher
- Laravel 9.0 or higher
- Composer

### Via Composer

[](#via-composer)

```
composer require edfavieljr/laravel-ai-bridge
```

### Publish Configuration

[](#publish-configuration)

After installing the package, publish the configuration file:

```
php artisan vendor:publish --provider="edfavieljr\LaravelAIBridge\AIBridgeServiceProvider" --tag="ai-config"
```

Quick Setup
-----------

[](#quick-setup)

The quickest way to get started is using the included setup command:

```
php artisan ai:setup
```

This interactive command will guide you through:

1. Selecting your preferred AI provider
2. Configuring your API keys
3. Setting default models
4. Updating your `.env` file automatically

Manual Configuration
--------------------

[](#manual-configuration)

### Environment Variables

[](#environment-variables)

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

```
# Default provider
AI_PROVIDER=openai

# OpenAI Configuration
OPENAI_API_KEY=your-openai-key
OPENAI_ORGANIZATION=your-organization-id  # Optional
OPENAI_DEFAULT_MODEL=gpt-4

# Anthropic Configuration
ANTHROPIC_API_KEY=your-anthropic-key
ANTHROPIC_DEFAULT_MODEL=claude-3-opus-20240229

# Google Gemini Configuration
GEMINI_API_KEY=your-gemini-key
GEMINI_PROJECT_ID=your-gcp-project-id  # Optional, for Vertex AI
GEMINI_DEFAULT_MODEL=gemini-1.5-pro

# Hugging Face Configuration
HUGGINGFACE_API_KEY=your-huggingface-key
HUGGINGFACE_DEFAULT_MODEL=gpt2

```

### Configuration Options

[](#configuration-options)

The `config/ai.php` file contains detailed settings for:

- Default provider
- Caching behavior
- Provider fallback options
- Rate limiting
- Logging
- Database storage for API calls
- Provider-specific configuration

Basic Usage
-----------

[](#basic-usage)

### Using the Main Facade

[](#using-the-main-facade)

```
use edfavieljr\LaravelAIBridge\Facades\AI;

// Generate text with default provider
$response = AI::generateText('Explain quantum computing in simple terms');

// Analyze sentiment
$sentiment = AI::analyzeSentiment('I absolutely love this product!');

// Generate embeddings for semantic search
$embeddings = AI::generateEmbeddings('Text to convert to vector representation');

// Classify text into categories
$classification = AI::classifyText(
    'The battery drains too quickly on this phone',
    ['hardware_issue', 'software_issue', 'battery_problem', 'user_experience']
);

// Extract entities
$entities = AI::extractEntities('Apple announced their new iPhone yesterday in California');
```

### Using Global Helper Functions

[](#using-global-helper-functions)

```
// Generate text
$explanation = ai('Explain how blockchain works in simple terms');

// Analyze sentiment
$sentiment = ai_sentiment('The customer service was terrible and I want a refund');

// Generate embeddings
$embeddings = ai_embed('Vector representation for semantic search');

// Classify text
$category = ai_classify(
    'The screen keeps freezing after the update',
    ['hardware_issue', 'software_bug', 'compatibility_problem', 'user_error']
);

// Extract entities
$entities = ai_entities('Microsoft CEO Satya Nadella announced a new partnership with OpenAI');
```

Working with Specific Providers
-------------------------------

[](#working-with-specific-providers)

### OpenAI

[](#openai)

```
use edfavieljr\LaravelAIBridge\Facades\OpenAI;

// Direct access via provider-specific facade
$completion = OpenAI::generateText('Write a poem about autumn');

// Generate an image
$imageUrl = OpenAI::generateImage('A futuristic city with flying cars');

// Using the main facade with provider specification
$completion = AI::provider('openai')
    ->model('gpt-4')
    ->generateText('Explain the theory of relativity');
```

### Anthropic (Claude)

[](#anthropic-claude)

```
use edfavieljr\LaravelAIBridge\Facades\Anthropic;

// Generate text with Claude
$completion = Anthropic::generateText('Write a summary of the last climate report');

// Using the main facade with provider specification
$completion = AI::provider('anthropic')
    ->model('claude-3-opus-20240229')
    ->generateText('Compare and contrast quantum computing and classical computing');
```

### Google Gemini

[](#google-gemini)

```
use edfavieljr\LaravelAIBridge\Facades\Gemini;

// Generate text with Gemini
$completion = Gemini::generateText('Create a tutorial for machine learning beginners');

// Using the main facade with provider specification
$completion = AI::provider('gemini')
    ->model('gemini-1.5-pro')
    ->generateText('Explain how neural networks work');
```

### Hugging Face

[](#hugging-face)

```
use edfavieljr\LaravelAIBridge\Facades\HuggingFace;

// Generate text with HuggingFace models
$completion = HuggingFace::model('gpt2')->generateText('Continue this story: Once upon a time');

// Generate embeddings with a specific model
$embeddings = HuggingFace::model('sentence-transformers/all-mpnet-base-v2')
    ->generateEmbeddings('Semantic search vector');
```

Integrating with Eloquent Models
--------------------------------

[](#integrating-with-eloquent-models)

Add AI capabilities directly to your models:

```
use Illuminate\Database\Eloquent\Model;
use edfavieljr\LaravelAIBridge\Traits\HasAICapabilities;

class Product extends Model
{
    use HasAICapabilities;

    // Your model implementation...
}
```

Then use the AI capabilities on your model instances:

```
$product = Product::find(1);

// Generate a marketing description
$marketingText = $product->completeText(
    'description',
    'Rewrite this product description to be more compelling: %s'
);

// Analyze customer review sentiment
$sentiment = $product->analyzeSentimentOf('customer_review');

// Categorize product based on description
$category = $product->classifyAttribute(
    'description',
    ['electronics', 'clothing', 'home', 'sports']
);

// Generate an image for the product
$imageUrl = $product->generateImageFrom('description');

// Summarize product description
$summary = $product->summarizeAttribute('description', 100);

// Translate product description
$translated = $product->translateAttribute('description', 'Spanish');
```

Advanced Features
-----------------

[](#advanced-features)

### Automatic Fallback Between Providers

[](#automatic-fallback-between-providers)

Configure fallback behavior in `config/ai.php`:

```
'fallback' => [
    'enabled' => true,
    'providers' => ['openai', 'anthropic', 'gemini', 'huggingface'],
],
```

With fallback enabled, if the primary provider fails, the library automatically tries the next provider:

```
// Will try OpenAI first, then fall back to other providers if it fails
$result = AI::provider('openai')->generateText('Explain quantum physics');
```

### Intelligent Caching

[](#intelligent-caching)

Configure caching in `config/ai.php`:

```
'cache' => [
    'enabled' => true,
    'ttl' => 60, // minutes
],
```

Identical requests will be cached to reduce API costs:

```
// First call hits the API
$result1 = AI::generateText('What is machine learning?');

// Second identical call uses cached result
$result2 = AI::generateText('What is machine learning?');
```

### Database Logging

[](#database-logging)

Enable database storage to track AI usage:

```
'storage' => [
    'enabled' => true,
    'purge_after_days' => 30,
],
```

Then publish and run the migration:

```
php artisan vendor:publish --provider="edfavieljr\LaravelAIBridge\AIBridgeServiceProvider" --tag="ai-migrations"
php artisan migrate
```

Query the logs:

```
use edfavieljr\LaravelAIBridge\Models\AICompletion;

// Get all completions
$completions = AICompletion::all();

// Get completions from a specific provider
$openaiCompletions = AICompletion::fromProvider('openai')->get();

// Get token usage summary
$usageSummary = AICompletion::getTokenUsageSummary();
```

Troubleshooting
---------------

[](#troubleshooting)

### Common Issues

[](#common-issues)

1. **API Key Authentication Failures**

    - Verify your API keys are correctly set in the `.env` file
    - Check for whitespace or special characters in your keys
2. **Rate Limiting**

    - Configure rate limiting settings in `config/ai.php`
    - Implement queue-based processing for high-volume applications
3. **Model Availability**

    - Ensure you have access to the selected models in your provider accounts
    - Some models require specific permissions or subscriptions

### Debugging

[](#debugging)

Enable detailed logging:

```
'logging' => [
    'enabled' => true,
    'channel' => 'ai-logs', // Create this channel in your config/logging.php
],
```

Contributing
------------

[](#contributing)

Contributions are welcome! Please see our [Contributing Guide](CONTRIBUTING.md) for details.

License
-------

[](#license)

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

###  Health Score

35

—

LowBetter than 79% of packages

Maintenance92

Actively maintained with recent releases

Popularity4

Limited adoption so far

Community7

Small or concentrated contributor base

Maturity34

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.

###  Release Activity

Cadence

Unknown

Total

1

Last Release

39d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/4918e99aa4476efe6764b1f54a696e250f3b4f03382554d1858ae82c7ce51b9c?d=identicon)[edfavieljr](/maintainers/edfavieljr)

---

Top Contributors

[![edfavieljr](https://avatars.githubusercontent.com/u/23642890?v=4)](https://github.com/edfavieljr "edfavieljr (5 commits)")

###  Code Quality

TestsPHPUnit

Static AnalysisPHPStan

Type Coverage Yes

### Embed Badge

![Health badge](/badges/edfavieljr-laravel-ai-bridge/health.svg)

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

###  Alternatives

[watson/active

Laravel helper for recognising the current route, controller and action

3253.6M14](/packages/watson-active)[spatie/laravel-pjax

A pjax middleware for Laravel 5

513371.8k11](/packages/spatie-laravel-pjax)[beyondcode/laravel-favicon

Create dynamic favicons based on your environment settings.

37345.5k](/packages/beyondcode-laravel-favicon)[glhd/conveyor-belt

14797.0k](/packages/glhd-conveyor-belt)[dragon-code/pretty-routes

Pretty Routes for Laravel

10058.7k4](/packages/dragon-code-pretty-routes)[erlandmuchasaj/laravel-gzip

Gzip your responses.

40129.3k2](/packages/erlandmuchasaj-laravel-gzip)

PHPackages © 2026

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