Adding AI to your web apps can really boost how well they work and how users like them. A great way to achieve this is by combining Cloudflare Workers AI with Laravel Livewire. This post will guide you on how to set up and use Cloudflare Workers AI in a Laravel Livewire application to make a smart and changing web application.
In this blog post, we will see an example where you can upload an image and convert that image to text using the Cloudflare Workers AI model Image to Text using @cf/llava-hf/llava-1.5-7b-hf, and then analyze the sentiment of that text using another Cloudflare Workers AI model, @cf/huggingface/distilbert-sst-2-int8.
Using these powerful AI models and Livewire's reactive components, we'll build a seamless workflow that transforms and analyzes user-uploaded images in real-time.
What is Cloudflare Workers AI?
Cloudflare Workers is a serverless platform. This gives you fast response times and high performance. Cloudflare has now added AI features to Workers and we will use those Workers AI using REST API.
What is Laravel Livewire?
Laravel Livewire is a framework that works with all parts of Laravel. It helps you make dynamic interfaces easy, while still using Laravel. With Livewire, you can build reactive dynamic interfaces using clear expressive PHP code.
Prerequisites
Before we start, make sure you have the following:
A Laravel 11 application set up
Composer installed
NPM installed
Cloudflare account
Step 1: Setting Up Cloudflare Workers
1. Sign in to Cloudflare: If you don't have an account, you must create one. 2. Generate an API Key: Go to the API Tokens section under My Profile. Generate a new API key with appropriate permissions to access Workers AI functionalities. (use a template for Workers AI). or Visit this link Create API Token. 3. Get Account ID: to use Workers AI REST API to make API calls.
Step 2: Setup env variables
Add this to your .env file.
CLOUDFLARE_API_KEY=CLOUDFLARE_ACCOUNT_ID=
Create a new config file cloudflare.php to use these env variables.
<?phpnamespaceApp\Livewire;useLivewire\Component;useLivewire\WithFileUploads;useIlluminate\Support\Facades\Http;classUploadImageextendsComponent{useWithFileUploads;public$file="";public$image_url;publicfunctionrender(){returnview('livewire.upload-image');}publicfunctionuploadImage(){$this->validate(['file'=>'image|max:1024',// 1MB Max]);$image=$this->file;$imagePath=$image->store('images','public');$this->image_url='/storage/'.$imagePath;// We are using session to store this datasession()->put('image_url',$this->image_url);$info=$this->createTextFromImg($this->file);$sentiments=$this->sentimentAnalysis($info['result']['description']);returnredirect()->back()->with(['text'=>$info['result']['description'],'sentiments'=>$sentiments]);}publicfunctionsentimentAnalysis($text){try{$authorizationToken=config('cloudflare.api_key');$accountId=config('cloudflare.account_id');$url='https://api.cloudflare.com/client/v4/accounts/'.$accountId.'/ai/run/@cf/huggingface/distilbert-sst-2-int8';$response=Http::withToken($authorizationToken)->post($url,['text'=>$text]);returnjson_decode($response->getBody(),true);}catch(\Exception$e){returnresponse()->json(['error'=>$e->getMessage()],500);}}publicfunctioncreateTextFromImg($img){try{if(!empty($img)){$imageData=file_get_contents($img->getRealPath());$imageArray=unpack('C*',$imageData);// Prepare input for the AI service$input=['image'=>array_values($imageArray),'prompt'=>'Generate a caption for this image by extracting all the details.','max_tokens'=>512,];$authorizationToken=config('cloudflare.api_key');$accountId=config('cloudflare.account_id');$baseURL=config('cloudflare.url');$url=$baseURL.$accountId.'/ai/run/@cf/llava-hf/llava-1.5-7b-hf';$response=Http::withToken($authorizationToken)->post($url,$input);if($response->successful()){return$response->json();}else{return['error'=>'Failed to get response from AI service'];}}}catch(\Exception$e){returnresponse()->json(['error'=>$e->getMessage()],500);}}publicfunctiondeleteExistingImage(){if(session()->get('image_url')){$imagePath=storage_path('app/public/'.basename(session()->get('image_url')));if(file_exists($imagePath)){unlink($imagePath);}session()->forget('image_url');}}}
WithFileUploads trait helps developers manage file uploads in Livewire components. This trait makes it easier to upload files by taking care of file storage and checking. It allows developers to handle file uploads in real-time without refreshing the page.
Conclusion
In summary, combining Cloudflare Workers AI with Laravel Livewire allows us to enhance our web applications smarter and interactive with trends in AI stuff.
Using models like @cf/llava-hf/llava-1.5-7b-hf to turn images into text and @cf/huggingface/distilbert-sst-2-int8 to figure out how people feel by analyzing their sentiments, developers can build seamless application. It's a good place to start if you want to create new apps that people find easy to use. Check out this strong combo and see what cool stuff you can make next!