To integrate the OpenAI API in a Laravel Inertia Vue project, you can follow these steps. While there might not be a specific package that combines all three technologies, you can use existing tools and libraries to achieve the integration.
Step 1: Set Up Laravel Backend
-
Install OpenAI PHP Client: Use a package like
openai-php/clientto interact with the OpenAI API from your Laravel backend.composer require openai-php/client -
Configure Environment Variables: Add your OpenAI API key to your
.envfile.OPENAI_API_KEY=your_openai_api_key -
Create a Service Class: Create a service class to handle requests to the OpenAI API.
<?php namespace App\Services; use OpenAI\Client; class OpenAIService { protected $client; public function __construct() { $this->client = new Client([ 'api_key' => env('OPENAI_API_KEY'), ]); } public function getResponse($prompt) { return $this->client->completions()->create([ 'model' => 'text-davinci-003', 'prompt' => $prompt, 'max_tokens' => 150, ]); } } -
Create a Controller: Create a controller to handle API requests from the front-end.
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Services\OpenAIService; class OpenAIController extends Controller { protected $openAIService; public function __construct(OpenAIService $openAIService) { $this->openAIService = $openAIService; } public function getResponse(Request $request) { $prompt = $request->input('prompt'); $response = $this->openAIService->getResponse($prompt); return response()->json($response); } } -
Define Routes: Add a route to handle the request.
use App\Http\Controllers\OpenAIController; Route::post('/api/openai', [OpenAIController::class, 'getResponse']);
Step 2: Set Up Inertia Vue Frontend
-
Create a Vue Component: Create a Vue component to interact with the backend.
<template> <div> <textarea v-model="prompt" placeholder="Enter your prompt"></textarea> <button @click="fetchResponse">Get Response</button> <div v-if="response"> <h3>Response:</h3> <p>{{ response }}</p> </div> </div> </template> <script> import { ref } from 'vue'; import axios from 'axios'; export default { setup() { const prompt = ref(''); const response = ref(null); const fetchResponse = async () => { try { const res = await axios.post('/api/openai', { prompt: prompt.value }); response.value = res.data.choices[0].text; } catch (error) { console.error('Error fetching response:', error); } }; return { prompt, response, fetchResponse }; }, }; </script> -
Add the Component to Your Page: Use the component in your Inertia page.
<template> <div> <OpenAIComponent /> </div> </template> <script> import OpenAIComponent from '@/Components/OpenAIComponent.vue'; export default { components: { OpenAIComponent, }, }; </script>
Conclusion
By following these steps, you can integrate the OpenAI API into your Laravel Inertia Vue project. This setup allows you to handle API requests on the backend with Laravel and display the results on the frontend using Vue.