PHPackages                             devcbh/laravel-ai-provider - 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. devcbh/laravel-ai-provider

ActiveLibrary

devcbh/laravel-ai-provider
==========================

A Laravel AI wrapper package with multiple provider drivers.

3.2.2(1mo ago)6101MITPHP

Since Jan 23Pushed 1mo agoCompare

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

READMEChangelog (10)Dependencies (6)Versions (13)Used By (1)

Laravel AI Provider
===================

[](#laravel-ai-provider)

[![Latest Version on Packagist](https://camo.githubusercontent.com/248a613066a00319f367915266092aeb70fb1f83db03d52f16b01f0bcf3c7c59/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f6465766362682f6c61726176656c2d61692d70726f76696465722e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/devcbh/laravel-ai-provider)[![Total Downloads](https://camo.githubusercontent.com/10a55eee5678182b2a7afd970b3531f793bf330b0b33e3aa2fc6be6f093853da/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f6465766362682f6c61726176656c2d61692d70726f76696465722e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/devcbh/laravel-ai-provider)[![License](https://camo.githubusercontent.com/4130f488cd49b2b3db3021666c0d85ad879039b379443a7e2fac9cc512bce66d/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f6c2f6465766362682f6c61726176656c2d61692d70726f76696465722e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/devcbh/laravel-ai-provider)

A powerful, secure, and intuitive Laravel wrapper for multiple AI providers. Switch between OpenAI, Anthropic (Claude), Google (Gemini), Mistral, and Ollama with a single, fluent API.

---

🚀 Key Features
--------------

[](#-key-features)

- **Multi-Provider Support**: unified API for OpenAI, Gemini, Claude, Mistral, and Ollama.
- **Privacy First (PII Masking)**: Automatically detect and mask sensitive data before it leaves your server.
- **Zero Liability Design**: Built-in tools for reversible masking or irreversible redaction.
- **Fluent &amp; Expressive API**: Chain methods for configuration, role-setting, and driver switching.
- **Structured Output**: Enforce JSON schemas across all supported drivers.
- **Smart Failover**: Automatic provider fallback if your primary AI service is down.
- **Parallel Requests**: Handle multiple AI calls concurrently using Laravel's HTTP pool.
- **Prompt Templates**: Reusable templates for common tasks like Sentiment Analysis, Summarization, and more.
- **Streaming**: Real-time response streaming for chat interfaces.
- **Tool/Function Calling**: Easily bridge AI with your PHP logic.

---

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

[](#-installation)

Install the package via composer:

```
composer require devcbh/laravel-ai-provider
```

Publish the configuration file:

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

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

[](#️-configuration)

Add your API keys to your `.env` file:

```
# Default driver: openai, gemini, claude, mistral, ollama
LARAVEL_AURA_AI_DRIVER=openai

# Provider Keys
LARAVEL_AURA_OPENAI_API_KEY=your-api-key
LARAVEL_AURA_GEMINI_API_KEY=your-api-key
LARAVEL_AURA_CLAUDE_API_KEY=your-api-key
LARAVEL_AURA_MISTRAL_API_KEY=your-api-key
LARAVEL_AURA_OLLAMA_BASE_URL=http://localhost:11434
```

---

🛠 Usage
-------

[](#-usage)

### Simple Question

[](#simple-question)

```
use Devcbh\LaravelAiProvider\Facades\Ai;

$response = Ai::ask('What is the capital of France?');
// Output: "The capital of France is Paris."
```

### JSON Response

[](#json-response)

Get structured data as a PHP array:

```
$data = Ai::asJson('Return a list of 3 fruits in JSON format with "name" and "color" keys.');

// Returns: ['fruits' => [['name' => 'Apple', 'color' => 'Red'], ...]]
```

### Structured Output with Schema

[](#structured-output-with-schema)

Define a JSON schema to ensure the AI responds exactly how you expect.

```
$schema = [
    'type' => 'object',
    'properties' => [
        'name' => ['type' => 'string'],
        'age' => ['type' => 'integer'],
        'hobbies' => [
            'type' => 'array',
            'items' => ['type' => 'string']
        ]
    ],
    'required' => ['name', 'age', 'hobbies']
];

$data = Ai::schema($schema, 'person_info')
    ->asJson('Tell me about a person named John.');

// Returns: ['name' => 'John', 'age' => 30, 'hobbies' => ['Reading', 'Cycling']]
```

### Asynchronous (Parallel) Requests

[](#asynchronous-parallel-requests)

Execute multiple AI requests simultaneously to improve performance.

```
// Simple parallel requests
$responses = Ai::async()->ask([
    'weather' => 'What is the weather in Tokyo?',
    'news' => 'What are the top news in Japan today?',
]);

// Fluent parallel requests with different drivers
$responses = Ai::async()
    ->add('gpt', Ai::driver('openai')->model('gpt-4o'))
    ->add('claude', Ai::driver('claude')->model('claude-3-5-sonnet-latest'))
    ->execute();
```

---

🛡 Security &amp; Privacy (Zero Liability)
-----------------------------------------

[](#-security--privacy-zero-liability)

This package is designed for high-security environments where data privacy is paramount.

### PII Masking &amp; Redaction

[](#pii-masking--redaction)

Automatically detect and mask sensitive information (emails, credit cards, API keys, etc.) before sending data to providers.

```
// Reversible Masking (Default)
// Masks "john@example.com" -> "[EMAIL_1]" before sending,
// then restores it when the AI responds.
$response = Ai::withPiiMasking()->ask('Tell my friend john@example.com hello.');

// Irreversible Redaction (Strict Mode)
// Permanently replaces PII with [REDACTED] - cannot be undone.
$response = Ai::scrubPii()->ask('My secret key is sk_12345');
```

Enable globally in `config/ai.php`:

```
'pii_masking' => [
    'enabled' => true,
    'strict' => false, // Set to true for irreversible redaction
],
```

---

🧩 Prompt Templates
------------------

[](#-prompt-templates)

Templates provide a clean way to handle complex prompts.

```
use Devcbh\LaravelAiProvider\Templates\SentimentTemplate;

$result = Ai::template(new SentimentTemplate(), [
    'text' => 'I absolutely love this new Laravel package!'
])->asJson();

// Returns: ['sentiment' => 'Positive', 'score' => 0.9]
```

### Available Templates

[](#available-templates)

TemplatePurposeKey Data Keys`SentimentTemplate`Analyze text sentiment`text``SummarizationTemplate`Summarize long content`content`, `max_length``TranslationTemplate`Multi-language translation`text`, `target_language``CodeReviewTemplate`Review code snippets`code`, `language``PredictionTemplate`Data sequence prediction`data`, `target``FraudDetectionTemplate`Identify suspicious patterns`data``SeoOptimizerTemplate`Generate SEO assets`content`, `keywords`... and many more.See `src/Templates`---

🔄 Advanced Features
-------------------

[](#-advanced-features)

### Global Failover (Fallbacks)

[](#global-failover-fallbacks)

Ensure your application stays up even if an AI provider goes down.

```
// Fluent fallback
$response = Ai::fallback(['gemini', 'ollama'])
    ->ask('Write a haiku about servers.');
```

### Streaming Support

[](#streaming-support)

Stream responses in real-time for chat applications.

```
$stream = Ai::stream('Write a long story about a space cat.');

foreach ($stream as $chunk) {
    echo $chunk;
    flush();
}
```

### Function Calling (Tools)

[](#function-calling-tools)

Allow AI to interact with your local PHP methods.

```
Ai::withTools([[$orderService, 'getDetails']])
  ->ask("Where is my order #123?");
```

---

🔌 Supported Drivers
-------------------

[](#-supported-drivers)

DriverJSON ResponseCustom SchemaPII MaskingStreamingTools**OpenAI**✅✅✅✅✅**Gemini**✅✅✅✅✅**Claude**✅✅✅✅✅**Mistral**✅✅✅✅✅**Ollama**XX✅✅✅---

🧪 Testing
---------

[](#-testing)

Since the package uses Laravel's `Http` client, you can use `Http::fake()` to mock AI responses in your tests:

```
use Illuminate\Support\Facades\Http;
use Devcbh\LaravelAiProvider\Facades\Ai;

Http::fake([
    '*' => Http::response(['choices' => [['message' => ['content' => 'Mocked response']]]], 200),
]);

$response = Ai::ask('Hello?');
$this->assertEquals('Mocked response', $response);
```

---

📄 License &amp; Disclaimer
--------------------------

[](#-license--disclaimer)

- **License**: MIT License. See [LICENSE.md](LICENSE.md).
- **Disclaimer**: AI models can hallucinate. Please read our [AI Disclaimer](DISCLAIMER.md) before use.
- **Privacy**: PII detection happens entirely on your server. No data is stored or logged by this package.

###  Health Score

39

—

LowBetter than 86% of packages

Maintenance90

Actively maintained with recent releases

Popularity11

Limited adoption so far

Community8

Small or concentrated contributor base

Maturity41

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

Every ~6 days

Recently: every ~14 days

Total

12

Last Release

51d ago

Major Versions

1.1.2 → 2.0.02026-01-27

2.2.0 → 3.0.02026-01-27

PHP version history (2 changes)1.0.0PHP ^8.2

1.1.1PHP ^8.0

### Community

Maintainers

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

---

Top Contributors

[![devcbh](https://avatars.githubusercontent.com/u/50860288?v=4)](https://github.com/devcbh "devcbh (1 commits)")

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/devcbh-laravel-ai-provider/health.svg)

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

###  Alternatives

[fumeapp/modeltyper

Generate TypeScript interfaces from Laravel Models

196277.9k](/packages/fumeapp-modeltyper)[aedart/athenaeum

Athenaeum is a mono repository; a collection of various PHP packages

245.2k](/packages/aedart-athenaeum)

PHPackages © 2026

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