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

Ia Exception Bundle Laravel Package

darkwood/ia-exception-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Install Dependencies:
    composer require symfony/ai-bundle darkwood/ia-exception-bundle
    
  2. Configure AI Platform (e.g., OpenAI in config/packages/ai.yaml):
    ai:
      platform:
        openai:
          api_key: '%env(OPENAI_API_KEY)%'
      agent:
        default:
          model: 'gpt-4o-mini'
    
  3. Enable the Bundle (auto-registered in Symfony 6+; otherwise add to config/bundles.php):
    Darkwood\IaExceptionBundle\DarkwoodIaExceptionBundle::class => ['all' => true],
    
  4. Basic Configuration (config/packages/darkwood_ia_exception.yaml):
    darkwood_ia_exception:
      enabled: true
      only_status_codes: [500]
      agent: 'ai.agent.default'
    
  5. Test in Development:
    • Trigger a 500 error (e.g., throw new \RuntimeException('Test error') in a controller).
    • Verify the AI-generated explanation appears in the error page.

First Use Case

Debugging a Production 500 Error:

  • A user reports a payment failure with a generic "500 Internal Server Error."
  • Instead of a raw stack trace, the error page now shows:
    AI Analysis:
    - Probable Cause: "Database transaction timed out during payment processing."
    - Suggested Fix: "Increase `db_timeout` in `.env` or optimize the `PaymentService` query."
    - Confidence: 0.92
    
  • Action: Engineers validate the fix and deploy within 15 minutes (vs. 2+ hours with manual debugging).

Implementation Patterns

Core Workflow

  1. Exception Capture:
    • The bundle hooks into Symfony’s kernel.exception event via ExceptionListener.
    • For Laravel, replicate this with a middleware or App\Exceptions\Handler::render().
  2. AI Analysis:
    • Exception details (class, message, stack trace) are sent to the configured AI agent.
    • Symfony: Uses ai.agent.default (from symfony/ai-bundle).
    • Laravel: Replace with a custom service using Guzzle/OpenAI SDK.
  3. Response Augmentation:
    • The default error page is extended with AI-generated content (Twig template in Symfony; Blade/Livewire in Laravel).
    • Async mode (async: true) loads analysis via a separate endpoint (/__ai_exception/{error_id}).

Integration Tips

Symfony-Specific

  • Twig Templates: Extend the default error template (templates/bundles/DarkwoodIaException/error.html.twig) to customize AI output. Example:
    {% extends '@DarkwoodIaException/error.html.twig' %}
    {% block ai_analysis %}
        <div class="ai-suggestion">
            {{ parent() }}
            <p class="disclaimer">Note: AI suggestions are hypotheses.</p>
        </div>
    {% endblock %}
    
  • Async Mode: Ensure routes are imported (config/routes.yaml):
    darkwood_ia_exception:
      resource: '@DarkwoodIaExceptionBundle/Resources/config/routes.yaml'
    
    Useful for high-traffic sites where blocking AI calls degrades performance.

Laravel Adaptation

  1. Create an AI Service:
    // app/Services/AiExceptionAnalyzer.php
    class AiExceptionAnalyzer
    {
        public function analyze(Exception $e): array
        {
            $client = new \GuzzleHttp\Client();
            $response = $client->post('https://api.openai.com/v1/chat/completions', [
                'json' => [
                    'model' => 'gpt-4o-mini',
                    'messages' => [
                        ['role' => 'system', 'content' => 'You are a PHP error analyst.'],
                        ['role' => 'user', 'content' => "Exception: {$e->getMessage()}\nTrace: {$e->getTraceAsString()}"],
                    ],
                ],
                'headers' => ['Authorization' => 'Bearer '.config('services.openai.key')],
            ]);
            return json_decode($response->getBody(), true);
        }
    }
    
  2. Override render() in Handler:
    // app/Exceptions/Handler.php
    public function render($request, Throwable $exception)
    {
        if ($exception instanceof \Symfony\Component\HttpKernel\Exception\HttpException && $exception->getStatusCode() === 500) {
            $aiAnalysis = app(AiExceptionAnalyzer::class)->analyze($exception);
            return response()->view('errors.ai_500', [
                'exception' => $exception,
                'aiAnalysis' => $aiAnalysis,
            ]);
        }
        return parent::render($request, $exception);
    }
    
  3. Create a View (resources/views/errors/ai_500.blade.php):
    @extends('errors::minimal')
    @section('title', 'AI Debug Help')
    @section('content')
        <h2>AI Analysis</h2>
        <p>{{ $aiAnalysis['english_exception'] }}</p>
        <h3>Probable Causes</h3>
        <ul>
            @foreach($aiAnalysis['probable_causes'] as $cause)
                <li>{{ $cause }}</li>
            @endforeach
        </ul>
    @endsection
    

Advanced Patterns

  • Dynamic Agent Selection: Use different AI models for dev vs. prod:
    # config/packages/ai.yaml
    ai:
      agent:
        dev:
          model: 'gpt-4'
        prod:
          model: 'gpt-4o-mini'
    
    # config/packages/darkwood_ia_exception.yaml
    darkwood_ia_exception:
      agent: '{{ app.environment === "dev" ? "ai.agent.dev" : "ai.agent.prod" }}'
    
  • Contextual Analysis: Pass additional context (e.g., request data) to the AI:
    // Symfony EventListener
    public function onKernelException(GetResponseForExceptionEvent $event)
    {
        $exception = $event->getThrowable();
        $context = [
            'user_role' => $event->getRequest()->attributes->get('user_role'),
            'endpoint' => $event->getRequest()->getPathInfo(),
        ];
        $this->aiAnalyzer->analyze($exception, $context);
    }
    
  • Fallback Mechanisms: Combine with Sentry or Logflare for hybrid debugging:
    // Laravel Handler
    public function report(Throwable $exception)
    {
        if ($exception instanceof \Symfony\Component\HttpKernel\Exception\HttpException) {
            Sentry\captureException($exception);
        }
        parent::report($exception);
    }
    

Gotchas and Tips

Pitfalls

  1. Sensitive Data in Stack Traces:

    • Issue: Stack traces may include .env keys, API tokens, or paths (e.g., /app/config/secrets.php).
    • Fix: Set include_trace: false in production and sanitize logs:
      darkwood_ia_exception:
        include_trace: false
      
    • Laravel Workaround: Use Str::of($trace)->replaceMatched('/[^a-zA-Z0-9_\-\/]/', '') to redact sensitive parts.
  2. AI Hallucinations:

    • Issue: AI may suggest incorrect fixes (e.g., "Restart the web server" for a database issue).
    • Fix:
      • Validate suggestions in a staging environment before acting.
      • Use confidence score to filter low-confidence responses:
        // Symfony EventListener
        if ($aiResponse['confidence'] < 0.7) {
            $this->fallbackToRawTrace($event);
        }
        
  3. Async Mode Quirks:

    • Issue: Async analysis may fail silently if the route is not registered or CORS blocks the fetch.
    • Fix:
      • Verify routes are imported (php bin/console debug:router | grep ai_exception).
      • Test CORS with:
        # config/packages/nelmio_cors.yaml
        nelmio_cors:
          defaults:
            allow_origin: ['*']
            allow_methods: ['GET']
            allow_headers: ['Content-Type']
            expose_headers: []
            max_age: 3600
        
      • Add a fallback UI:
        // In your error page
        fetch(`/__ai_exception/${errorId}`)
            .then(response => response.json())
            .catch(() => {
                document.getElementById('ai-analysis').innerHTML =
                    '<p class="fallback">AI analysis unavailable. Showing raw trace.</p>';
            });
        
  4. Caching Gotchas:

    • Issue: Cached responses may stale if the exception message changes slightly (e.g., "User not found" vs. "User #1
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.
ilhamsyabani/laravel-volt-starter
thethunderturner/filament-latex
ghostcompiler/laravel-querybuilder
webrek/laravel-telescope-mongodb
anousss007/blatui
zatona-eg/zatona-eg-api
cocosmos/filament-sticky-save-bar
patrickbussmann/oauth2-apple
3brs/enterprise-security-bundle
anousss007/vigilance
supportpal/eloquent-model
ardenexal/fhir-models
laravel-at/laravel-image-sanitize
romalytar/yammi-audit-log-laravel
ardenexal/fhir-validation
arshaviras/weather-widget
laravel-chronicle/core
sunchayn/nimbus
daikazu/eloquent-salesforce-objects
unseen-codes/chat