Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Larabrain Laravel Package

inceptia-io/larabrain

LaraBrain gives your Laravel app “self-awareness” by scanning models, migrations, routes, and controllers to build a context graph, then lets you ask natural-language questions via AI providers (OpenAI, Gemini, Anthropic, DeepSeek) with links to relevant code.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps to First Use

  1. Installation:

    composer require inceptia-io/larabrain
    php artisan vendor:publish --tag=brain-config
    

    Configure .env with your AI provider key (e.g., OPENAI_API_KEY).

  2. Initial Scan:

    php artisan app-brain:scan
    

    This builds the context graph for your codebase (models, routes, controllers).

  3. First Question:

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

    Or via the web UI at /brain (if enabled).

Where to Look First

  • Configuration: config/app-brain.php (adjust AI provider, caching, UI settings).
  • Scanning: php artisan app-brain:scan --help (customize paths, dry runs).
  • Facade: AppBrain::ask() for programmatic use.

First Use Case

Onboarding a New Developer: Ask, "Explain the order processing flow" to get a structured breakdown with clickable links to relevant code/files. Ideal for reducing ramp-up time.


Implementation Patterns

Core Workflows

  1. Scanning Workflow:

    • Scheduled Scans: Add to app/Console/Kernel.php to run nightly:
      protected function schedule(Schedule $schedule): void
      {
          $schedule->command('app-brain:scan')->daily();
      }
      
    • Incremental Scans: Use --path to target specific directories (e.g., app/Features):
      php artisan app-brain:scan --path=app/Features
      
  2. Querying Workflow:

    • CLI: For scripts/automation:
      php artisan app-brain:ask "List all API routes" --json > routes.json
      
    • Web UI: Embed the floating widget in admin dashboards for ad-hoc queries.
    • Facade: In controllers/services:
      $response = AppBrain::ask('What models use the `User` model?');
      return response()->json($response->answer);
      
  3. Context-Driven Development:

    • Pair Programming: Use the web UI to explain logic during PR reviews.
    • Debugging: Ask, "Why is this validation failing?" to surface related code.

Integration Tips

  • Middleware: Protect the UI with custom middleware:
    'ui' => [
        'middleware' => ['web', 'can:access-brain-ui'],
    ],
    
  • Event Listeners: Trigger scans after deployments:
    public function handle(Deployed $event)
    {
        Artisan::call('app-brain:scan');
    }
    
  • Testing: Mock the BrainInterface in unit tests:
    $this->mock(BrainInterface::class, function ($mock) {
        $mock->shouldReceive('ask')
             ->andReturn(new AppBrainResponse('Mock answer'));
    });
    

Advanced Patterns

  • Custom Prompts: Extend the AppBrainResponse to include metadata:
    $response = AppBrain::ask('Explain the checkout flow', ['format' => 'markdown']);
    
  • Multi-Keyword Queries: Chain keywords for precision:
    php artisan app-brain:ask "Show routes for the payment model" --keyword=payment
    
  • AI Provider Switching: Dynamically override the driver:
    config(['app-brain.ai.default' => 'gemini']);
    $response = AppBrain::ask('Describe the user model');
    

Gotchas and Tips

Pitfalls

  1. Cold Starts:

    • Issue: First queries after a scan are slower due to context building.
    • Fix: Enable caching (BRAIN_CACHE_ENABLED=true) and pre-scan during deployments.
  2. Token Limits:

    • Issue: Complex queries hit AI token limits (e.g., gpt-4o max 128K tokens).
    • Fix: Use --keyword to narrow context or reduce BRAIN_OPENAI_MAX_TOKENS.
  3. Dynamic Code:

    • Issue: Scans miss runtime-generated routes (e.g., API resource routes).
    • Fix: Extend the RouteScanner to include dynamic route resolution.
  4. Permission Errors:

    • Issue: Web UI returns 403 if middleware isn’t configured.
    • Fix: Verify config/app-brain.php under 'ui' => ['middleware'].
  5. Cache Invalidation:

    • Issue: Stale context after code changes.
    • Fix: Clear cache manually:
      php artisan cache:clear
      php artisan app-brain:scan --force
      

Debugging

  • Log Queries: Enable debug logs to inspect prompts/responses:
    BRAIN_ASK_LOG_QUERIES=true
    BRAIN_LOG_CHANNEL=single
    
  • Dry Runs: Test scans without writing to the database:
    php artisan app-brain:scan --dry-run
    
  • Intent Mismatches: If answers are off-topic, adjust the IntentMap:
    IntentMap::extend(Intent::DescribeModel, ['schema', 'database']);
    

Configuration Quirks

  1. Cache Prefix Collisions:

    • Fix: Customize BRAIN_CACHE_PREFIX if using other packages with brain-* keys.
  2. UI Route Conflicts:

    • Fix: Change BRAIN_UI_PREFIX (e.g., to dev-brain) to avoid clashes with existing routes.
  3. AI Provider Timeouts:

    • Fix: Increase BRAIN_OPENAI_TIMEOUT (default: 60s) for slow networks:
      BRAIN_OPENAI_TIMEOUT=120
      

Extension Points

  1. Custom Scanners:

    • Implement Arafat\Brain\Contracts\ScannerInterface to add support for:
      • Custom file types (e.g., .env files).
      • External APIs (e.g., Stripe webhooks).
    • Register in config/app-brain.php:
      'scan' => [
          'scanners' => [
              'custom' => \App\Scanners\CustomScanner::class,
          ],
      ],
      
  2. Prompt Customization:

    • Override the default prompt template in a service provider:
      Brain::extend(function ($app) {
          $app->singleton('brain.prompt', function () {
              return new CustomPromptTemplate();
          });
      });
      
  3. Response Post-Processing:

    • Extend AppBrainResponse to add fields (e.g., confidence scores):
      class ExtendedResponse extends AppBrainResponse
      {
          public function getConfidence(): float
          {
              return $this->answer->contains('likely') ? 0.7 : 1.0;
          }
      }
      
  4. Queue Integration:

    • Offload AI calls to a queue (e.g., for long-running prompts):
      BRAIN_QUEUE_ENABLED=true
      
    • Process responses via BrainEvents::asked:
      Event::listen(BrainEvents::asked, function ($response) {
          // Store response in DB or notify users
      });
      

Performance Tips

  • Selective Scanning: Disable scanners for unused features:
    'scan' => [
        'scanners' => [
            'model' => false, // Disable model scanning
            'route' => true,
        ],
    ],
    
  • Keyword Caching: Cache context per keyword to avoid rescanning:
    BRAIN_ASK_CACHE_CONTEXT=true
    BRAIN_CACHE_CONTEXT_TTL=86400
    
  • Model Optimization: Use cheaper models for non-critical queries:
    BRAIN_OPENAI_MODEL=gpt-3.5-turbo
    
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
terminal42/code-quality-tools
codifyo/ts-generator-bundle
andydefer/laravel-cluster
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky