How to Integrate OpenAI with Laravel 10: A Comprehensive Guide
If you want to integrate openAI with laravel 8,9 or 10, then you are at the right place.
OpenAI has revolutionized the world of artificial intelligence, enabling developers to create powerful applications that leverage natural language processing.
Laravel, on the other hand, is a popular PHP web application framework known for its simplicity and elegance. By combining the capabilities of OpenAI with the versatility of Laravel 10, developers can build sophisticated applications that interact with users through natural language.
In this article, we will explore the process of integrating OpenAI with Laravel 10 but you can also use it with Laravel 8 or 9. Let’s dive into it with the following steps,
Prerequisites:
Before we begin, make sure you have the following prerequisites in place:
- Basic understanding of PHP, Laravel, and web development.
- Composer installed on your system.
- An OpenAI API key, which you can obtain by signing up at the OpenAI website.
Step 1: Set up a new Laravel project
First, let’s set up a new Laravel project by using the Composer command-line tool. Open your terminal and run the following command:
composer create-project laravel/laravel openai-laravel-example
This command will create a new Laravel project named “openai-laravel-example” in the current directory.
Step 2: Install OpenAI SDK to integrate OpenAI with Laravel 10
Next, we need to install the OpenAI SDK to interact with the OpenAI API. We will use Composer to do this. In your terminal, navigate to the project directory and run:
composer require openai/openai-api
Step 3: Configure OpenAI API Key
In order to use the OpenAI API, you need to set your API key in the Laravel configuration. Open the `.env` file in the project root directory and add the following line:
OPENAI_API_KEY=your_openai_api_key_here
Replace your_openai_api_key_here
with your actual OpenAI API key.
Then clear the config cache and if face valid cache path error checkout our previous article about it.
Step 4: Create a Controller and Route
Now, let’s create a controller that will handle the interaction with OpenAI. In the terminal, run the following Artisan command to generate a new controller:
php artisan make:controller OpenAIController
Open the newly created controller file located at app/Http/Controllers/OpenAIController.php
. We will create a simple method called generateText
that will take a user input as a prompt and use OpenAI to generate a text completion based on that prompt.
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use OpenAI\OpenAI; class OpenAIController extends Controller { public function generateTextForm(Request $request) { return view('generated_text'); } public function generateText(Request $request) { $input = $request->input('prompt'); $apiKey = config('services.openai.api_key'); OpenAI::setApiKey($apiKey); $response = OpenAI::completion([ 'engine' => 'davinci', 'prompt' => $input, 'max_tokens' => 100, ]); $output = $response['choices'][0]['text']; return view('generated_text', compact('output')); } }
Step 5: Create a Blade View
Now, let’s create a Blade view to capture the user input and display the generated text. Create a new file called generate_text.blade.php
in the resources/views
directory with the following content:
<!DOCTYPE html> <html> <head> <title>OpenAI Laravel Integration</title> </head> <body> <h1>Generate Text using OpenAI</h1> <form method="POST" action="{{ route('generate-text') }}"> @csrf <label for="prompt">Enter Prompt:</label><br> <input type="text" id="prompt" name="prompt" required><br> <button type="submit">Generate</button> </form> <br> @isset($output) <h2>Generated Text:</h2> <p>{{ $output }}</p> @endisset </body> </html>
Step 6: Define a Route
Next, we need to define a route that will point to our generateText
method in the controller. Open the routes/web.php
file and add the following route definition:
Route::get('/generate-text', 'OpenAIController@generateTextForm')->name('generate-text.form'); Route::post('/generate-text', 'OpenAIController@generateText')->name('generate-text');
Step 7: Start the Development Server
We are almost there! Now, let’s start the development server to see our integration in action. In your terminal, run the following command from the project root:
php artisan serve
Now, open your web browser and go to http://localhost:8000/generate-text
. You will see a form with an input field. Enter a prompt in the input field and click the “Generate” button.
Step 8: View the Generated Text
After clicking the “Generate” button, the form will submit, and the generated text will be displayed on the page.
Congratulations! You have successfully integrated OpenAI with Laravel 10. Your Laravel application can now generate text using the OpenAI API based on user input.
Conclusion
In this article, we walked through the process of integrate OpenAI with Laravel 10 to generate text based on user prompts.
We covered the installation of required dependencies, setting up the OpenAI API key, creating a controller and route, and displaying the generated text using a Blade view.
Feel free to explore more features of OpenAI and Laravel to create even more sophisticated applications that push the boundaries of what’s possible with AI and web development.