Weave 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

Ai Replicate Platform Laravel Package

symfony/ai-replicate-platform

Symfony AI bridge for the Replicate Platform. Provides integration with Replicate’s HTTP API to create and manage predictions from Symfony apps. Includes links to Replicate docs and points contributors to the main symfony/ai repository for issues and PRs.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Install the Package:

    composer require symfony/ai-replicate-platform
    

    Ensure your project uses PHP 8.2+ and Symfony HTTP Client (v7.3+). Laravel 10+ is recommended due to Symfony component compatibility.

  2. Configure Replicate API Token: Add your token to .env:

    REPLICATE_API_TOKEN=your_token_here
    

    Publish the config (if using Symfony’s config system):

    php artisan vendor:publish --provider="Symfony\Component\Ai\Replicate\ReplicateClientProvider"
    
  3. First Prediction: Create a service to wrap the client (Laravel-style):

    // app/Services/ReplicateService.php
    namespace App\Services;
    
    use Symfony\Component\Ai\Replicate\ReplicateClient;
    use Symfony\Contracts\HttpClient\HttpClientInterface;
    
    class ReplicateService
    {
        public function __construct(
            private ReplicateClient $client
        ) {}
    
        public function generateImage(string $prompt): string
        {
            $result = $this->client->predict('stable-diffusion:abc123', [
                'prompt' => $prompt,
                'width' => 512,
                'height' => 512,
            ]);
            return $result->getOutput()['url'];
        }
    }
    
  4. Bind the Service: Register the service in AppServiceProvider:

    public function register()
    {
        $this->app->singleton(ReplicateService::class, function ($app) {
            return new ReplicateService(
                new ReplicateClient(
                    $app->make(HttpClientInterface::class),
                    config('services.replicate.token')
                )
            );
        });
    }
    
  5. Use in a Controller:

    use App\Services\ReplicateService;
    
    class ImageController extends Controller
    {
        public function generate(ReplicateService $replicate)
        {
            $imageUrl = $replicate->generateImage('A Laravel mascot');
            return response()->json(['url' => $imageUrl]);
        }
    }
    

First Use Case: Dynamic Image Generation

  • Scenario: Generate thumbnails for blog posts on-the-fly.
  • Steps:
    1. Call ReplicateService from a PostController.
    2. Store the generated image URL in the database (e.g., posts.thumbnail_url).
    3. Cache responses in Redis to avoid redundant API calls.
  • Example:
    $post->thumbnail_url = $replicate->generateImage("Thumbnail for {$post->title}");
    $post->save();
    

Implementation Patterns

Core Workflows

1. Model Prediction Workflow

  • Pattern: Use the ReplicateClient to trigger predictions with structured input.
  • Example: Text-to-image generation with error handling:
    try {
        $result = $client->predict('stable-diffusion:abc123', [
            'prompt' => 'Laravel logo in a fantasy style',
            'num_outputs' => 1,
        ]);
        $imageUrl = $result->getOutput()['url'];
    } catch (\Symfony\Component\Ai\Exception\AiException $e) {
        Log::error("Replicate prediction failed: {$e->getMessage()}");
        throw new \RuntimeException("Failed to generate image.", 500);
    }
    

2. Provider Abstraction (Multi-Model Support)

  • Pattern: Leverage Symfony’s Provider interface to route models dynamically.
  • Example: Switch between Replicate and Hugging Face providers:
    // config/ai.php
    'providers' => [
        'replicate' => [
            'class' => \Symfony\Component\Ai\Replicate\ReplicateProvider::class,
            'models' => [
                'stable-diffusion' => 'stable-diffusion:abc123',
                'llama' => 'llama2:456def',
            ],
        ],
    ];
    
    // In a service:
    $provider = $this->app->make(\Symfony\Component\Ai\ProviderInterface::class);
    $result = $provider->predict('stable-diffusion', ['prompt' => '...']);
    

3. Queue-Based Batch Processing

  • Pattern: Offload predictions to Laravel Queues to avoid timeouts and reduce costs.
  • Example:
    // Dispatch a job
    GenerateImageJob::dispatch($postId, 'A fantasy landscape');
    
    // Job class
    class GenerateImageJob implements ShouldQueue
    {
        use Dispatchable, InteractsWithQueue, Queueable;
    
        public function handle(ReplicateService $replicate)
        {
            $imageUrl = $replicate->generateImage($this->prompt);
            // Update database or trigger notifications
        }
    }
    

4. Event-Driven Extensions

  • Pattern: Subscribe to Symfony AI events (e.g., ModelPredicted) to extend functionality.
  • Example: Log predictions to a custom table:
    // In a service provider
    $this->app->make(\Symfony\Component\Ai\EventDispatcher\EventDispatcherInterface::class)
        ->addListener(\Symfony\Component\Ai\Event\ModelPredicted::class, function ($event) {
            \App\Models\AiPrediction::create([
                'model' => $event->getModel(),
                'input' => $event->getInput(),
                'output' => $event->getOutput(),
            ]);
        });
    

Integration Tips

Laravel-Specific Adaptations

  1. HTTP Client:

    • Replace Symfony’s HttpClient with Laravel’s Guzzle by binding it to the container:
      $this->app->singleton(HttpClientInterface::class, function () {
          return new \Symfony\Component\HttpClient\GuzzleClient(
              new \GuzzleHttp\Client()
          );
      });
      
  2. Configuration:

    • Use Laravel’s config system to centralize Replicate settings:
      // config/services.php
      'replicate' => [
          'token' => env('REPLICATE_API_TOKEN'),
          'timeout' => 30, // seconds
      ];
      
  3. Exception Handling:

    • Convert Symfony AI exceptions to Laravel exceptions:
      catch (\Symfony\Component\Ai\Exception\AiException $e) {
          throw new \App\Exceptions\ReplicateException(
              $e->getMessage(),
              $e->getCode(),
              $e
          );
      }
      

Performance Optimization

  • Caching: Use Laravel’s cache to store prediction results (e.g., for static images):

    $cacheKey = "replicate:{$prompt}";
    return Cache::remember($cacheKey, now()->addHours(1), function () use ($prompt) {
        return $replicate->generateImage($prompt);
    });
    
  • Rate Limiting: Implement Laravel’s rate limiter to avoid hitting Replicate’s API limits:

    use Illuminate\Support\Facades\RateLimiter;
    
    RateLimiter::hit('replicate-predictions', 100, now()->addMinutes(1));
    

Testing

  • Mock the Client: Use Laravel’s mocking to test services without hitting the API:

    $this->mock(ReplicateClient::class, function ($mock) {
        $mock->shouldReceive('predict')
             ->once()
             ->andReturn(new \Symfony\Component\Ai\Replicate\ReplicateResult(['url' => 'fake-url.jpg']));
    });
    
  • Unit Test Example:

    public function test_image_generation()
    {
        $service = new ReplicateService($this->mockClient);
        $url = $service->generateImage('Test prompt');
        $this->assertEquals('fake-url.jpg', $url);
    }
    

Gotchas and Tips

Pitfalls

  1. Synchronous API Calls:

    • Issue: Replicate’s API is synchronous, which can cause timeouts for slow models (e.g., large image generation).
    • Fix: Use Laravel Queues or serverless functions (e.g., Vapor) to handle long-running predictions.
  2. Cost Overruns:

    • Issue: Replicate charges per prediction ($0.002–$0.02). Unoptimized usage can lead to unexpected costs.
    • Fix:
      • Implement caching for static outputs.
      • Use batch processing (e.g., generate 10 images in a single API call where possible).
      • Set budget alerts (e.g., via AWS Cost Explorer or a custom script).
  3. Model Versioning:

    • Issue: Models may change or deprecate, breaking your code.
    • Fix: Pin model versions in your code (e.g., stable-diffusion:v1.0) and monitor Replicate’s changelog.
  4. Error Handling Gaps:

    • **
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.
adachsoft/changelog-linter
adachsoft/collection
payerurl/telegrambot-crypto-payment-instant-payout
dskripchenko/laravel-hybrid-search
riorizkyrainey/lara-ced
mehedimi/static-vel
zharp/zharp
nonsapiens/bigquery-model-sync
lgu-bayambang-ict-office/lgu-laravel-development-standards
andydefer/laravel-support
se7enxweb/flysystem
lampwick/laravel
jeslage/statamic-emojis
micahdshackelford/rmap-laravel
draftsmaninc/draftsman
square-bit/laravel-volition
himito/laravel-mailman
htinlynn/genius-helper
maco-studios/hephaestus
adachsoft/php-code-style