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.
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.
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"
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'];
}
}
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')
)
);
});
}
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]);
}
}
ReplicateService from a PostController.posts.thumbnail_url).$post->thumbnail_url = $replicate->generateImage("Thumbnail for {$post->title}");
$post->save();
ReplicateClient to trigger predictions with structured input.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);
}
Provider interface to route models dynamically.// 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' => '...']);
// 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
}
}
ModelPredicted) to extend functionality.// 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(),
]);
});
HTTP Client:
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()
);
});
Configuration:
// config/services.php
'replicate' => [
'token' => env('REPLICATE_API_TOKEN'),
'timeout' => 30, // seconds
];
Exception Handling:
catch (\Symfony\Component\Ai\Exception\AiException $e) {
throw new \App\Exceptions\ReplicateException(
$e->getMessage(),
$e->getCode(),
$e
);
}
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));
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);
}
Synchronous API Calls:
Cost Overruns:
Model Versioning:
stable-diffusion:v1.0) and monitor Replicate’s changelog.Error Handling Gaps:
How can I help you explore Laravel packages today?