Integrating AI in Laravel (Using OpenAI, ChatGPT, or AI Libraries)

Integrating AI in Laravel - Using OpenAI, ChatGPT, or AI Libraries

1. Install Laravel

First, install Laravel if you haven’t already:

composer create-project laravel/laravel ai-project

2. Set Up OpenAI API Key

Register at OpenAI and get your API key. Add it to your .env file:

OPENAI_API_KEY=your_openai_api_key

3. Install OpenAI PHP SDK

Use Composer to install the OpenAI PHP package:

composer require openai-php/client

4. Create an AI Service

Create a service class to interact with OpenAI’s API:

namespace App\Services;

use OpenAI\Client;

class OpenAIService {
    protected $client;

    public function __construct() {
        $this->client = new Client(env('OPENAI_API_KEY'));
    }

    public function generateText($prompt) {
        return $this->client->completions()->create([
            'model' => 'gpt-4',
            'prompt' => $prompt,
            'max_tokens' => 100
        ]);
    }
}

5. Create a Controller

Generate a controller to handle AI requests:

php artisan make:controller AIController

Add the following code to AIController.php:

use App\Services\OpenAIService;
use Illuminate\Http\Request;

class AIController extends Controller {
    protected $openAI;

    public function __construct(OpenAIService $openAI) {
        $this->openAI = $openAI;
    }

    public function getResponse(Request $request) {
        $response = $this->openAI->generateText($request->input('prompt'));
        return response()->json($response);
    }
}

6. Define API Route

Add an API route in routes/api.php:

Route::post('/ai-response', [AIController::class, 'getResponse']);

7. Test the AI API

Use Postman or a frontend client to send a POST request to:

http://your-laravel-app.test/api/ai-response

With a JSON body:

{ "prompt": "Write a Laravel tutorial" }

8. Enhancing AI Capabilities

You can use AI for:

  • Chatbots
  • Content generation
  • Code suggestions
  • Data analysis

9. Deploying the AI-Powered App

Deploy the Laravel app on a server or cloud platform like AWS, DigitalOcean, or Laravel Forge.

10. Conclusion

Integrating AI into Laravel can add intelligent automation to your applications. Try OpenAI and other AI libraries to enhance user experience.

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

0 Comments