Implementing AI Chatbot with Laravel and OpenAI

Implementing AI Chatbot with Laravel and OpenAI - Developer Sahayak

Introduction

Are you a developer in Gujarat, Mehsana, or anywhere in the world looking to integrate AI into your Laravel project? In this guide, we will walk through the process of building an AI-powered chatbot using Laravel and OpenAI's API.

Why Use Laravel and OpenAI?

Laravel is a powerful PHP framework that makes development easy and scalable. OpenAI provides advanced AI capabilities, making it possible to create an intelligent chatbot.

Steps to Implement an AI Chatbot in Laravel

1. Install Laravel

Run the following command to create a new Laravel project:

composer create-project --prefer-dist laravel/laravel chatbot

2. Install Guzzle HTTP Client

Guzzle is required to make API requests:

composer require guzzlehttp/guzzle

3. Get OpenAI API Key

Sign up at OpenAI and get your API key.

4. Configure OpenAI API in Laravel

Open the .env file and add:

OPENAI_API_KEY=your_openai_api_key

5. Create a Chatbot Controller

Run:

php artisan make:controller ChatbotController

6. Write the API Call Function

Edit ChatbotController.php:


use Illuminate\Http\Request;
use GuzzleHttp\Client;

class ChatbotController extends Controller {
    public function chat(Request $request) {
        $client = new Client();
        $response = $client->post('https://api.openai.com/v1/completions', [
            'headers' => [
                'Authorization' => 'Bearer ' . env('OPENAI_API_KEY'),
                'Content-Type' => 'application/json',
            ],
            'json' => [
                'model' => 'text-davinci-003',
                'prompt' => $request->input('message'),
                'max_tokens' => 150,
            ],
        ]);
        return response()->json(json_decode($response->getBody(), true));
    }
}
        

7. Set Up Routes

Add this in routes/web.php:

Route::post('/chat', [ChatbotController::class, 'chat']);

8. Create a Simple Frontend

In resources/views/chat.blade.php:


<form id="chat-form" method="POST" action="/chat">
    @csrf
    <input type="text" name="message" required>
    <button type="submit">Send</button>
</form>
        

9. Test Your Chatbot

Run the Laravel server and test your chatbot:

php artisan serve

Conclusion

Now you have a fully functional AI chatbot using Laravel and OpenAI. This chatbot can be enhanced with more features and a better UI.

Published by Developer Sahayak - Helping Developers Solve PHP, Laravel, and Drupal Issues.

0 Comments