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

Laravelai Laravel Package

muradbdinfo/laravelai

Unified AI chat interface for Laravel with pluggable providers (Ollama, OpenAI/ChatGPT, Anthropic/Claude, DeepSeek). Includes quick setup, configuration, real-world examples, chat app integration, API reference, and built-in RAG support.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require muradbdinfo/laravelai
    php artisan vendor:publish --provider="Muradbdinfo\LaravelAI\LaravelAIServiceProvider" --tag="config"
    
    • Publishes the config file at config/laravelai.php.
  2. Environment Configuration: Add your API keys to .env (e.g., OPENAI_API_KEY, OLLAMA_BASE_URL). Configure the default provider in config/laravelai.php:

    'default' => env('AI_PROVIDER', 'openai'),
    
  3. First Use Case: Use the facade to send a prompt:

    use Muradbdinfo\LaravelAI\Facades\LaravelAI;
    
    $response = LaravelAI::send('What is Laravel?');
    dd($response);
    
    • Returns a structured response with choices, usage, and metadata.

Key Files to Review

  • Config: config/laravelai.php (providers, defaults, rate limits).
  • Facade: app/Facades/LaravelAI.php (primary interface).
  • Providers: app/Providers/LaravelAIServiceProvider.php (service binding).

Implementation Patterns

Core Workflows

1. Provider Switching

Dynamically switch AI providers at runtime:

// Use Ollama locally
$response = LaravelAI::use('ollama')->send('Explain Laravel Eloquent');

// Fallback to OpenAI if Ollama fails
LaravelAI::fallbackTo('openai');

2. Streaming Responses

Handle streaming responses for real-time UIs:

LaravelAI::stream('Generate a poem about Laravel', function ($chunk) {
    echo $chunk->content;
});

3. Custom Models

Override default models per provider:

LaravelAI::use('openai')->withModel('gpt-4')->send('Analyze this code...');

4. Rate Limiting

Respect API limits with built-in retries:

LaravelAI::withRetry(3)->send('Complex query...');

Integration Tips

With Laravel Queues

Offload AI calls to queues to avoid timeouts:

LaravelAI::dispatch('Generate report')->onQueue('ai');

With Vue.js

Use Laravel Echo for real-time updates:

// Frontend (Vue)
Echo.channel('ai-responses')
    .listen('AiResponseEvent', (response) => {
        console.log(response);
    });

With Testing

Mock responses in tests:

LaravelAI::fake()->shouldReturn([
    'choices' => [['message' => ['content' => 'Mocked response']]],
]);

Gotchas and Tips

Pitfalls

  1. API Key Leaks:

    • Never commit .env or hardcode keys. Use Laravel’s env() or .env files.
    • Fix: Validate keys in config/laravelai.php:
      'validate_keys' => true,
      
  2. Rate Limits:

    • Providers like OpenAI throttle requests. Use withRetry() or implement exponential backoff.
    • Tip: Log usage metrics in config/laravelai.php:
      'log_usage' => true,
      
  3. Streaming Quirks:

    • Some providers (e.g., Ollama) may not support streaming. Check the provider’s docs.
    • Workaround: Use chunk() for partial responses:
      $response = LaravelAI::stream('...')->chunk();
      
  4. Model Availability:

    • Not all models are available across providers. Validate in config/laravelai.php:
      'valid_models' => [
          'openai' => ['gpt-3.5-turbo', 'gpt-4'],
          'ollama' => ['llama3'],
      ],
      

Debugging

  1. Enable Logging:

    LaravelAI::debug(true); // Logs all requests/responses to storage/logs/laravelai.log
    
  2. Validate Responses:

    • Use LaravelAI::lastResponse() to inspect raw API responses:
      $last = LaravelAI::lastResponse();
      dd($last->raw);
      
  3. Provider-Specific Errors:

    • Check config/laravelai.php for provider-specific error handling:
      'exceptions' => [
          'openai' => \Muradbdinfo\LaravelAI\Exceptions\OpenAIException::class,
      ],
      

Extension Points

  1. Custom Providers: Extend the base Provider class to add support for new AI services:

    namespace App\Providers;
    
    use Muradbdinfo\LaravelAI\Contracts\Provider;
    
    class CustomProvider implements Provider {
        public function send($prompt, array $options = []) {
            // Custom logic
        }
    }
    

    Register in config/laravelai.php:

    'providers' => [
        'custom' => \App\Providers\CustomProvider::class,
    ],
    
  2. Middleware: Add middleware to modify prompts/responses:

    LaravelAI::middleware(function ($prompt, $next) {
        return $next($prompt . " Add this context: ...");
    });
    
  3. Events: Listen for AI events (e.g., AiRequestSent, AiResponseReceived):

    LaravelAI::listen(function ($event) {
        Log::info('AI Event:', $event->data);
    });
    
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.
nasirkhan/laravel-sharekit
directorytree/privacy-filter-classifier
directorytree/privacy-filter
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