PHPackages                             mojahed/aiapi - 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. mojahed/aiapi

ActiveLibrary

mojahed/aiapi
=============

A Laravel AI API package — connect to any LLM provider with a clean, unified interface. Supports OpenAI, Claude, Gemini, Ollama, OpenRouter, Groq, DeepSeek, Mistral and more.

1.0.2(1mo ago)013↓75%MITPHPPHP ^8.1

Since Jul 13Pushed 1mo agoCompare

[ Source](https://github.com/md-mojahed/AIAPI-laravel)[ Packagist](https://packagist.org/packages/mojahed/aiapi)[ RSS](/packages/mojahed-aiapi/feed)WikiDiscussions master Synced 1w ago

READMEChangelogDependenciesVersions (2)Used By (0)

mojahed/aiapi
=============

[](#mojahedaiapi)

A Laravel AI API package — connect to any LLM provider with a clean, unified interface.
Supports OpenAI, Claude, Gemini, Ollama, OpenRouter, Groq, DeepSeek, Mistral, Together AI, Fireworks, xAI, Cohere, Z.AI, and custom providers.

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

[](#requirements)

- PHP &gt;= 8.1
- Laravel &gt;= 9.x

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

[](#installation)

```
composer require mojahed/aiapi
```

Publish config:

```
php artisan aiapi:setup
```

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

[](#configuration)

Add to your `.env`:

```
AIAPI_PROVIDER=openrouter
AIAPI_MODEL=z-ai/glm-5.2
# Note: "z-ai/glm-5.2" is the OpenRouter slug.
# For the native "zai" provider use the model name directly, e.g. glm-5.
AIAPI_BEHAVIOUR="You are a helpful assistant. Answer clearly and formally."

OPENROUTER_API_KEY=sk-or-...
OPENAI_API_KEY=sk-...
ANTHROPIC_API_KEY=sk-ant-...
GEMINI_API_KEY=...
GROQ_API_KEY=...
DEEPSEEK_API_KEY=...
MISTRAL_API_KEY=...
TOGETHER_API_KEY=...
FIREWORKS_API_KEY=...
XAI_API_KEY=...
COHERE_API_KEY=...
ZAI_API_KEY=...
```

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

[](#basic-usage)

```
use Mojahed\AIAPI\AI;

$ai = new AI();
$response = $ai->ask('What is Laravel?');

echo $response->answer;      // the answer
echo $response->summary;     // updated conversation summary
echo $response->tokensUsed;  // total tokens used
echo $response->model;       // model that responded
$response->raw;              // full raw API response array
```

Fluent Chaining
---------------

[](#fluent-chaining)

```
use Mojahed\AIAPI\AI;

$response = (new AI())
    ->setProvider('openrouter')
    ->setModel('z-ai/glm-5.2')
    ->setBehaviour('You are an Eduplus school assistant. Reply formally.')
    ->setKnowledge('/path/to/eduplus-docs.md')
    ->setSummary($summaryFromDB)
    ->setMaxTokens(1024)
    ->setTemperature(0.7)
    ->ask('How does the attendance system work?');

echo $response->answer;
```

Knowledge Injection
-------------------

[](#knowledge-injection)

Pass a file path, raw string, or array of both:

```
// Single file
$ai->setKnowledge('/knowledge/eduplus.md');

// Raw string
$ai->setKnowledge('MdsChatBot is a floating chatbot widget...');

// Multiple files
$ai->setKnowledge([
    '/knowledge/git.md',
    '/knowledge/php.md',
    '/knowledge/eduplus.md',
]);
```

Summary Memory (Cost-Efficient)
-------------------------------

[](#summary-memory-cost-efficient)

Each response returns a compact summary. Pass it back on the next question:

```
// Load summary from DB
$summary = AiSession::find($sessionId)?->summary ?? '';

$response = (new AI())
    ->setSummary($summary)
    ->ask($question);

// Save updated summary to DB
AiSession::updateOrCreate(
    ['id' => $sessionId],
    ['summary' => $response->summary]
);

return $response->answer;
```

This gives the AI conversation memory at minimal token cost — no full history needed.

Switch Provider Per Instance
----------------------------

[](#switch-provider-per-instance)

```
// Different providers for different purposes
$fast    = (new AI())->setProvider('groq');     // fastest
$smart   = (new AI())->setProvider('claude');   // most capable
$cheap   = (new AI())->setProvider('deepseek'); // cheapest
$local   = (new AI())->setProvider('ollama');   // free, local
```

Custom Provider
---------------

[](#custom-provider)

Implement `ProviderInterface` with 4 methods:

```
use Mojahed\AIAPI\Providers\ProviderInterface;

class MyCustomProvider implements ProviderInterface
{
    public function __construct(protected string $apiKey) {}

    public function send(array $messages, array $options): array
    {
        // Make your API call here
        // Return the raw response as array
    }

    public function extractContent(array $raw): string
    {
        return $raw['my_answer_field'] ?? '';
    }

    public function extractTokens(array $raw): int
    {
        return $raw['usage']['total'] ?? 0;
    }

    public function extractModel(array $raw): string
    {
        return $raw['model'] ?? 'custom';
    }
}
```

Register in `AppServiceProvider::boot()`:

```
use Mojahed\AIAPI\AI;

public function boot(): void
{
    AI::registerProvider('myprovider', MyCustomProvider::class);
}
```

Use it:

```
$ai = (new AI())->setProvider('myprovider');
```

Test Connection
---------------

[](#test-connection)

```
php artisan aiapi:test
php artisan aiapi:test --provider=claude
php artisan aiapi:test --provider=ollama --question="What is PHP?"
```

Supported Providers
-------------------

[](#supported-providers)

KeyProviderFormat`openrouter`OpenRouterOpenAI compatible`openai`OpenAIOpenAI`claude`Anthropic ClaudeAnthropic`gemini`Google GeminiGoogle`ollama`Ollama (local)Ollama`groq`GroqOpenAI compatible`deepseek`DeepSeekOpenAI compatible`mistral`Mistral AIOpenAI compatible`together`Together AIOpenAI compatible`fireworks`Fireworks AIOpenAI compatible`xai`xAI (Grok)OpenAI compatible`cohere`CohereCohere`zai`Z.AIOpenAI compatible`custom`Your ownImplement interfaceDefault Config (config/aiapi.php)
---------------------------------

[](#default-config-configaiapiphp)

```
return [
    'provider'    => env('AIAPI_PROVIDER', 'openrouter'),
    'model'       => env('AIAPI_MODEL', 'z-ai/glm-5.2'),
    'behaviour'   => env('AIAPI_BEHAVIOUR', 'You are a helpful assistant.'),
    'knowledge'   => null,
    'max_tokens'  => 1024,
    'temperature' => 0.7,
    'timeout'     => 60,
    'keys'        => [
        'openrouter' => env('OPENROUTER_API_KEY'),
        // ...
    ],
];
```

Example: Full Chat Application
------------------------------

[](#example-full-chat-application)

A complete, copy-paste-ready chat app lives in [`example/`](example):

- `example/migrations/` — `chats` + `chat_messages` tables
- `example/Models/` — `Chat` &amp; `ChatMessage` Eloquent models
- `example/Http/Controllers/ChatController.php` — chat with **history** + **summary memory**
- `example/routes/chat.php` — API routes

### The optimization

[](#the-optimization)

Full message history is stored in the database (for the UI), but **only the rolling `summary`** is sent to the LLM on each turn. Token cost stays roughly flat per message instead of growing with the conversation length.

```
$ai = (new AI())
    ->setSummary($chat->summary)            // memory from previous turns (cheap)
    ->setBehaviour(config('aiapi.behaviour'));

$response = $ai->ask($message);

$chat->update(['summary' => $response->summary]);   // roll memory forward
```

### Setup

[](#setup)

1. Copy the files from `example/` into the matching app folders.
2. Run `php artisan migrate`.
3. Register the routes from `example/routes/chat.php` inside `routes/api.php`.
4. Wrap the `ask()` call in a `try/catch` (see `ChatController::ask`) to show users a friendly error on rate limits / outages.

License
-------

[](#license)

MIT

###  Health Score

38

—

LowBetter than 83% of packages

Maintenance90

Actively maintained with recent releases

Popularity5

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity42

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

49d ago

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/92214734?v=4)[Md Mojahedul Islam](/maintainers/md-mojahed)[@md-mojahed](https://github.com/md-mojahed)

---

Top Contributors

[![md-mojahed](https://avatars.githubusercontent.com/u/92214734?v=4)](https://github.com/md-mojahed "md-mojahed (3 commits)")

---

Tags

laravelaiopenaiGeminiclaudellmdeepseekOpenRouterollamagroq

### Embed Badge

![Health badge](/badges/mojahed-aiapi/health.svg)

```
[![Health](https://phpackages.com/badges/mojahed-aiapi/health.svg)](https://phpackages.com/packages/mojahed-aiapi)
```

###  Alternatives

[cognesy/instructor-php

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

326133.2k1](/packages/cognesy-instructor-php)[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).

6877.8k](/packages/sbsaga-toon)[fomvasss/laravel-ai-tasks

AI task orchestrator for Laravel: routing, queue, audit, budget, webhooks

381.6k1](/packages/fomvasss-laravel-ai-tasks)[alidaaer/laravel-ai-agent

Give your Laravel app a brain, safely. Build AI Agents that can execute real actions in your application.

281.0k](/packages/alidaaer-laravel-ai-agent)

PHPackages © 2026

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