OpenAI launched ChatGPT at the end of 2022, as you may already know. As everyone knows, ChatGPT is a very powerful tool. Fortunately, we can use the official API to take advantage of this feature as developers.
In today's lesson, we'll learn how to use it in a Laravel project. So, this time we not going to build chat based app. Because you know there's chatgpt already and chatgpt can be used not just for chat.
The other day I found some nice app to generate emoticon https://logsnag.com/icon, we can type any word and the API will give the emoticon representation of it. Here's what it look like.
Setup project
Let's create new laravel project.
Now let's add some package to interact with openai API.
Then publish the configuration file.
Next go to https://platform.openai.com/ you can register there you will get free access $18 credit for next three months.
After that go to https://platform.openai.com/account/api-keys and generate the API token.
Then add your API KEY to .env
file:
Create API
Now let's create controller to provide the API for generating the emoticon for any given text.
Here's the controller content.
Explanation:
- With chatgpt we can tell the bot what they task are, in this case in
role:system
we tell the bot to always reply with emoticon. - If you want the chatgpt to remember the conversation you can always put the response message to the
$messages
. Eg:
And then don't forget to register the controller to the routes. Go to routes/api.php
.
Create UI to interact with our API
Now go to welcome.blade.php
and add this form to capture user text input and generate icon from it.
Then add some javascript to listent text input change and then call the api to generate the emoticon.
Hopefully you can get the idea how to use openai chatgpt api in you laravel project.