PHPackages                             inceptia-io/larabrain - 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. inceptia-io/larabrain

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

inceptia-io/larabrain
=====================

Give your Laravel application self-awareness. Scans models, routes, controllers and migrations, builds a context graph, and answers natural-language questions about your codebase via OpenAI, Gemini, Anthropic or DeepSeek.

v1.0.1(2mo ago)1240↓86.8%MITPHPPHP ^8.1

Since May 5Pushed 2mo agoCompare

[ Source](https://github.com/inceptia-io/larabrain)[ Packagist](https://packagist.org/packages/inceptia-io/larabrain)[ Docs](https://github.com/inceptia-io/larabrain)[ RSS](/packages/inceptia-io-larabrain/feed)WikiDiscussions master Synced 1w ago

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

LaraBrain
=========

[](#larabrain)

Give your Laravel application self-awareness. LaraBrain scans your codebase (models, migrations, routes, controllers), builds a structured context graph, and uses an AI provider to answer natural-language questions about how your application works — with clickable links to relevant pages.

[![Latest Version on Packagist](https://camo.githubusercontent.com/6cc997c67f9ffe4b9f3a8f2ea0ffd8e2b1acf27556139518afd61b87afcfb5f8/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f696e6365707469612d696f2f6c617261627261696e2e737667)](https://packagist.org/packages/inceptia-io/larabrain)[![PHP Version](https://camo.githubusercontent.com/f0489645d3f02e76fec3d352dfb2badf410276fde067a009b3b03a15843d6769/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f7068702d762f696e6365707469612d696f2f6c617261627261696e2e737667)](https://packagist.org/packages/inceptia-io/larabrain)[![License](https://camo.githubusercontent.com/20d15c79b54fcdf8d9c8f48ad530a25560b0536bdbe549533f7915e0d507e35e/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f6c6963656e73652f696e6365707469612d696f2f6c617261627261696e2e737667)](LICENSE)

---

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

[](#requirements)

- PHP 8.1 or higher
- Laravel 10, 11, 12, or 13

---

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

[](#installation)

### 1 — Install via Composer

[](#1--install-via-composer)

```
composer require inceptia-io/larabrain
```

Laravel will auto-discover the service provider via the `extra.laravel` key in `composer.json`. No manual provider registration is required for Laravel 10+.

### 2 — Publish the config file

[](#2--publish-the-config-file)

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

This places `config/app-brain.php` in your application's `config/` directory.

### 3 — (Optional) Publish migrations

[](#3--optional-publish-migrations)

```
php artisan vendor:publish --tag=brain-migrations
php artisan migrate
```

### 4 — Configure environment variables

[](#4--configure-environment-variables)

Add the variables below to your `.env` file. Only `BRAIN_AI_DRIVER` and its corresponding API key are required.

---

Environment Variables
---------------------

[](#environment-variables)

All environment variables are optional unless marked **required**. The package reads from `.env` and falls back to `config/app-brain.php`.

### AI Provider Configuration

[](#ai-provider-configuration)

VariableDefaultDescription`BRAIN_AI_DRIVER``openai`**Required.** AI provider: `openai`, `gemini`, `anthropic`, or `deepseek``OPENAI_API_KEY`—OpenAI API key (e.g. `sk-...`). Required if `BRAIN_AI_DRIVER=openai``GEMINI_API_KEY`—Google Gemini API key. Required if `BRAIN_AI_DRIVER=gemini``ANTHROPIC_API_KEY`—Anthropic API key. Required if `BRAIN_AI_DRIVER=anthropic``DEEPSEEK_API_KEY`—DeepSeek API key. Required if `BRAIN_AI_DRIVER=deepseek`### Provider-Specific Settings

[](#provider-specific-settings)

VariableDefaultDescription`BRAIN_OPENAI_MODEL``gpt-4o`OpenAI model to use (e.g. `gpt-4-turbo`, `gpt-4`)`BRAIN_OPENAI_MAX_TOKENS``2048`Maximum tokens for OpenAI responses`BRAIN_OPENAI_TIMEOUT``60`Request timeout in seconds for OpenAI`BRAIN_GEMINI_MODEL``gemini-1.5-pro`Google Gemini model to use`BRAIN_GEMINI_MAX_TOKENS``2048`Maximum tokens for Gemini responses`BRAIN_ANTHROPIC_MODEL``claude-3-5-sonnet-20241022`Anthropic model to use`BRAIN_ANTHROPIC_MAX_TOKENS``2048`Maximum tokens for Anthropic responses`BRAIN_DEEPSEEK_MODEL``deepseek-chat`DeepSeek model to use`BRAIN_DEEPSEEK_MAX_TOKENS``2048`Maximum tokens for DeepSeek responses### Caching

[](#caching)

VariableDefaultDescription`BRAIN_CACHE_ENABLED``true`Enable/disable the cache layer entirely`BRAIN_ASK_CACHE_CONTEXT``false`Cache context results per keyword to avoid re-scanning`BRAIN_CACHE_CONTEXT_TTL``3600`TTL in seconds for cached context results`BRAIN_CACHE_PREFIX``brain`Cache key prefix to avoid conflicts### Logging

[](#logging)

VariableDefaultDescription`BRAIN_ASK_LOG_QUERIES``false`Log every `ask()` call at DEBUG level with metadata`BRAIN_LOG_CHANNEL``null`Log channel (uses app default if null)### Web Interface

[](#web-interface)

VariableDefaultDescription`BRAIN_UI_ENABLED``true`Enable/disable the web chat interface`BRAIN_UI_PREFIX``brain`URL prefix for chat page (e.g. `/brain`)### Example `.env`

[](#example-env)

```
# Required
BRAIN_AI_DRIVER=openai
OPENAI_API_KEY=sk-your-key-here

# Optional: customize model behavior
BRAIN_OPENAI_MODEL=gpt-4o
BRAIN_OPENAI_MAX_TOKENS=4096

# Optional: enable context caching
BRAIN_CACHE_ENABLED=true
BRAIN_ASK_CACHE_CONTEXT=true
BRAIN_CACHE_CONTEXT_TTL=7200

# Optional: enable logging
BRAIN_ASK_LOG_QUERIES=true
BRAIN_LOG_CHANNEL=single

# Optional: web interface
BRAIN_UI_ENABLED=true
BRAIN_UI_PREFIX=brain
```

---

Scanning Your Codebase
----------------------

[](#scanning-your-codebase)

Before asking questions, scan your application to build the context index:

```
php artisan app-brain:scan
```

This scans your models, migrations, routes, and controllers and stores a snapshot. Options:

```
# Scan a specific path
php artisan app-brain:scan --path=app/Models

# Only run one type of scanner
php artisan app-brain:scan --scanner=model

# Preview files without scanning
php artisan app-brain:scan --dry-run
```

---

Asking Questions
----------------

[](#asking-questions)

Use the Artisan command to ask a natural-language question:

```
php artisan app-brain:ask "How does the user registration flow work?"
```

Options:

```
# Provide an explicit keyword to focus context lookup
php artisan app-brain:ask "Explain the checkout process" --keyword=order

# Output the full response as JSON
php artisan app-brain:ask "What routes does the user have?" --json
```

---

Web Interface
-------------

[](#web-interface-1)

LaraBrain includes a built-in web UI for asking questions directly from your browser. Access is controlled by middleware (protected by `auth` by default).

### Standalone Chat Page

[](#standalone-chat-page)

Visit the chat interface at your configured URL:

```
https://your-app.test/brain

```

This is a full-page chat application with:

- Clean dark theme
- Markdown rendering for AI responses
- Clickable links to relevant routes in your application
- Request metadata (intent, driver, elapsed time)

**Access control:** Protected by `auth` middleware by default. Configure in `config/app-brain.php`:

```
'ui' => [
    'enabled'    => true,
    'prefix'     => 'brain',              // URL prefix
    'middleware' => ['web', 'auth'],      // Remove 'auth' to make public
],
```

To make it public:

```
'middleware' => ['web'],
```

### Floating Widget

[](#floating-widget)

Drop the widget anywhere in your admin layout for quick access without leaving the page:

```

@include('brain::widget')
```

The widget appears as a fixed button in the bottom-right corner. Click to open a chat panel with the same features as the standalone page.

**Example:** Add to your admin panel footer:

```

    &copy; {{ date('Y') }} Your App
    @include('brain::widget')

```

The widget respects the same middleware configuration as the chat page.

---

Using the Facade
----------------

[](#using-the-facade)

```
use AppBrain;

$response = AppBrain::ask('How does the order placement flow work?');

echo $response->answer;
echo $response->intent->label();   // e.g. "Explain Workflow"
echo $response->driver;            // e.g. "openai"
echo $response->elapsedMs;
```

You can also override keyword detection:

```
$response = AppBrain::ask(
    question: 'Explain the payment process',
    keyword:  'payment',
);
```

The `AppBrainResponse` object contains:

PropertyTypeDescription`query`stringThe original question`keyword`stringExtracted or overridden keyword`intent`IntentDetected intent enum`context`ContextResultThe resolved context graph`prompt`stringThe full prompt sent to the AI`driver`stringThe AI driver used`answer`stringThe AI response`elapsedMs`floatTotal time in milliseconds---

Intent Detection
----------------

[](#intent-detection)

The package classifies each question into one of five intents before building the prompt. This focuses the AI's response on the relevant aspect of your codebase.

IntentTriggered byExplain Workflow"how does", "explain", "walk me through", "flow", "process", "lifecycle"Show Routes"routes", "endpoints", "url", "web route", "api route"Describe Model"model", "schema", "fields", "fillable", "casts", "relationships"List Dependencies"dependencies", "what uses", "what calls", "connected to", "references"GeneralEverything elseYou can extend the keyword map at runtime:

```
use Arafat\Brain\AI\Intent;
use Arafat\Brain\AI\IntentMap;

IntentMap::extend(Intent::ExplainWorkflow, ['pipeline', 'journey', 'sequence']);
```

---

Context Building
----------------

[](#context-building)

The `Brain` facade provides direct access to the context layer:

```
use Brain;

$context = Brain::context('order');

$context->models;            // Collection of matched model data
$context->tables;            // Collection of matched table data
$context->routes;            // Collection of matched route data
$context->controllerMethods; // Collection of matched controller method data
$context->elapsedMs;
```

---

AI Providers
------------

[](#ai-providers)

Four providers are built in. Switch between them with `BRAIN_AI_DRIVER`.

DriverEnvironment KeyDefault Model`openai``OPENAI_API_KEY`gpt-4o`gemini``GEMINI_API_KEY`gemini-1.5-pro`anthropic``ANTHROPIC_API_KEY`claude-3-5-sonnet-20241022`deepseek``DEEPSEEK_API_KEY`deepseek-chatPer-provider model and token settings can be overridden in `config/app-brain.php` or via environment variables:

```
BRAIN_OPENAI_MODEL=gpt-4-turbo
BRAIN_OPENAI_MAX_TOKENS=4096
BRAIN_OPENAI_TIMEOUT=60
```

### Custom Provider

[](#custom-provider)

Implement `Arafat\Brain\AI\AppBrainAIInterface` and register it in the config:

```
// config/app-brain.php
'ai' => [
    'default' => 'myprovider',
    'drivers' => [
        'myprovider' => \App\AI\MyProvider::class,
    ],
],
```

---

Configuration Reference
-----------------------

[](#configuration-reference)

The full config file at `config/app-brain.php` includes these top-level keys:

KeyDefaultDescription`enabled``true`Globally enable or disable the package`cache.enabled``true`Enable the cache layer`cache.ttl``3600`Default cache TTL in seconds`cache.context_ttl``3600`TTL for context results specifically`cache.prefix``brain`Cache key prefix`ask.cache_context``false`Cache context results per keyword`ask.log_queries``false`Log each ask() call at DEBUG level`log_channel``null`Log channel (null uses app default)`scan.exclude`vendor, node\_modules, storage, etc.Paths excluded from file scanning`scan.scanners`all enabledPer-scanner enable/disable flags`ai.default``openai`Active AI driver`ui.enabled``true`Enable/disable the web chat interface`ui.prefix``brain`URL prefix for chat page (e.g. `/brain`)`ui.middleware``['web', 'auth']`Middleware stack for UI routes (remove `auth` to make public)---

Testing
-------

[](#testing)

```
composer test
```

With coverage:

```
composer test:coverage
```

Code quality:

```
# Style check + static analysis
composer quality

# Auto-fix style
composer format

# Static analysis only
composer analyse
```

---

License
-------

[](#license)

MIT BRAIN\_CACHE\_ENABLED=true BRAIN\_CACHE\_TTL=3600 BRAIN\_CACHE\_PREFIX=brain BRAIN\_LOG\_CHANNEL=null BRAIN\_QUEUE\_ENABLED=false BRAIN\_QUEUE\_CONNECTION=default BRAIN\_QUEUE\_NAME=brain

```

---

## Usage

### Via Facade

```php
use Arafat\Brain\Facades\Brain;

Brain::method();

```

### Via Dependency Injection

[](#via-dependency-injection)

```
use Arafat\Brain\Contracts\BrainInterface;

class MyService
{
    public function __construct(
        protected readonly BrainInterface $brain
    ) {}
}
```

---

Folder Structure
----------------

[](#folder-structure)

```
laravel-brain/
├── composer.json
├── .gitignore
├── config/
│   └── app-brain.php            # Package configuration
├── database/
│   └── migrations/
│       └── 2026_01_01_000000_create_brain_tables.php
├── src/
│   ├── Brain.php                # Core implementation
│   ├── BrainServiceProvider.php # Laravel service provider
│   ├── Contracts/
│   │   └── BrainInterface.php  # Public API contract
│   ├── Exceptions/
│   │   └── BrainException.php  # Base package exception
│   └── Facades/
│       └── Brain.php            # Laravel Facade
└── tests/
    ├── Pest.php                 # Pest bootstrap
    ├── TestCase.php             # Testbench base case
    ├── Feature/                 # Feature tests
    └── Unit/                   # Unit tests

```

---

Testing
-------

[](#testing-1)

```
composer test
# with coverage
composer test:coverage
```

---

License
-------

[](#license-1)

The MIT License (MIT). See [LICENSE](LICENSE) for details.

###  Health Score

41

—

FairBetter than 87% of packages

Maintenance85

Actively maintained with recent releases

Popularity17

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity46

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 ~0 days

Total

2

Last Release

80d ago

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/36876600?v=4)[Alamgir Kabir Roni](/maintainers/kabirswe)[@kabirswe](https://github.com/kabirswe)

---

Top Contributors

[![arafatinceptia](https://avatars.githubusercontent.com/u/249538531?v=4)](https://github.com/arafatinceptia "arafatinceptia (5 commits)")

---

Tags

laravelailaravel-packageContextopenaiGeminianthropicnatural-languagedeepseekcodebasebrainassistant

###  Code Quality

TestsPest

Static AnalysisPHPStan

Code StyleLaravel Pint

Type Coverage Yes

### Embed Badge

![Health badge](/badges/inceptia-io-larabrain/health.svg)

```
[![Health](https://phpackages.com/badges/inceptia-io-larabrain/health.svg)](https://phpackages.com/packages/inceptia-io-larabrain)
```

###  Alternatives

[cognesy/instructor-php

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

326123.0k1](/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).

6753.8k](/packages/sbsaga-toon)[spectra-php/laravel-spectra

Comprehensive observability for AI/LLM operations in Laravel applications

182.9k](/packages/spectra-php-laravel-spectra)

PHPackages © 2026

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