Build an AI-Powered Text Summarizer with Laravel and Livewire: A Step-by-Step Guide

Building an AI-Powered Text Summarizer with Laravel and Livewire

In today’s fast-paced digital world, the ability to quickly digest large amounts of information is crucial. This tutorial will guide you through creating an AI-powered text summarizer using Laravel and Livewire, perfect for developers looking to expand their skills in web development and AI integration.

Table of Contents

What You’ll Learn

  • Setting up a Laravel project with Livewire
  • Creating a responsive single-page application
  • Implementing basic text summarization logic
  • Integrating OpenAI’s GPT model for advanced summarization
  • Handling user input and displaying results dynamically

Prerequisites

  • Basic knowledge of PHP and Laravel
  • Familiarity with HTML, CSS, and JavaScript
  • Composer installed on your system
  • An OpenAI API key (for the advanced version)

Project Setup

Let’s start by setting up our Laravel project:

  • Create a new Laravel project:

    composer create-project laravel/laravel ai-summarizer
    
  • Navigate to the project directory:

    cd ai-summarizer
    
  • Install Livewire:

    composer require livewire/livewire
    
  • Create a new Livewire component:

    php artisan make:livewire TextSummarizer
    

Building the User Interface

Our summarizer will have a clean, user-friendly interface. Let’s create it using Tailwind CSS, which comes pre-installed with Laravel.

Update your resources/views/livewire/text-summarizer.blade.php:

				
					<div class="max-w-4xl mx-auto p-6">
    <h1 class="text-3xl font-bold mb-6">AI Text Summarizer</h1>
    
    <div class="mb-4">
        <textarea wire:model="inputText" class="w-full h-40 p-2 border rounded" placeholder="Paste your text here..."></textarea>
    </div>
    
    <div class="mb-4">
        <label class="block mb-2">Summary Length:</label>
        <select wire:model="summaryLength" class="w-full p-2 border rounded">
            <option value="3">3 sentences</option>
            <option value="5">5 sentences</option>
            <option value="7">7 sentences</option>
        </select>
    </div>
    
    <button wire:click="summarize" class="bg-blue-500 text-white px-4 py-2 rounded hover:bg-blue-600">Summarize</button>
    
    @if($summary)
        <div class="mt-6 p-4 bg-gray-100 rounded">
            <h2 class="text-xl font-bold mb-2">Summary:</h2>
            <p>{{ $summary }}</p>
        </div>
    @endif
</div>
				
			

Implementing Basic Summarization Logic

For our basic version, we’ll implement a simple summarization algorithm based on sentence importance. Update your app/Http/Livewire/TextSummarizer.php:

				
					<?php

namespace App\Http\Livewire;

use Livewire\Component;

class TextSummarizer extends Component
{
    public $inputText = '';
    public $summaryLength = 3;
    public $summary = '';

    public function summarize()
    {
        $sentences = preg_split('/(?<=[.!?])\s+/', $this->inputText, -1, PREG_SPLIT_NO_EMPTY);
        $sentenceScores = [];

        foreach ($sentences as $index => $sentence) {
            $score = 0;
            $words = str_word_count($sentence, 1);
            $score += strlen($sentence) * 0.1;
            $score += count($words) * 0.2;
            $score += ($index === 0 || $index === count($sentences) - 1) ? 2 : 0;
            $sentenceScores[$index] = $score;
        }

        arsort($sentenceScores);
        $topSentences = array_slice($sentenceScores, 0, $this->summaryLength, true);
        ksort($topSentences);

        $this->summary = implode(' ', array_intersect_key($sentences, $topSentences));
    }

    public function render()
    {
        return view('livewire.text-summarizer');
    }
}
				
			

This basic algorithm scores sentences based on length, word count, and position, then selects the top-scoring sentences for the summary.

Enhancing with OpenAI Integration

To take our summarizer to the next level, let’s integrate OpenAI’s GPT model. First, install the necessary packages:

composer require openai-php/client
composer require guzzlehttp/guzzle

Update your TextSummarizer.php component:

				
					<?php

namespace App\Http\Livewire;

use Livewire\Component;
use OpenAI;

class TextSummarizer extends Component
{
    public $inputText = '';
    public $summaryLength = 3;
    public $summary = '';

    public function summarize()
    {
        $ApiKey = getenv('OPENAI_API_KEY');
        $client = OpenAI::client($ApiKey);

        $response = $client->chat()->create([
            'model' => 'gpt-3.5-turbo',
            'messages' => [
                ['role' => 'system', 'content' => "You are a helpful assistant that summarizes text."],
                ['role' => 'user', 'content' => "Summarize the following text in {$this->summaryLength} sentences: {$this->inputText}"],
            ],
        ]);

        $this->summary = $response->choices[0]->message->content;
    }

    public function render()
    {
        return view('livewire.text-summarizer');
    }
}
				
			

Don’t forget to add your OpenAI API key to your .env file:

OPENAI_API_KEY=your_api_key_here

Error Handling and Validation

To improve user experience, let’s add some error handling and input validation:

				
					public function summarize()
{
    $this->validate([
        'inputText' => 'required|min:50',
    ]);

    try {
        // OpenAI API call here
    } catch (\Exception $e) {
        session()->flash('error', 'An error occurred while summarizing the text. Please try again.');
    }
}
				
			

Comparing Basic and AI-Powered Summarization

Let’s compare the results of our basic algorithm with the AI-powered version:

FeatureBasic AlgorithmAI-Powered (OpenAI)
SpeedFastDepends on API response time
QualityExtracts existing sentencesGenerates coherent summaries
CustomizationLimited to sentence selectionCan be fine-tuned with prompts
CostFreeRequires API credits
Offline UseYesRequires internet connection

How to Use the AI Text Summarizer?

Total Time Needed: 5 minutes
Total Cost: 69 USD

Required Tools:

- A Computer.
- Internet Connection.
- Web browser

Things Needed?

Text to be summarized

Steps to configure the How-to Schema widget:

Step 1 : Access the summarizer
Open your web browser and navigate to the summarizer page
Step 2 : Input your text
Paste or type your text into the large text area provided
Step 3 : Choose summary length
Select the desired number of sentences for your summary from the dropdown menu
Step 4 : Generate summary
Click the "Summarize" button to process your text
Step 5 : Review the results
Read the generated summary displayed below the input area

FAQ

The AI-powered summarizer using OpenAI's GPT model is generally quite accurate and can provide coherent, contextually relevant summaries. However, its performance may vary depending on the complexity and subject matter of the input text.

The basic algorithm is language-agnostic and can work with any language that uses sentence-ending punctuation. The AI-powered version using OpenAI can handle multiple languages, but performance may vary across different languages.

For the basic algorithm, there's no strict limit, but very long texts may take longer to process. For the AI-powered version, there are token limits imposed by the OpenAI API, typically around 4000 tokens (roughly 3000 words) for input and output combined.

For better results, try to use well-structured text with clear paragraphs. You can also experiment with different summary lengths to find the optimal balance between brevity and informativeness.

By following this tutorial, you’ve created a powerful AI-powered text summarizer that combines the simplicity of Laravel and Livewire with the advanced capabilities of OpenAI’s language models. This project serves as an excellent starting point for exploring more complex AI integrations in web applications.

See also
Building a Real-Time Weather Dashboard with Laravel Reverb and Vue.js

Leave a Reply

Your email address will not be published. Required fields are marked *

Send this to a friend