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

Aierrorexplained Bundle Laravel Package

acseo/aierrorexplained-bundle

Symfony dev bundle that enhances the default error page with AI-powered explanations and fix suggestions using OpenAI. Includes caching to avoid repeat calls for the same exception and integrates via a custom runtime error handler and error controller.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps to First Use

  1. Install the Bundle (dev environment only):
    composer require --dev acseo/aierrorexplained-bundle
    
  2. Configure composer.json (add runtime error handler):
    "extra": {
        "runtime": {
            "error_handler": "ACSEO\\AIErrorExplainedBundle\\Runtime\\Internal\\AIErrorHandler"
        }
    }
    
  3. Set OpenAI Key in .env:
    OPENAI_CLIENT_KEY=sk-your-key-here
    
  4. Override Error Controller (dev only):
    # config/packages/framework.yml
    when@dev:
        framework:
            error_controller: ACSEO\AIErrorExplainedBundle\Controller\ErrorController::show
    
  5. Trigger an Error (e.g., 1/0 in a dev controller) to see AI-generated explanations.

First Use Case

Debugging a runtime exception (e.g., UndefinedMethodException, DatabaseException) with an AI-generated fix suggestion in the Symfony error page.


Implementation Patterns

Core Workflow

  1. Exception Handling:

    • The bundle replaces Symfony’s default error handler with AIErrorHandler, which intercepts all uncaught exceptions.
    • Uses Symfony’s ErrorHandlerInterface to process exceptions before rendering.
  2. AI Query Generation:

    • Extracts exception details (class, message, trace) and formats them into a prompt for OpenAI’s API.
    • Example prompt structure:
      "You are a Symfony developer. Explain how to fix this error:
      Exception: [Class], Message: [Message], Trace: [Trace].
      Provide a concise fix (code snippet + explanation)."
      
  3. Caching Layer:

    • Stores AI responses in Symfony’s cache (e.g., cache:app) to avoid redundant API calls for identical errors.
    • Cache key: aierror_explained_{exception_hash}.
  4. Error Page Integration:

    • Extends Symfony’s default error template (error404.html.twig/error.html.twig) with an ai_suggestion block.
    • Renders the AI response alongside stack traces.

Integration Tips

  • Environment-Specific: Disable in production (dev: true in bundles.php) to avoid API costs and latency.
  • Custom Prompts: Override the prompt template via dependency injection:
    # config/services.yaml
    ACSEO\AIErrorExplainedBundle\Service\AIErrorService:
        arguments:
            $promptTemplate: "Your custom prompt here..."
    
  • Rate Limiting: Use Symfony’s Cache component to throttle OpenAI API calls (e.g., 1 call/minute).
  • Fallback Behavior: If OpenAI fails, revert to Symfony’s default error page (configurable via fallback_on_failure in config/packages/aierror_explained.yaml).

Example: Handling a Database Exception

// In a controller
try {
    $entityManager->flush();
} catch (\Doctrine\DBAL\Exception\ForeignKeyConstraintViolationException $e) {
    // Exception bubbles up to AIErrorHandler
    throw $e; // AI will suggest fixing the foreign key constraint
}

Gotchas and Tips

Pitfalls

  1. API Costs:

    • OpenAI API calls are not free. Monitor usage via OpenAI’s dashboard or log responses.
    • Fix: Cache aggressively and disable in production.
  2. Rate Limits:

    • OpenAI’s free tier has strict limits (~20 requests/minute).
    • Fix: Implement a cache layer (e.g., CacheInterface) to debounce API calls.
  3. Sensitive Data Exposure:

    • Error traces may include sensitive data (e.g., passwords in DATABASE_URL).
    • Fix: Sanitize traces before sending to OpenAI:
      // Override AIErrorService::generatePrompt()
      $sanitizedTrace = preg_replace('/password|secret|key=[^&]+/', '[REDACTED]', $trace);
      
  4. Cache Invalidation:

    • AI responses may become stale if OpenAI’s model updates.
    • Fix: Add a last_updated timestamp to cache keys and invalidate periodically.
  5. Bundle Maturity:

    • Low stars (2) and dependents (0) suggest untested edge cases.
    • Fix: Test with common exceptions (e.g., HttpException, LogicException) before relying on it.

Debugging Tips

  • Log AI Responses: Enable debug mode to log prompts/responses:
    # config/packages/aierror_explained.yaml
    ai_error_explained:
        debug: true
    
  • Mock OpenAI: For testing, mock the OpenAI\Client service:
    // tests/Service/AIErrorServiceTest.php
    $client = $this->createMock(OpenAI\Client::class);
    $client->method('chat')->willReturn(['choices' => [['message' => ['content' => 'Mock fix']]]]);
    $service = new AIErrorService($client, $cache);
    
  • Check Cache: Verify cache entries with:
    bin/console cache:pool:list
    bin/console cache:pool:clear aierror_explained
    

Extension Points

  1. Custom Error Handling: Override AIErrorHandler to exclude specific exceptions:

    // src/EventSubscriber/AIErrorSubscriber.php
    public function onKernelException(GetResponseForExceptionEvent $event) {
        $exception = $event->getThrowable();
        if ($exception instanceof \Symfony\Component\HttpKernel\Exception\NotFoundHttpException) {
            return; // Skip AI for 404s
        }
        // ... rest of logic
    }
    
  2. Prompt Customization: Extend AIErrorService to add domain-specific context:

    public function generatePrompt(Throwable $exception): string {
        $basePrompt = parent::generatePrompt($exception);
        return "{$basePrompt}\n\nNote: This is a Symfony 6.4 app with Doctrine ORM.";
    }
    
  3. Alternative AI Providers: Replace OpenAI with a local LLM (e.g., Hugging Face) by injecting a custom AIClientInterface:

    services:
        ACSEO\AIErrorExplainedBundle\Service\AIClientInterface: '@your_local_ai_service'
    
  4. Error Page Styling: Customize the Twig template (templates/error.html.twig) to highlight AI suggestions:

    <div class="ai-suggestion">
        <h3>AI Suggests:</h3>
        {{ ai_suggestion|raw }}
    </div>
    
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.
babenkoivan/elastic-client
innmind/static-analysis
innmind/coding-standard
datacore/hub-sdk
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony
develia/geo-bundle
dreamzy/livewire-charts
touchestate-sdk/php-sdk
22h/doctrine-garbage-collection-bundle
agtp/agtp-php
agtp/mod-php
splash/sonata-admin
splash/metadata
splash/openapi
splash/scopes
splash/toolkit
testo/output-teamcity
testo/bridge-symfony