Today we will connect our Laravel app to Chat GPT using the simplest way possible. The idea is to start tinkering with AI so we can take advantage of this powerful tool.
Requirements:
PHP 8.1+
Laravel 9.46+
Here you have the guide:
Create a Laravel app (or use the one you already have).
laravel new aiwithlaravel
We must add the Open AI composer package
composer require openai-php/laravel
Create an account at https://openai.com then head to https://platform.openai.com/account/api-keys so you can create your API keys
Once you have your keys, let's publish the vendor file for the OpenAI\Laravel\ServiceProvider using the following command.
php artisan vendor:publish
This will generate a config/openai.php file with the name of the env vars you need to define and fill in your .env with the respective keys
OPENAI_API_KEY= OPENAI_ORGANIZATION=
With everything in place, we should be able to communicate with Chat GPT. Let's modify the inspire command at routes/console.php like the following:
Artisan::command('inspire', function () { $this->comment( OpenAI::chat()->create([ 'model' => 'gpt-3.5-turbo', 'messages' => [ [ 'role' => 'user', 'content' => 'Hello, how are you?' ] ] ])->choices[0]->message->content ); })->purpose('Display an inspiring quote');
At this point you only need to run the next command to get the Chat GTP response:
php artisan inspire
And here you have the response from Chat GPT
The OpenAI::chat method can be used from many blocks like controllers, a service, a command, events, and actions you name it. Feel free to experiment and create your workflow.
As mentioned above, this practice is focused on consuming Chat GPT API with a basic example. To get the most out of the service you need to learn about prompt engineering as well.
Also, let's say you want to build a chatbot for a specific context or sector, you'd need to learn about embeddings and vector databases. You could feed your database with plain text data, PDFs, scrapping websites etc. And of course, learn a little bit more about the AI models available to fit your needs.
BONUS ๐คฏ
How Chat GPT works: