Recently, I've been seeing a lot of developers trying to integrate ChatGPT into their web application and seem to be confused about it; so I decided to create a package that simplifies the process of integrating ChatGPT into a Laravel application.
Let's see how it works.
The only thing you need to worry about is the API key from openAI website; apart from that, everything else is taken care of.
Click here to generate your own API key.
Ok! Now that you have your API key ready, let's install the package.
composer require hesamrad/laravel-chatgpt
Then, publish the configuration file:
php artisan vendor:publish --provider="HesamRad\LaravelChatGpt\LaravelChatGptServiceProvider" --tag="chatgpt-config"
And lastly, head over to your .env
file and paste your API key so that the package can use it to connect to ChatGPT:
CHATGPT_API_KEY="{YOUR-API-KEY}"
And you're done! How easy was that? You now have ChatGPT inside your application.
Wanna try?
There are a couple ways to use the package to connect to ChatGPT.
Method #1 - Using built-in routes.
The package comes with a built-in route so you can send a request from anywhere inside your client application; whether it's a separate JavaScript-powered front-end, or anything else.
Simply send a POST
request to /api/chatgpt/ask
with a body parameter question
to get your answer.
Method #2 - Using global helper function.
There is a chatgpt()
global helper function which takes one parameter as the question you want to ask. You could use this method anywhere you like.
If you want to use this package inside any controller you could go about it like this:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use App\Http\Controllers\Controller;
class ImaginaryController extends Controller
{
/**
* This method connects to ChatGPT servers
* and asks the given question.
*
* @param string $question
* @return \Illuminate\Http\Response
*/
public function ImaginaryMethod($question)
{
$answer = chatgpt($question);
return response($answer, Response::HTTP_OK);
}
}
I think this is a very simple but useful package for developers who just want to use ChatGPT without having to deal with its implementation.
I will certainly add more details to the package and update this post; but I would really appreciate it if you'd be so kind to drop a star on its GitHub repository.
Feel free to give me more ideas to implement on this package; I'd love nothing more than to contribute to the open-source community.
Cheers!
Top comments (0)