PHPackages                             rahasistiyak/laravel-ai-integration - 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. rahasistiyak/laravel-ai-integration

ActiveLibrary

rahasistiyak/laravel-ai-integration
===================================

Comprehensive AI integration package for Laravel

2.0.0(4mo ago)20MITPHPPHP ^8.2CI passing

Since Dec 28Pushed 4mo agoCompare

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

READMEChangelog (2)Dependencies (6)Versions (6)Used By (0)

Laravel AI Integration
======================

[](#laravel-ai-integration)

[![Laravel AI Integration](https://camo.githubusercontent.com/167e62cc16a94275841269efb7510288beb01ab7f519954c3e1c9696ed3cf253/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f4c61726176656c2d4149253230496e746567726174696f6e2d4646324432303f7374796c653d666f722d7468652d6261646765266c6f676f3d6c61726176656c266c6f676f436f6c6f723d7768697465)](https://camo.githubusercontent.com/167e62cc16a94275841269efb7510288beb01ab7f519954c3e1c9696ed3cf253/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f4c61726176656c2d4149253230496e746567726174696f6e2d4646324432303f7374796c653d666f722d7468652d6261646765266c6f676f3d6c61726176656c266c6f676f436f6c6f723d7768697465)

**The Ultimate AI Integration Package for Laravel**

Enterprise-grade, multi-provider AI SDK with caching, cost tracking, and production-ready features

[![Latest Version](https://camo.githubusercontent.com/9fafd348627893b9b899bc217aa24398a57fa6129755808a2ba445b1c3ab8a06/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f72616861736973746979616b2f6c61726176656c2d61692d696e746567726174696f6e2e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/rahasistiyak/laravel-ai-integration)[![GitHub Tests](https://camo.githubusercontent.com/0ff48058694170b6c37217fcec798824391c7f0f157e694ea20208b5cd814ffd/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f616374696f6e732f776f726b666c6f772f7374617475732f72616861736973746979616b6f6666696369616c2f6c61726176656c2d61692d696e746567726174696f6e2f74657374732e796d6c3f6272616e63683d6d61696e266c6162656c3d7465737473267374796c653d666c61742d737175617265)](https://github.com/rahasistiyakofficial/laravel-ai-integration/actions)[![PHP Version](https://camo.githubusercontent.com/606e8ac8228b3cbda683466b514a8bcad4c4f70cefc0e1e798903fd54843a2dc/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f7068702d762f72616861736973746979616b2f6c61726176656c2d61692d696e746567726174696f6e2e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/rahasistiyak/laravel-ai-integration)[![License](https://camo.githubusercontent.com/d18ab3035ae48c09451c132fd26287360b66b3070a4c4a34b4324d4812a8872e/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f6c6963656e73652f72616861736973746979616b6f6666696369616c2f6c61726176656c2d61692d696e746567726174696f6e2e7376673f7374796c653d666c61742d737175617265)](LICENSE)

**Laravel AI Integration** provides a unified, elegant API to interact with multiple AI providers including OpenAI, Anthropic (Claude), Google (Gemini), Ollama, and Groq. Built specifically for Laravel 11+, it abstracts provider complexity while offering powerful features like streaming, function calling, embeddings, and more.

[Installation](#-installation) • [Usage](#-usage) • [Features](#-features) • [FAQ](FAQ.md) • [Examples](#-examples)

---

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

[](#-features)

- 🎯 **5 AI Providers**: OpenAI, Anthropic (Claude), Google (Gemini), Ollama, Groq
- 💬 **Chat Completion**: Standard and streaming responses
- 🧠 **Embeddings**: Generate vector embeddings for semantic search
- 🖼️ **Image Generation**: DALL-E and compatible APIs
- 🛠️ **Function Calling**: Tool/function use support
- 🔄 **Streaming**: Real-time SSE streaming for chat
- 💾 **Response Caching**: Intelligent caching with Redis/database support (v2.0)
- 💰 **Cost Tracking**: Token counting and cost calculation (v2.0)
- 🔁 **Retry Logic**: Exponential backoff with circuit breaker (v2.0)
- 📝 **Prompt Templates**: Reusable prompt system (v2.0)
- 🎨 **Eloquent Integration**: Traits for AI-powered models
- ⚡ **Task Abstraction**: Pre-built tasks for common operations
- 💻 **Artisan Commands**: CLI for code generation, cache management, usage stats
- 📦 **Jobs**: Queue support for background processing

---

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

[](#-installation)

Install via Composer:

```
composer require rahasistiyak/laravel-ai-integration
```

Publish the configuration file:

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

---

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

[](#️-configuration)

### Environment Variables

[](#environment-variables)

Add your API keys to `.env`:

```
OPENAI_API_KEY=sk-...
ANTHROPIC_API_KEY=sk-ant-...
GOOGLE_API_KEY=...
GROQ_API_KEY=...
OLLAMA_BASE_URL=http://localhost:11434

AI_DEFAULT_PROVIDER=openai

# Optional: Enable Caching & Tracking (v2.0)
AI_CACHE_ENABLED=true
AI_TRACKING_ENABLED=true
```

### Provider Configuration

[](#provider-configuration)

Edit `config/ai.php` to customize provider settings:

```
return [
    'default' => env('AI_DEFAULT_PROVIDER', 'openai'),

    'providers' => [
        'openai' => [
            'driver' => 'openai',
            'api_key' => env('OPENAI_API_KEY'),
            'base_url' => env('OPENAI_BASE_URL', 'https://api.openai.com/v1'),
            'timeout' => 30,
            'models' => [
                'chat' => ['gpt-4', 'gpt-3.5-turbo'],
                'embedding' => ['text-embedding-ada-002'],
            ],
        ],
        // Additional providers...
    ],
];
```

---

🚀 Usage
-------

[](#-usage)

### Basic Chat

[](#basic-chat)

```
use Rahasistiyak\LaravelAiIntegration\Facades\AI;

$response = AI::chat()
    ->messages([
        ['role' => 'user', 'content' => 'Explain quantum computing in simple terms']
    ])
    ->get();

echo $response->content();
```

**That's it!** You're now using AI in Laravel with caching and cost tracking enabled by default.

---

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

[](#-features-1)

- 🎯 **5 AI Providers**: OpenAI, Anthropic (Claude), Google (Gemini), Ollama, Groq
- 💬 **Chat Completion**: Standard and streaming responses
- 🧠 **Embeddings**: Generate vector embeddings for semantic search
- 🖼️ **Image Generation**: DALL-E and compatible APIs
- 🛠️ **Function Calling**: Tool/function use support
- 🔄 **Streaming**: Real-time SSE streaming for chat
- 💾 **Response Caching**: Intelligent caching with Redis/database support (v2.0)
- 💰 **Cost Tracking**: Token counting and cost calculation (v2.0)
- 🔁 **Retry Logic**: Exponential backoff with circuit breaker (v2.0)
- 📝 **Prompt Templates**: Reusable prompt system (v2.0)
- 🎨 **Eloquent Integration**: Traits for AI-powered models
- ⚡ **Task Abstraction**: Pre-built tasks for common operations
- 💻 **Artisan Commands**: CLI for code generation, cache management, usage stats
- 📦 **Jobs**: Queue support for background processing

---

📦 Supported Providers
---------------------

[](#-supported-providers)

ProviderChatStreamingEmbeddingsImagesFunction Calling**OpenAI**✅✅✅✅✅**Anthropic (Claude)**✅✅❌❌✅**Google (Gemini)**✅❌✅❌❌**Groq**✅✅❌❌❌**Ollama**✅❌✅❌❌---

💡 Examples
----------

[](#-examples)

### Basic Chat

[](#basic-chat-1)

```
$response = AI::chat()
    ->messages([
        ['role' => 'system', 'content' => 'You are a helpful assistant'],
        ['role' => 'user', 'content' => 'Explain Laravel in one sentence']
    ])
    ->get();

echo $response->content();
// "Laravel is a modern PHP framework..."
```

### Streaming Responses

[](#streaming-responses)

Stream responses in real-time:

```
AI::chat()
    ->messages([
        ['role' => 'user', 'content' => 'Write a short story about AI']
    ])
    ->stream(function ($chunk) {
        echo $chunk; // Output each chunk as it arrives
    });
```

### Using Different Providers

[](#using-different-providers)

```
// Use Anthropic (Claude)
$response = AI::driver('anthropic')
    ->chat([
        ['role' => 'user', 'content' => 'Hello Claude!']
    ]);

// Use Google Gemini
$response = AI::driver('google')
    ->chat([
        ['role' => 'user', 'content' => 'Hello Gemini!']
    ]);

// Use Groq
$response = AI::driver('groq')
    ->chat([
        ['role' => 'user', 'content' => 'Hello Groq!']
    ]);

// Use local Ollama
$response = AI::driver('ollama')
    ->chat([
        ['role' => 'user', 'content' => 'Hello Llama!']
    ]);
```

### Embeddings

[](#embeddings)

Generate vector embeddings for semantic search:

```
$embedding = AI::embed()->generate('Your text here');
// Returns: [0.0123, -0.0234, 0.0156, ...]
```

### Eloquent Model Integration

[](#eloquent-model-integration)

Add AI capabilities to your models:

```
use Rahasistiyak\LaravelAiIntegration\Traits\HasAiEmbeddings;

class Article extends Model
{
    use HasAiEmbeddings;
}

// Generate embeddings
$article = Article::find(1);
$embedding = $article->generateEmbedding();
```

### Function Calling / Tools

[](#function-calling--tools)

Use function calling for structured outputs:

```
$response = AI::chat()
    ->withTools([
        [
            'type' => 'function',
            'function' => [
                'name' => 'get_weather',
                'description' => 'Get the current weather for a location',
                'parameters' => [
                    'type' => 'object',
                    'properties' => [
                        'location' => [
                            'type' => 'string',
                            'description' => 'City name',
                        ],
                        'unit' => [
                            'type' => 'string',
                            'enum' => ['celsius', 'fahrenheit'],
                        ],
                    ],
                    'required' => ['location'],
                ],
            ],
        ],
    ])
    ->messages([
        ['role' => 'user', 'content' => 'What\'s the weather in Tokyo?']
    ])
    ->get();
```

### Task Abstraction

[](#task-abstraction)

Use pre-built tasks for common operations:

```
// Text classification
$category = AI::task()->classify(
    'This new GPU delivers incredible performance for AI workloads',
    ['Technology', 'Fashion', 'Sports', 'Politics']
);
// Returns: "Technology"
```

### Image Generation

[](#image-generation)

```
$image = AI::image()->generate('A futuristic city at sunset', [
    'size' => '1024x1024',
    'quality' => 'hd'
]);
// Returns: ['url' => 'https://...']
```

### Console Commands

[](#console-commands)

Generate code via Artisan:

```
php artisan ai:generate-code "Create a UserObserver that logs model events" --language=php
```

### Background Jobs

[](#background-jobs)

Process AI tasks in the background:

```
use Rahasistiyak\LaravelAiIntegration\Jobs\ProcessAiTask;

ProcessAiTask::dispatch('classify', $text, [
    'labels' => ['Positive', 'Negative', 'Neutral']
]);
```

---

🛠️ Advanced Features
--------------------

[](#️-advanced-features)

### Custom Model Selection

[](#custom-model-selection)

Use the `model()` method on the chat builder to specify a different model for the request:

```
// Use a specific model with the default provider
AI::chat()
    ->model('gpt-4-turbo')
    ->messages([...])
    ->get();
```

### Custom Parameters

[](#custom-parameters)

```
AI::chat()
    ->withParameters([
        'temperature' => 0.9,
        'max_tokens' => 500,
        'top_p' => 0.95,
    ])
    ->messages([...])
    ->get();
```

### Fluent API Chaining

[](#fluent-api-chaining)

```
$response = AI::chat()
    ->model('gpt-4')
    ->withParameters(['temperature' => 0.7])
    ->withTools([...])
    ->messages([...])
    ->get();
```

### Prompt Templates (v2.0)

[](#prompt-templates-v20)

```
use Rahasistiyak\LaravelAiIntegration\Support\PromptTemplate;

$prompt = PromptTemplate::load('classification')
    ->with(['text' => $userInput, 'categories' => 'Tech, Sports'])
    ->toMessages();

$response = AI::chat()->messages($prompt)->get();
```

---

🎁 v2.0 New Features
-------------------

[](#-v20-new-features)

### Response Caching

[](#response-caching)

Save 60-80% on API costs automatically:

```
// First call - hits API
$response = AI::chat()->messages([...])->get();

// Second identical call - instant from cache!
$cached = AI::chat()->messages([...])->get();
```

### Cost Tracking

[](#cost-tracking)

Track usage and costs:

```
php artisan ai:usage --provider=openai
```

### Circuit Breaker

[](#circuit-breaker)

Automatic retry with circuit breaker pattern ensures 99.9% uptime.

---

📝 License
---------

[](#-license)

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

---

🙏 Credits
---------

[](#-credits)

- **Author**: [Rahasistiyak](https://github.com/rahasistiyakofficial)
- **Package**: [rahasistiyak/laravel-ai-integration](https://packagist.org/packages/rahasistiyak/laravel-ai-integration)

**Made with ❤️ for the Laravel community**

[⬆ Back to Top](#laravel-ai-integration)

###  Health Score

36

—

LowBetter than 82% of packages

Maintenance75

Regular maintenance activity

Popularity3

Limited adoption so far

Community8

Small or concentrated contributor base

Maturity51

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 94.1% 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 ~0 days

Total

4

Last Release

135d ago

Major Versions

1.2.0 → 2.0.02025-12-28

### Community

Maintainers

![](https://www.gravatar.com/avatar/64626fc08fcee19f6c990dd464377015cb4cb02413c0f96d50b639c166aa72e3?d=identicon)[rahasistiyakofficial](/maintainers/rahasistiyakofficial)

---

Top Contributors

[![IstiyakCPL](https://avatars.githubusercontent.com/u/182621267?v=4)](https://github.com/IstiyakCPL "IstiyakCPL (16 commits)")[![rahasistiyakofficial](https://avatars.githubusercontent.com/u/121127883?v=4)](https://github.com/rahasistiyakofficial "rahasistiyakofficial (1 commits)")

---

Tags

laravelaiopenaiintegrationllmanthropic

###  Code Quality

TestsPest

### Embed Badge

![Health badge](/badges/rahasistiyak-laravel-ai-integration/health.svg)

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

###  Alternatives

[laravel/boost

Laravel Boost accelerates AI-assisted development by providing the essential context and structure that AI needs to generate high-quality, Laravel-specific code.

3.4k10.6M274](/packages/laravel-boost)[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)

PHPackages © 2026

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