Skip to content

Instantly share code, notes, and snippets.

@Zakarialabib
Created December 6, 2022 14:28
Show Gist options
  • Save Zakarialabib/b7be5ad7d62f3739fb1f77a68710228e to your computer and use it in GitHub Desktop.
Save Zakarialabib/b7be5ad7d62f3739fb1f77a68710228e to your computer and use it in GitHub Desktop.
ChatBot Laravel Livewire PHP-ML

ChatBot Laravel Livewire PHP-ML

I was expermenting with chatgpt, i had the idea to build chatbot, i already tried that years ago botman and rasa,

so there is plenty of things to work on

i thought of building it with livewire cause it's fast for chat responses,

composer require php-ai/php-ml

// Create a simple chatbot interface using Laravel's Blade templating engine

Chatbot

@csrf Enter your message: Send

// Use the PHP-ML library to train your chatbot on a dataset of sample user inputs and responses

// app/Http/Controllers/ChatbotController.php

use Phpml\Classification\KNearestNeighbors; public function trainChatbot() { // Load dataset of sample user inputs and responses $samples = [['How are you?', 'I am good, thank you.'], ['What is your name?', 'My name is Chatbot.']]; $labels = ['greeting', 'introduction'];

// Train K-Nearest Neighbors classifier using dataset
$classifier = new KNearestNeighbors();
$classifier->train($samples, $labels);

// Save trained classifier for future use
$classifier->save('chatbot.model');

}

// Use the trained chatbot to process user input and generate appropriate responses public function handleUserInput(Request $request) { // Load trained classifier $classifier = KNearestNeighbors::restore('chatbot.model');

// Process user input using classifier
$label = $classifier->predict($request->input('user_input'));

// Generate appropriate response based on processed user input
$response = '';
switch ($label) {
    case 'greeting':
        $response = 'Hello! How are you?';
        break;
    case 'introduction':
        $response = 'My name is Chatbot.';
        break;
}

To train your chatbot to learn about products in a database and answer questions about their prices, you will need to perform the following steps:

Create a database of products, including information such as the name, price, and any other relevant details. Load the product information from the database into your Laravel and PHP Symphony project. This can be done using Laravel's Eloquent ORM.

$products = Product::all();

Train your chatbot on a dataset of sample user inputs and responses that includes questions about product prices. This can be done using the PHP-ML library.

$samples = [
    ['How much does the XYZ product cost?', 'The XYZ product costs $100.'],
    ['What is the price of the ABC product?', 'The ABC product costs $200.'],
];
$labels = ['product_price', 'product_price'];

$classifier = new KNearestNeighbors();
$classifier->train($samples, $labels);

Use the trained classifier to process user input and generate an appropriate response. This can be done using the predict method provided by the PHP-ML library.

$label = $classifier->predict($request->input('user_input'));

Generate an appropriate response based on the processed user input. If the user input is a question about a product price, use the product information loaded from the database to generate a response.

$response = '';
switch ($label) {
    case 'product_price':
        // Extract product name from user input
        $productName = $this->extractProductName($request->input('user_input'));

        // Look up product price in database and generate response
        $product = Product::where('name', $productName)->first();
        if ($product) {
            $response = "The $productName product costs $" . $product->price . ".";
        } else {
            $response = "I'm sorry, I don't have information about that product.";
        }
        break;
    // Add other cases for other types of user input
}

To create a chatbot that can search and retrieve data from multiple models, such as the sales, saledetails, salepayments, purchase, purchasedetails, and purchasepayments models in your example, you will need to perform the following steps:

Define the relationships between the different models in your database. This can be done using Laravel's Eloquent ORM.

// app/Sale.php

class Sale extends Model
{
    public function saledetails()
    {
        return $this->hasMany(SaleDetail::class);
    }

    public function salepayments()
    {
        return $this->hasMany(SalePayment::class);
    }
}

// app/Purchase.php

class Purchase extends Model
{
    public function purchasedetails()
    {
        return $this->hasMany(PurchaseDetail::class);
    }

    public function purchasepayments()
    {
        return $this->hasMany(PurchasePayment::class);
    }
}

Train your chatbot on a dataset of sample user inputs and responses that includes questions about the data in the different models. This can be done using the PHP-ML library.

$samples = [    ['What was the total sale amount for invoice number 12345?', 'The total sale amount for invoice number 12345 was $1000.'],
    ['How many items were purchased in the last month?', 'There were 100 items purchased in the last month.'],
    ['What is the balance due for purchase order number 54321?', 'The balance due for purchase order number 54321 is $500.'],
];
$labels = ['sales', 'purchases', 'purchases'];

$classifier = new KNearestNeighbors();
$classifier->train($samples, $labels);

Use the trained classifier to process user input and generate an appropriate response. This can be done using the predict method provided by the PHP-ML library.

$label = $classifier->predict($request->input('user_input'));

Generate an appropriate response based on the processed user input. If the user input is a question about data in one of the models, use the relationships defined in step 1 to search and retrieve the relevant data.

$response = '';
switch ($label) {
    case 'sales':
        // Extract invoice number from user input
        $invoiceNumber = $this->extractInvoiceNumber($request->input('user_input'));

        // Look up sale information in database and generate response
        $sale = Sale::with('saledetails', 'salepayments')->where('invoice_number', $invoiceNumber)->first();
        if ($sale) {
            $totalSaleAmount = $sale->saledetails->sum('amount') + $sale->salepayments->sum('amount');
            $response = "The total sale amount for invoice number $invoiceNumber was $" . $totalSaleAmount . ".";
        } else {
            $response = "I'm sorry, I don't have information about that invoice number.";
        }
   }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment