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

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

Integration Approach

Stack Fit

  • Laravel + Symfony Components:

    • Symfony HttpClient: The package uses Symfony’s HttpClient (v7.3+), which can be integrated into Laravel via:
      • The symfony/http-client-bundle (if using Symfony bundles).
      • Laravel’s Service Container to bind Symfony’s HttpClient as a singleton:
        $this->app->singleton(\Symfony\Contracts\HttpClient\HttpClientInterface::class, fn () =>
            \Symfony\Component\HttpClient\CurlHttpClient::create([
                'headers' => ['Authorization' => 'Bearer ' . config('services.replicate.token')],
            ])
        );
        
      • Alternative: Use Laravel’s built-in Guzzle client by creating a wrapper adapter for Symfony’s HttpClient interface (minimal effort for one-off integrations).
    • Dependency Injection (DI): The package follows Symfony’s DI patterns, which Laravel’s container supports natively. Bind the ReplicateClient as a service:
      $this->app->bind(\Symfony\Component\Ai\Replicate\ReplicateClient::class, function ($app) {
          return new \Symfony\Component\Ai\Replicate\ReplicateClient(
              $app->make(\Symfony\Contracts\HttpClient\HttpClientInterface::class),
              config('services.replicate.token')
          );
      });
      
    • Event System: Symfony AI emits events (e.g., ModelPredicted) that can be bridged to Laravel’s events using a listener:
      use Symfony\Component\Ai\Event\ModelPredicted;
      use Symfony\Component\EventDispatcher\EventSubscriberInterface;
      
      class ReplicateEventSubscriber implements EventSubscriberInterface
      {
          public static function getSubscribedEvents(): array
          {
              return [
                  ModelPredicted::class => 'onModelPredicted',
              ];
          }
      
          public function onModelPredicted(ModelPredicted $event): void
          {
              event(new \App\Events\ReplicatePredictionCompleted($event->getResult()));
          }
      }
      
      Register the subscriber in AppServiceProvider:
      public function boot()
      {
          $this->app->make(\Symfony\Component\EventDispatcher\EventDispatcherInterface::class)
              ->addSubscriber(new ReplicateEventSubscriber());
      }
      
    • Configuration: Store Replicate API tokens and model configurations in config/services.php:
      'replicate' => [
          'token' => env('REPLICATE_API_TOKEN'),
          'default_model' => 'stable-diffusion:abc123',
          'timeout' => 30, // seconds
      ],
      
  • Laravel-Specific Enhancements:

    • Queues: For async batch processing, wrap the client in a Laravel Job:
      namespace App\Jobs;
      
      use Illuminate\Bus\Queueable;
      use Illuminate\Contracts\Queue\ShouldQueue;
      use Symfony\Component\Ai\Replicate\ReplicateClient;
      
      class GenerateImageJob implements ShouldQueue
      {
          use Queueable;
      
          public function handle(ReplicateClient $client)
          {
              $result = $client->predict('stable-diffusion:abc123', ['prompt' => 'Laravel logo']);
              // Store result in DB or S3
          }
      }
      
    • Caching: Cache model predictions or API responses using Laravel’s cache:
      $cacheKey = "replicate:prompt:{$prompt}";
      $result = cache()->remember($cacheKey, now()->addHours(1), function () use ($client, $prompt) {
          return $client->predict($model, ['prompt' => $prompt]);
      });
      
    • Validation: Use Laravel’s Form Requests or Validator to sanitize inputs before passing them to Replicate:
      use Illuminate\Foundation\Http\FormRequest;
      
      class GenerateImageRequest extends FormRequest
      {
          public function rules(): array
          {
              return [
                  'prompt' => 'required|string|max:1000',
                  'model' => 'sometimes|string|in:stable-diffusion,llama2',
              ];
          }
      }
      

Migration Path

  1. Phase 1: Proof of Concept (1–2 weeks)

    • Goal: Validate the package’s feasibility for a single use case (e.g., image generation).
    • Steps:
      • Install dependencies:
        composer require symfony/ai-replicate-platform symfony/http-client
        
      • Configure config/services.php with Replicate API token.
      • Implement a controller route to test predictions:
        use Symfony\Component\Ai\Replicate\ReplicateClient;
        
        route('generate-image', function (ReplicateClient $client) {
            $result = $client->predict('stable-diffusion:abc123', ['prompt' => request('prompt')]);
            return response()->json($result);
        });
        
      • Test with manual API calls (e.g., Postman) and monitor:
        • Latency (target: <2s for interactive use).
        • Cost (track Replicate usage via dashboard).
        • Error rates (e.g., rate limits, invalid inputs).
  2. Phase 2: Feature Integration (2–4 weeks)

    • Goal: Integrate the package into one product feature (e.g., AI-powered thumbnails for blog posts).
    • Steps:
      • Wrap the client in a Laravel service (App\Services\ReplicateService) to handle:
        • Retries for failed requests.
        • Input validation.
        • Output processing (e.g., storing images in S3).
      • Add caching for frequent predictions (e.g., cached for 1 hour).
      • Implement error handling (e.g., log failures to Sentry, notify users of delays).
      • Example Service:
        namespace App\Services;
        
        use Symfony\Component\Ai\Replicate\ReplicateClient;
        use Illuminate\Support\Facades\Log;
        
        class ReplicateService
        {
            public function __construct(private ReplicateClient $client) {}
        
            public function generateImage(string $prompt, string $model = 'stable-diffusion:abc123')
            {
                try {
                    $result = $this->client->predict($model, ['prompt' => $prompt]);
                    return $this->processResult($result);
                } catch (\Exception $e) {
                    Log::error("Replicate failed: {$e->getMessage()}");
                    throw new \RuntimeException('Image generation failed. Please try again later.');
                }
            }
        
            private function processResult($result): string
            {
                // Save to S3, return URL, etc.
                return "https://bucket.s3.example.com/{$result['output'][0]}";
            }
        }
        
      • Bind the service in AppServiceProvider:
        $this->app->bind(ReplicateService::class, function ($app) {
            return new ReplicateService($app->make(ReplicateClient::class));
        });
        
  3. Phase 3: Scaling and Abstraction (3–6 weeks)

    • Goal: Generalize the integration for multiple use cases (e.g., text generation, multimodal models) and optimize for scale.
    • Steps:
      • Adopt Symfony AI’s Provider Abstraction:
        • Implement a ReplicateProvider to route models dynamically:
          use Symfony\Component\Ai\Provider\ProviderInterface;
          
          class ReplicateProvider implements ProviderInterface
          {
              public function getModel(string $modelName): string
              {
                  return match ($modelName) {
                      'image' => 'stable-diffusion:abc123',
                      'text' => 'llama2:456def',
                      default => throw new \InvalidArgumentException("Unknown model: {$modelName}"),
                  };
              }
          }
          
        • Bind the provider to Symfony’s event dispatcher.
      • Add Queue Support:
        • Convert synchronous calls to Laravel Queues for batch processing:
          $job = new GenerateImageJob($prompt);
          dispatch($job);
          
      • Implement Monitoring:
        • Log prediction metrics (latency, cost, model usage) to a database or observability tool (e.g., Datadog).
        • Set up alerts for cost thresholds or error rates.
      • Optimize Costs:
        • Cache predictions aggressively for static content.
        • Use Replicate’s "Hosted Inference" for high-volume use cases (if latency is acceptable).

Compatibility

  • PHP Version: Requires PHP 8.2+ (aligned with Laravel 10/11). No conflicts expected.
  • Laravel Version: Compatible with Laravel 10/11 (Symfony 6/7 components). For older Laravel versions, use a composer override for Symfony dependencies:
    "extra": {
        "laravel": {
            "
    
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