PHPackages                             fiachehr/laravel-ai-gateway - 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. fiachehr/laravel-ai-gateway

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

fiachehr/laravel-ai-gateway
===========================

Unified AI gateway for Laravel supporting multiple providers with structured logging.

v1.0.0(1mo ago)0104↓11.1%MITPHPPHP ^8.3

Since Apr 14Pushed 1mo agoCompare

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

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

Laravel AI Gateway
==================

[](#laravel-ai-gateway)

[![Latest Version](https://camo.githubusercontent.com/fc029001fc7df3d5222d373a200b8e599bb653038f7bf781b14c126ddeb42ce9/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f66696163686568722f6c61726176656c2d61692d676174657761792e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/fiachehr/laravel-ai-gateway)[![Total Downloads](https://camo.githubusercontent.com/6a212ee4c6cf22a814c2c7dca5b13e9654f9488704474ed7521394b71fe8dba5/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f66696163686568722f6c61726176656c2d61692d676174657761792e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/fiachehr/laravel-ai-gateway)[![License](https://camo.githubusercontent.com/9e164a375c291dfddb5435a41a0901a9b2360b3cf2b0afcc9e075eb6e6350283/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f6c2f66696163686568722f6c61726176656c2d61692d676174657761792e7376673f7374796c653d666c61742d737175617265)](LICENSE)

Unified AI gateway for Laravel: one fluent API for multiple providers, normalized response DTOs, and database logging that never breaks the main request flow.

Table of contents
-----------------

[](#table-of-contents)

- [Documentation](#documentation)
- [Supported providers](#supported-providers)
- [Features](#features)
- [Requirements](#requirements)
- [Installation](#installation)
- [Environment variables](#environment-variables)
- [Configuration](#configuration)
- [Usage](#usage)
- [Response object](#response-object)
- [Model listing](#model-listing)
- [Logging](#logging)
- [Error handling](#error-handling)
- [Extending with new providers](#extending-with-new-providers)
- [Testing](#testing)
- [Troubleshooting](#troubleshooting)
- [Security](#security)
- [Links](#links)
- [License](#license)

Documentation
-------------

[](#documentation)

- Hosted HTML: [Laravel AI Gateway — Documentation](https://fiachehr.ir/docs/laravel-ai-gateway.html)

Supported providers
-------------------

[](#supported-providers)

ProviderKeyModel listingOpenAI`openai`YesGemini`gemini`YesDeepSeek`deepseek`YesClaude`claude`No (throws capability exception)Ollama`ollama`YesFeatures
--------

[](#features)

- Fluent chain: `AI::provider()->model()->systemPrompt()->userPrompt()->options()->metadata()->send()`
- `prompt()` alias for user prompt (backward compatible)
- Service API: `app(AIManager::class)->send(...)` and `listModels()`
- DTOs: `AIRequestData`, `AIResponseData`, `ModelData`
- Factory-based provider resolution; strategy-style adapters
- Eloquent-backed `ai_logs` table via `AILog` model and repository
- Log failures isolated so they never interrupt AI calls

Requirements
------------

[](#requirements)

- PHP 8.3+
- Laravel 10.x, 11.x, or 12.x

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

[](#installation)

```
composer require fiachehr/laravel-ai-gateway
```

Publish assets and migrate:

```
php artisan vendor:publish --tag=aigateway-config
php artisan vendor:publish --tag=aigateway-migrations
php artisan migrate
```

The service provider registers automatically. The facade alias is `AI` → `Fiachehr\AiGateway\Facades\AI`.

Environment variables
---------------------

[](#environment-variables)

Minimal `.env` example (adjust per provider you use):

```
AI_GATEWAY_DEFAULT_PROVIDER=openai
AI_GATEWAY_DEFAULT_MODEL=gpt-5-mini
AI_GATEWAY_TIMEOUT=60

OPENAI_API_KEY=
OPENAI_BASE_URL=https://api.openai.com/v1

GEMINI_API_KEY=
GEMINI_BASE_URL=https://generativelanguage.googleapis.com/v1beta

DEEPSEEK_API_KEY=
DEEPSEEK_BASE_URL=https://api.deepseek.com/v1

CLAUDE_API_KEY=
CLAUDE_BASE_URL=https://api.anthropic.com/v1
CLAUDE_API_VERSION=2023-06-01

OLLAMA_BASE_URL=http://localhost:11434
OLLAMA_API_KEY=
```

Configuration
-------------

[](#configuration)

After publishing, edit `config/aigateway.php`. Defaults come from `env()` as in the block above. Each provider has `base_url` and usually `api_key` (Ollama may omit the key on a local install).

Usage
-----

[](#usage)

### Fluent API (recommended)

[](#fluent-api-recommended)

```
use Fiachehr\AiGateway\Facades\AI;

$response = AI::provider('openai')
    ->model('gpt-5-mini')
    ->systemPrompt('You are a concise technical assistant.')
    ->userPrompt('Write a short welcome message for new users.')
    ->send();

$text = $response->responseText;
```

### `prompt()` as user message

[](#prompt-as-user-message)

```
$response = AI::provider('gemini')
    ->model('gemini-2.5-flash')
    ->systemPrompt('Respond in Persian.')
    ->prompt('Summarize this text.')
    ->options(['generationConfig' => ['temperature' => 0.2]])
    ->metadata(['source' => 'admin-panel'])
    ->send();
```

### Service layer

[](#service-layer)

```
use Fiachehr\AiGateway\Services\AIManager;

$response = app(AIManager::class)->send(
    provider: 'deepseek',
    model: 'deepseek-chat',
    prompt: 'Explain SOLID briefly.',
    systemPrompt: 'Keep it short and practical.',
    options: [],
    metadata: ['request_id' => request()->id()]
);
```

### Default provider and model

[](#default-provider-and-model)

If you omit `provider()` or `model()`, values from `config('aigateway.default_provider')` and `config('aigateway.default_model')` are used.

Response object
---------------

[](#response-object)

`send()` returns `Fiachehr\AiGateway\DTOs\AIResponseData` (readonly). Common properties:

PropertyTypeDescription`responseText``string`Normalized assistant text`provider``string`Provider key`model``string`Model id used`requestPayload``array`Payload sent to the provider`responsePayload``array`Raw decoded JSON response`requestId``?string`When the API returns one`inputTokens``?int`Usage when available`outputTokens``?int`Usage when available`totalTokens``?int`Usage when available`estimatedCost``?float`Reserved; not computed by the package`metadata``array`Merged metadata from request/responseUse `->toArray()` for logging or API responses.

Model listing
-------------

[](#model-listing)

```
use Fiachehr\AiGateway\Facades\AI;

$models = AI::listModels('openai');
```

Each entry is a `ModelData` instance with `id`, `provider`, `name`, `metadata`, and `toArray()`. For `claude`, listing throws `CapabilityNotSupportedException` by design.

Logging
-------

[](#logging)

Rows are written to `ai_logs` (Eloquent: `Fiachehr\AiGateway\Models\AILog`) with:

- `provider`, `model`, `prompt`
- `request_payload`, `response_payload`, `response_text`
- `status` (`success` / `failed`), `error_message`, `request_id`
- `input_tokens`, `output_tokens`, `total_tokens`, `estimated_cost`, `latency_ms`
- `metadata` (includes `system_prompt` and `user_prompt` when set)

If the database write fails, the error is swallowed so your application flow continues.

Error handling
--------------

[](#error-handling)

```
use Fiachehr\AiGateway\Exceptions\AIException;
use Fiachehr\AiGateway\Exceptions\ProviderRequestException;

try {
    $response = AI::provider('claude')
        ->model('claude-3-5-sonnet')
        ->prompt('Hello')
        ->send();
} catch (ProviderRequestException $e) {
    report($e);
} catch (AIException $e) {
    report($e);
}
```

Exception hierarchy (all extend `AIException` unless noted):

- `ProviderNotSupportedException` — unknown provider key
- `CapabilityNotSupportedException` — e.g. model listing not supported
- `ProviderRequestException` — base for HTTP-level failures
- `ProviderAuthenticationException` — 401 / 403
- `ProviderRateLimitException` — 429
- `ProviderResponseException` — 5xx from provider

Extending with new providers
----------------------------

[](#extending-with-new-providers)

1. Create a class implementing `Fiachehr\AiGateway\Contracts\AIProviderContract` (`send()` returns `AIResponseData`).
2. Optionally implement `Fiachehr\AiGateway\Contracts\ModelListableContract` for `listModels()`.
3. Register the provider key in `Fiachehr\AiGateway\Factories\ProviderFactory::make()`.
4. Add config under `config/aigateway.php` `providers` and document env keys in your README.

Bind the concrete class in `AiGatewayServiceProvider` if you need container injection.

Testing
-------

[](#testing)

From a clone of this repository:

```
composer install
./vendor/bin/phpunit -c phpunit.xml
```

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

[](#troubleshooting)

SymptomWhat to check`Class "Fiachehr\AiGateway\Facades\AI" not found`Run `composer dump-autoload`, clear config cache `php artisan config:clear`.Migration errorsPublish migrations once; avoid duplicate `ai_logs` table names.Empty `responseText`Inspect `responsePayload` in logs; model or API shape may have changed.Gemini 404 on modelUse full model id as in Google docs (e.g. `gemini-2.5-flash`).Claude model list failsExpected: use `CapabilityNotSupportedException` or call listing only on supported drivers.Security
--------

[](#security)

- Store API keys only in `.env` / secret managers, never in VCS.
- Treat prompts as sensitive; avoid putting secrets inside logged prompts.
- Use HTTPS `base_url` values for cloud providers.

Links
-----

[](#links)

- [Packagist — fiachehr/laravel-ai-gateway](https://packagist.org/packages/fiachehr/laravel-ai-gateway)
- [GitHub — laravel-ai-gateway](https://github.com/fiachehr/laravel-ai-gateway)
- [Laravel documentation](https://laravel.com/docs)

License
-------

[](#license)

This package is released under the [MIT License](LICENSE).

###  Health Score

41

—

FairBetter than 87% of packages

Maintenance89

Actively maintained with recent releases

Popularity13

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity48

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

56d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/535c8f29f90b6f75ba28d952c79d2861c115652851314b7f6330e204493f1c48?d=identicon)[fiachehr](/maintainers/fiachehr)

---

Top Contributors

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

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/fiachehr-laravel-ai-gateway/health.svg)

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

###  Alternatives

[psalm/plugin-laravel

Psalm plugin for Laravel

3325.1M337](/packages/psalm-plugin-laravel)[pressbooks/pressbooks

Pressbooks is an open source book publishing tool built on a WordPress multisite platform. Pressbooks outputs books in multiple formats, including PDF, EPUB, web, and a variety of XML flavours, using a theming/templating system, driven by CSS.

45344.0k1](/packages/pressbooks-pressbooks)[api-platform/laravel

API Platform support for Laravel

59156.3k10](/packages/api-platform-laravel)[calebdw/larastan

Larastan - Discover bugs in your code without running it. A phpstan/phpstan extension for Laravel

15104.9k4](/packages/calebdw-larastan)[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)
