Using AI In Your Frontend App feat. OpenAI and NextJS
In this video I'm going to show you how you can use Open AI to create some nice features in your apps.
Will the AI take our jobs?
YES!
When?
We are not sure! (probably soon… ish).
Ok, now that we got that out of the way, since that seems to be a concern in the dev community, we can figure out what to do in the meantime.
And I don’t mean by helping you to code your apps (which it can do for sure), but to help with the features of your apps.
For example, I put useful links to articles I find around the web in Notion or Obsidian apps. However I always need to categorise them somehow, by tags usually.
Wouldn’t it be great if I could just paste a link to a box, and then let AI generate most relevant tags or keywords for that article and that way I would be able to categorise them.
In this video we will create this exact example using OpenAI and NextJS.
And actually, it’s incredible how easy this is. Let me show you.
Setup
Let’s quickly just go over the setup.
I have here NextJS 13 app with Tailwind for styling. What we will also need is an OpenAI SDK for Node. You can install it by running npm install openai
in the root of your NextJS app.
Now you need to Signup for OpenAI API by clicking the API link on their site, and then click Signup. You can use Email or Microsoft or Google Accounts.
Once you are done with that - Login. Click on your profile and then View API Keys.
Create new secret key, and save it somewhere because you will not be able to copy it again. You will only be able to create a new key.
Ok, setup is done. Let’s write some code.
Create API Endpoint
In your Next app create a file called .env.local
add OPENAI_KEY=
as a variable and add your key there.
Now, create a file called get-ai-response.js
inside of pages/api
folder.
We need to setup OpenAI connection.
First we require Configuration
and OpenAIAPI
from openai
module.
Then we define our configuration and pass in OPENAI_KEY
from our .env.local
file.
Great.
Let’s define our async handler function for our API endpoint. In it, we will actually call the OpenAI API and give it a task.
The most important parts here are model
and prompt
. model
defines the AI model that you wanna use. Different models have different usage cost. You can read about different models on the OpenAI site. We will use the most expensive one “text-davinci-003”. Don’t worry, you get 18 bucks of API calls for free for two months. And thats more than enough for what we are doing here.
prompt
defines what you wanna ask the API. Like when you go to ChatGPT page and ask it something.
For this we will ask the AI to read the link we send it and give us 3 most relevant keywords of an article, and then return those keywords as a string separated with pipe symbol. This is so we can parse it easily into an array later on.
So we can say something like:
Read this link: ${req.query.link} and give me 3 most relevant keywords, output them as a string separated with |
We will of course get the link from the request that we will send to our get-ai-response
endpoint.
Only thing that is left to do is to return data from the response in json format.
const {Configuration, OpenAIApi} = require("openai");
const configuration = new Configuration({
apiKey: process.env.OPENAI_KEY,
});
const openai = new OpenAIApi(configuration);
export default async function handler(req, res) {
const response = await openai.createCompletion({
model: "text-davinci-003",
prompt: `Read this link: ${req.query.link} and give me 3 most relevant keywords, output them as a string separated with |`,
temperature: 0,
max_tokens: 100,
});
res.status(200).json(response.data)
}
We can already test this out by going to localhost:3000
then api/get-ai-response?link=<link-to-the-article>
.
Now wait a little and if everything is ok, you should get a response like this.
{
"id": "cmpl-6iSLDVJiFvEEx2WkCnA7wxvKAgMuA",
"object": "text_completion",
"created": 1676053395,
"model": "text-davinci-003",
"choices": [{"text": "\n\nDirectus|Newsletter|Flows|Subscribers|List", "index": 0, "logprobs": null, "finish_reason": "stop"}],
"usage": {"prompt_tokens": 48, "completion_tokens": 15, "total_tokens": 63}
}
Notice that under text
property we get a string with keywords separated by a pipe.
It works!
All that is left to do now is to create a user interface for sending links and we are done.
User interface
So I removed almost everything from the home page of our NextJS app. And replaced it with just an input field and a button.
Input and button are inside of a form tag.
Ok, first of all lets add two states, loading
for showing loading state while the AI is working, and data
for setting and displaying the keywords that we get from the AI.
Now let’s add a function for submitting our link to the API. I’ll call it handleSubmit
. We will of course first preventDefault
so that our page doesn’t refresh. Then we set the loading state to true
, get the link from the field named link
in our form. And we send that to the API with fetch
. we await for the data, and when we get it we need to trim it to remove new lines, and then split it into an array on the |
symbol. Set loading
to false.
const handleSubmit = async (e) => {
e.preventDefault()
setLoading(true)
const link = e.target.link.value
const res = await fetch(`/api/get-ai-response?link=${link}`)
const data = await res.json()
setData(data.choices[0].text.trim().split("|"))
setLoading(false)
}
Great.
Now all we need to do is pass handleSubmit
function to onSubmit
event of the form.
Under the form we show “Please wait…” if the loading state is true
.
And then finally we spit out the keywords if we get the data and loading
state is false
.
And that is all there is to it!
{loading && <div>Please wait...</div>}
{data.length > 0 && !loading && data.map((tag, index) => <div key={index}>{tag}</div>)}
Let’s test it out.
Find your article somewhere on the web, and paste that link. I will use the documentation for installing TailwindCSS on NextJS: https://tailwindcss.com/docs/guides/nextjs.
And if everything works as expected we should get some results.
Try it out with a few more articles, and judge for yourself if the results you are getting are relevant.
Conclusion
Of course this is just a proof of concept. But the possibilities are endless here. You could for example take those key words, save them to the database with a link. Maybe allow the users to add their own keywords, play around with refining the results and so on.
What would be your idea for using AI in your apps? Let me know down in the comments.
Everything we did here will be available for you on Github. The link is below.