Introduction
In this tutorial, we will learn how to build an AI chatbot using Laravel and Rubix ML. This chatbot will process user messages and provide intelligent responses using machine learning. Rubix ML is a powerful PHP-based machine learning library that makes it easy to implement AI-driven applications.
This step-by-step guide will cover:
- Installing Laravel and Rubix ML
- Training the chatbot with sample data
- Creating a chatbot API
- Building a simple UI to interact with the chatbot
Let’s get started!
Step 1: Install Laravel and Rubix ML
1.1 Install Laravel
First, set up a new Laravel project:
composer create-project laravel/laravel chatbot
cd chatbot
1.2 Install Rubix ML
Next, install the Rubix ML package:
composer require rubix/ml
This will allow us to use machine learning models within Laravel.
Step 2: Create a Chatbot Model
We will now create a chatbot service that processes user messages and provides responses.
2.1 Create Chatbot Service
Run the following command to create a service file:
php artisan make:service ChatbotService
Open app/Services/ChatbotService.php
and add:
<?php
namespace App\Services;
use Rubix\ML\Classifiers\KNearestNeighbors;
use Rubix\ML\Datasets\Labeled;
use Rubix\ML\Persisters\Filesystem;
use Rubix\ML\PersistentModel;
class ChatbotService
{
protected $modelPath = 'storage/chatbot_model.rbx';
public function train()
{
$samples = [
['hello'], ['hi'], ['how are you'], ['who are you'], ['what is Laravel'],
['tell me a joke'], ['bye'], ['goodbye'], ['thanks']
];
$labels = [
'Hello! How can I assist you?',
'Hi there!',
'I am an AI chatbot, always ready to assist!',
'I am a chatbot built using Rubix ML in Laravel.',
'Laravel is a PHP framework for web applications.',
'Sure! Why don’t scientists trust atoms? Because they make up everything!',
'Goodbye! Have a great day!',
'Take care!',
'You’re welcome!'
];
$dataset = new Labeled($samples, $labels);
$estimator = new PersistentModel(new KNearestNeighbors(3), new Filesystem($this->modelPath));
$estimator->train($dataset);
$estimator->save();
}
public function getResponse($message)
{
if (!file_exists($this->modelPath)) {
return "I am not trained yet. Please train me first.";
}
$estimator = PersistentModel::load(new Filesystem($this->modelPath));
return $estimator->predict([$message]);
}
}
Step 3: Create a Chatbot API
We will now create a chatbot controller.
3.1 Generate Controller
Run:
php artisan make:controller ChatbotController
Open app/Http/Controllers/ChatbotController.php
and add:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Services\ChatbotService;
class ChatbotController extends Controller
{
protected $chatbot;
public function __construct(ChatbotService $chatbot)
{
$this->chatbot = $chatbot;
}
public function train()
{
$this->chatbot->train();
return response()->json(['message' => 'Chatbot trained successfully!']);
}
public function chat(Request $request)
{
$message = $request->input('message');
$response = $this->chatbot->getResponse($message);
return response()->json(['response' => $response]);
}
}
3.2 Define Routes
Edit routes/web.php
:
use App\Http\Controllers\ChatbotController;
Route::get('/train-chatbot', [ChatbotController::class, 'train']);
Route::post('/chat', [ChatbotController::class, 'chat']);
Step 4: Build a Simple Chatbot UI
Create a new Blade template: resources/views/chatbot.blade.php
<!DOCTYPE html>
<html>
<head>
<title>Laravel AI Chatbot</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
<h2>AI Chatbot</h2>
<div id="chat-box">
<p><b>Bot:</b> Hello! How can I help you?</p>
</div>
<input type="text" id="message" placeholder="Type your message...">
<button onclick="sendMessage()">Send</button>
<script>
function sendMessage() {
let message = $("#message").val();
$("#chat-box").append(`<p><b>You:</b> ${message}</p>`);
$.post("/chat", { message: message }, function(data) {
$("#chat-box").append(`<p><b>Bot:</b> ${data.response}</p>`);
});
$("#message").val('');
}
</script>
</body>
</html>
Add a route to serve the chatbot UI in web.php
:
Route::get('/chatbot', function () {
return view('chatbot');
});
Step 5: Run and Test the Chatbot (Build an AI Chatbot Using Laravel)
Start the Laravel server:
php artisan serve
Train the chatbot:
http://localhost:8000/train-chatbot
Chat with the bot:
http://localhost:8000/chatbot