PHPackages                             mukundhanmohan/laravel-explainable-ai - 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. mukundhanmohan/laravel-explainable-ai

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

mukundhanmohan/laravel-explainable-ai
=====================================

Laravel-native AI orchestration and explainability toolkit.

v0.1.1(1mo ago)21MITPHPPHP ^8.2CI passing

Since Apr 12Pushed 1mo agoCompare

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

READMEChangelog (2)Dependencies (13)Versions (3)Used By (0)

laravel-explainable-ai
======================

[](#laravel-explainable-ai)

[![Latest Version on Packagist](https://camo.githubusercontent.com/7469f9f2a795b0ca4f1b377ac2e34fd25d6c0a3a8eff1135d1b2cb0528ab6c58/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f6d756b756e6468616e6d6f68616e2f6c61726176656c2d6578706c61696e61626c652d61692e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/mukundhanmohan/laravel-explainable-ai)[![License](https://camo.githubusercontent.com/a8d976b1633908deab2c7a391ca2484d73e82342b46fb4bbdd551069e9cafe73/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f6c6963656e73652f6d756b756e6468616e2d6d6f68616e2f6c61726176656c2d6578706c61696e61626c652d61692e7376673f7374796c653d666c61742d737175617265)](LICENSE)[![Total Downloads](https://camo.githubusercontent.com/2d665296ca42259b2fd69d8b6e5f733a02f59726513a59b75e1dbbbe3c6390a2/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f6d756b756e6468616e6d6f68616e2f6c61726176656c2d6578706c61696e61626c652d61692e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/mukundhanmohan/laravel-explainable-ai)[![Tests](https://camo.githubusercontent.com/fb7e918beb0bde71ff7c1e04c575c0ee51928b8fdbe052049a653de95e72645c/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f616374696f6e732f776f726b666c6f772f7374617475732f6d756b756e6468616e2d6d6f68616e2f6c61726176656c2d6578706c61696e61626c652d61692f74657374732e796d6c3f6272616e63683d6d61696e267374796c653d666c61742d737175617265266c6162656c3d7465737473)](https://github.com/mukundhan-mohan/laravel-explainable-ai/actions/workflows/tests.yml)

`laravel-explainable-ai` is a Laravel-native AI orchestration and explainability toolkit for teams that want more than a raw provider SDK. It wraps prompt templates, structured outputs, heuristic explainability metadata, audit logging, cost tracking, caching, queue dispatch, and test helpers behind a Laravel-friendly API.

[![laravel-explainable-ai demo](docs/assets/demo-terminal.svg)](docs/assets/demo-terminal.svg)

The package is designed around a simple fluent developer experience:

```
use LaravelExplainableAI\Facades\AI;

$result = AI::prompt('summarize_feedback')
    ->input(['feedback' => $text])
    ->withExplanation()
    ->withConfidence()
    ->provider('openai')
    ->model('gpt-4.1-mini')
    ->execute();
```

Typical normalized output:

```
[
    'content' => 'Escalate this complaint to support.',
    'structured_output' => [
        'summary' => 'Customer is unhappy',
        'next_action' => 'Escalate this complaint to support.',
    ],
    'explanation' => [
        'summary' => 'Heuristic rationale based on refund, complaint, support.',
        'factors' => ['refund', 'complaint', 'support', 'schema-compliant structured output'],
        'confidence' => 0.86,
        'risk_flags' => ['customer_churn_risk'],
        'decision_trace' => [...],
    ],
    'usage' => [
        'input_tokens' => 100,
        'output_tokens' => 25,
        'total_tokens' => 125,
        'estimated_cost' => 0.00008,
        'currency' => 'USD',
    ],
    'provider' => 'openai',
    'model' => 'gpt-4.1-mini',
]
```

Why explainability matters
--------------------------

[](#why-explainability-matters)

Most application teams do not need fake claims about model internals. They need operational clarity:

- What prompt version was used
- What evidence patterns influenced the answer
- How confident the system appears to be
- Which risk flags should trigger human review
- How much the request cost
- Whether the answer was cached

This package frames explainability as heuristic rationale, decision trace, and confidence estimation built from observable request and response data.

Features
--------

[](#features)

- Provider-agnostic orchestration via contracts
- Fluent `AI` facade and request builder
- YAML prompt templates in `resources/prompts/*.yaml`
- Structured output parsing and validation
- Heuristic explainability metadata
- Confidence scoring and risk flagging
- Database audit logging and cost tracking
- Cache-aware execution
- Queue-based async execution
- Middleware safeguards for rate limiting, PII redaction, and safety checks
- `AI::fake()` testing support
- Artisan install, prompt generation, and prompt test commands

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

[](#requirements)

- PHP 8.2+
- Laravel 11+

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

[](#installation)

Install the package through Composer:

```
composer require mukundhanmohan/laravel-explainable-ai
```

Publish the package assets:

```
php artisan ai:install
```

Or publish assets individually:

```
php artisan vendor:publish --tag=explainable-ai-config
php artisan vendor:publish --tag=explainable-ai-migrations
php artisan vendor:publish --tag=explainable-ai-prompts
php artisan migrate
```

Add provider credentials to `.env`:

```
OPENAI_API_KEY=your-key
OPENAI_MODEL=gpt-4.1-mini
EXPLAINABLE_AI_PROVIDER=openai
```

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

[](#configuration)

The main package config lives at [`config/explainable-ai.php`](config/explainable-ai.php). It includes:

- Default provider selection
- Provider credentials and default models
- Prompt search paths
- Cache configuration
- Queue configuration
- Logging flags
- Explainability heuristics
- Rate limits
- Pricing tables for token cost estimation

Quick start
-----------

[](#quick-start)

### Basic prompt execution

[](#basic-prompt-execution)

```
use LaravelExplainableAI\Facades\AI;

$response = AI::prompt('summarize_feedback')
    ->input(['feedback' => 'This is my third complaint and I want a refund.'])
    ->provider('openai')
    ->model('gpt-4.1-mini')
    ->execute();

$response->toArray();
```

### Explainability and confidence

[](#explainability-and-confidence)

```
$response = AI::prompt('summarize_feedback')
    ->input(['feedback' => $feedback])
    ->withExplanation()
    ->withConfidence()
    ->execute();

$summary = $response->explanation?->summary;
$confidence = $response->explanation?->confidence;
```

### Structured output

[](#structured-output)

You can rely on the schema from the prompt template or override it at runtime:

```
$response = AI::prompt('classify_urgency')
    ->input(['message' => $message])
    ->schema([
        'type' => 'object',
        'required' => ['urgency', 'rationale'],
        'properties' => [
            'urgency' => ['type' => 'string'],
            'rationale' => ['type' => 'string'],
        ],
    ])
    ->execute();

$urgency = $response->structuredOutput['urgency'];
```

### Async execution

[](#async-execution)

```
AI::prompt('recommend_next_action')
    ->input(['case' => $case])
    ->provider('openai')
    ->async()
    ->execute();
```

This dispatches `LaravelExplainableAI\Queue\ExecuteAIRequestJob` using the package queue settings.

Prompt templates
----------------

[](#prompt-templates)

Prompt files live in `resources/prompts/*.yaml`.

Example:

```
name: summarize_feedback
version: 1.0.0
system: |
  You summarize customer feedback for support operations.
  Provide a concise recommendation. If a schema is provided, return valid JSON only.
user: |
  Summarize this feedback and recommend the next step:
  {{ feedback }}
schema:
  type: object
  required:
    - summary
    - next_action
  properties:
    summary:
      type: string
    next_action:
      type: string
```

Included examples:

- [`resources/prompts/summarize_feedback.yaml`](resources/prompts/summarize_feedback.yaml)
- [`resources/prompts/classify_urgency.yaml`](resources/prompts/classify_urgency.yaml)
- [`resources/prompts/recommend_next_action.yaml`](resources/prompts/recommend_next_action.yaml)

Explainability model
--------------------

[](#explainability-model)

The package does not claim access to model internals. Instead it produces a practical explanation layer with:

- Summary: a concise heuristic rationale
- Factors: keyword and response-shape signals observed in input/output
- Confidence: a heuristic score derived from completeness, schema compliance, and provider signals when available
- Risk flags: keyword-based operational flags like churn or escalation risk
- Decision trace: a step-by-step trace of prompt rendering, provider completion, output parsing, and heuristic scoring

Core implementation lives in:

- [`src/Explainability/ExplainabilityEngine.php`](src/Explainability/ExplainabilityEngine.php)
- [`src/Explainability/ConfidenceScorer.php`](src/Explainability/ConfidenceScorer.php)
- [`src/Explainability/RiskFlagger.php`](src/Explainability/RiskFlagger.php)

Logging and observability
-------------------------

[](#logging-and-observability)

The package stores audit and cost data in four tables:

- `ai_requests`
- `ai_responses`
- `ai_cost_records`
- `ai_prompt_versions`

Logging classes:

- [`src/Logging/AuditLogger.php`](src/Logging/AuditLogger.php)
- [`src/Logging/UsageLogger.php`](src/Logging/UsageLogger.php)

Cache behavior
--------------

[](#cache-behavior)

Responses are cached using a key derived from:

- Prompt name and version
- Input payload
- Provider and model
- Schema
- Explainability flags
- Rendered prompt content

Cache implementation:

- [`src/Caching/ResponseCache.php`](src/Caching/ResponseCache.php)
- [`src/Caching/CacheKeyGenerator.php`](src/Caching/CacheKeyGenerator.php)

Testing
-------

[](#testing)

The package includes `AI::fake()` so application tests can avoid provider calls:

```
use LaravelExplainableAI\Facades\AI;

AI::fake([
    [
        'content' => 'Escalate this complaint to support.',
        'provider' => 'openai',
        'model' => 'gpt-4.1-mini',
    ],
]);

$response = AI::prompt('summarize_feedback')
    ->input(['feedback' => 'Repeated refund complaint'])
    ->execute();
```

Core test coverage is included for:

- Prompt rendering
- OpenAI normalization
- Output parsing and repair
- Explainability generation
- Cache hits
- Async dispatch
- Facade fake support

Tests live under [`tests`](tests).

Artisan commands
----------------

[](#artisan-commands)

- `php artisan ai:install`
- `php artisan ai:prompt make {name}`
- `php artisan ai:test {prompt}`

Architecture overview
---------------------

[](#architecture-overview)

Main runtime flow:

1. `AI::prompt(...)` builds an `AIRequest`
2. `AIManager` resolves provider/model defaults or dispatches async work
3. `AIExecutionPipeline` renders the prompt and applies middleware
4. Cache is checked
5. The provider executes the request
6. Structured output is parsed and validated
7. Explainability metadata is generated
8. Audit and cost data are stored
9. A normalized `AIResponse` is returned

Key entry points:

- [`src/Managers/AIManager.php`](src/Managers/AIManager.php)
- [`src/Managers/AIExecutionPipeline.php`](src/Managers/AIExecutionPipeline.php)
- [`src/Builders/AIRequestBuilder.php`](src/Builders/AIRequestBuilder.php)

Extensibility
-------------

[](#extensibility)

Contracts are defined for:

- [`src/Contracts/AIProviderInterface.php`](src/Contracts/AIProviderInterface.php)
- [`src/Contracts/PromptRepositoryInterface.php`](src/Contracts/PromptRepositoryInterface.php)
- [`src/Contracts/ExplanationEngineInterface.php`](src/Contracts/ExplanationEngineInterface.php)
- [`src/Contracts/OutputParserInterface.php`](src/Contracts/OutputParserInterface.php)

Placeholder providers are included for:

- Anthropic
- Gemini
- Ollama

The OpenAI path is the MVP implementation. The others are ready for provider-specific adapters.

Roadmap
-------

[](#roadmap)

- Provider-specific adapters for Anthropic, Gemini, and Ollama
- Streaming responses
- Conversation memory primitives
- Richer schema support
- Response review workflows
- Per-tenant policy layers
- Telemetry integrations

Local development status
------------------------

[](#local-development-status)

The package source and tests are present in this repository. PHP syntax checks passed across `src`, `tests`, `config`, and `database`. Full PHPUnit execution was not run in this workspace because Composer dependencies are not installed yet.

###  Health Score

36

—

LowBetter than 79% of packages

Maintenance88

Actively maintained with recent releases

Popularity4

Limited adoption so far

Community8

Small or concentrated contributor base

Maturity37

Early-stage or recently created project

 Bus Factor1

Top contributor holds 83.3% 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

2

Last Release

59d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/40e78b8abc06f11ae1db331b023d4876a58a735bae9955c22a31024e8d5c889e?d=identicon)[mukundhan-mohan](/maintainers/mukundhan-mohan)

---

Top Contributors

[![sc23mm](https://avatars.githubusercontent.com/u/163000472?v=4)](https://github.com/sc23mm "sc23mm (5 commits)")[![mukundhan-mohan](https://avatars.githubusercontent.com/u/50148909?v=4)](https://github.com/mukundhan-mohan "mukundhan-mohan (1 commits)")

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/mukundhanmohan-laravel-explainable-ai/health.svg)

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

###  Alternatives

[psalm/plugin-laravel

Psalm plugin for Laravel

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

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

6.4k51.0M7.4k](/packages/larastan-larastan)[laravel/pulse

Laravel Pulse is a real-time application performance monitoring tool and dashboard for your Laravel application.

1.7k14.1M120](/packages/laravel-pulse)[roots/acorn

Framework for Roots WordPress projects built with Laravel components.

9732.3M121](/packages/roots-acorn)[flarum/core

Delightfully simple forum software.

261.4M2.2k](/packages/flarum-core)[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)
