Hello everyone, My name is Rohit and welcome to my
channel. In this video, I am gonna show you how to make a ai chatbot using Google Gemini and Next.js
14. I am using Tailwind CSS for the UI part. For the source code check out the description. So,
without any further delay, let’s get started! First, we initialized an nextjs project, I named this project aichatbot and these
are my default settings for this project. Before we jump into the code, let’s first
set up the Gemini account. For this go to the ai.google.dev and click on Get Gemini API key.
Your dashboard will look something like this, from here you can change the models. If
you click on get code. You will see the documented code provided by Google to use
the API in different programming languages. For the javascript, we need to install
a package. So, let’s install this first. Alright, let’s open this project in
our favorite code editor VS code. These are the default codes provided
by Next.js, we don’t need all of these, delete this. Here we will write
the code for the ai chatbot. —-- For this project, we are going to use
a model called gemini-1.0-pro-001, which is a text-generation model
that can chat with you about various topics. To use this model, we need to write some
code in React, which is a popular framework for building user interfaces. We also need to
install the @google/generative-ai package, which is a library that helps us interact
with the Google Generative AI service. Let’s take a look at the code and see how it
works. The imports are the first few lines of the code, where we import the modules and
packages that we need for the project. We use the “use client” directive to tell the compiler
that we are writing code for the browser, not the server. We import the useState and
useEffect hooks from React, which allow us to manage the state and the side effects of our
app. We also import the GoogleGenerativeAI, HarmCategory, and HarmBlockThreshold classes
from the @google/generative-ai package, which we will use to create and
configure the generative model. The Home component has several variables
and functions that we define using the useState and useEffect hooks. Let
me explain what each of them does: The messages variable is an array that stores the
messages that are exchanged between the user and the bot. We use the useState hook to initialize
the messages variable as an empty array, and to create a function called setMessages
that allows us to update the messages array. The userInput variable is a string that
stores the current input of the user. The chat variable is an object that represents
the chat session with the generative model. The theme variable is a string
that stores the current theme of the app. We use the useState hook to
initialize the theme variable as “light”, and to create a function called setTheme
that allows us to update the theme variable. The error variable is a string that stores
the current error message of the app. The API_KEY variable is a string
that stores the API key that we need to access the Google Generative AI
service. We will add the API key later The MODEL_NAME variable is a string that
stores the name of the generative model that we want to use. In this case,
we use the gemini-1.0-pro-001 model, which is the name of the text
generation model that can chat with us The genAI variable is an instance
of the GoogleGenerativeAI class, which is the main class that we use to
interact with the Google Generative AI service. We create this instance by passing the
API_KEY variable as an argument to the constructor The generationConfig variable is an object
that stores the configuration settings for the text generation. It has four properties:
temperature, topK, topP, and maxOutputTokens. The temperature is a number that controls the
randomness of the generation. The topK and topP are numbers that control the filtering of
the possible tokens that can be generated. The maxOutputTokens is a number that controls the
maximum number of tokens that can be generated for each response. This parameter helps to limit
the length and the complexity of the response. The safetySettings variable is an array
that stores the safety settings for the text generation. It has four objects, each
representing a different category of harmful or inappropriate content that we want to avoid.
Each object has two properties: category and threshold. The category is a string that specifies
the name of the harm category, such as harassment, hate speech, sexually explicit, or dangerous
content. The threshold is a string that specifies the level of harm that we want to block, such
as low, medium, or high. These parameters help to prevent the model from generating content that
could offend, hurt, or harm the user or others. The initChat function is a function that
we define inside the useEffect hook. It is an async function, which means that it can
use the await keyword to pause the execution until a promise is resolved. A promise is
an object that represents the completion or failure of an asynchronous operation.
The initChat function create a new chat session with the generative model by using the genAI
variable and the getGenerativeModel method. Also, It tries to start the chat session by using
the newChat variable and the startChat method. It catches any error that might occur during the
process, and sets the error variable to a string that says “Failed to initialize chat. Please
try again.” by using the setError function. The handleSendMessage function create a user
message object by using the userInput variable and the new Date function. Also, It tries
to update the messages array by using the setMessages function and the spread operator.
Next, clear the userInput variable by using the setUserInput function and passing an empty
string as an argument. This way, we reset the userInput variable to an empty string. Also,
it checks if the chat variable is not null, which means that the chat session is initialized
and ready. If so, it tries to send the user input to the generative model by using the chat
variable and the sendMessage method. Next, create a bot message object by using the
result variable and the response method. Also, update the messages array by using the
setMessages function and the spread operator. At last, catch any error
that might occur during the process. The handleThemeChange function is a function
that takes an event object as an argument, and updates the theme variable by using the
setTheme function and the target.value property. The handleKeyPress function is a function
that takes an event object as an argument, and checks if the key that the user
pressed is the Enter key. If so, it prevents the default behavior of the event,
which is to add a new line in the input field, and calls the handleSendMessage function to
send the user input to the generative model. The return statement is the last part
of the Home component, where we return the JSX element that represents the
UI of our app. We use the className attribute to assign Tailwind CSS classes
to the elements, and we use the primary, secondary, accent, and text variables to
get the theme colors for the elements. An h1 element that displays the app
title. A div element that contains the theme label and the theme select.
It has the flex and space-x-2 classes. A label element that displays the theme label. A select element that allows the user to
choose the theme. It has the id, value, onChange, and className attributes. The
id attribute sets the id of the element to “theme”. The value attribute binds the element
to the theme variable, which stores the current theme. The onChange attribute updates the theme
variable by using the handleThemeChange function and the target.value property, which
gets the value of the selected option. A div element that contains the chat area.
A map method that iterates over the messages array and renders each message as a div
element. The map method takes a callback function and an index as arguments. The callback
function returns a JSX element for each message, and the index is the position
of the message in the array. A div element that wraps the message. A
span element that displays the message text. A p element that displays the message
sender and the message time. A div element that displays the error message if
there is any. It has the error and className attributes. A div element that contains
the input field and the send button. An input element that allows the user
to type their message. It has the type, placeholder, value, onChange, onKeyDown,
and className attributes. The type attribute sets the type of the element to “text”,
which means that it accepts text input. A button element that allows the user to
send their message. It has the onClick and className attributes. The onClick attribute
calls the handleSendMessage function when the user clicks on the button, which sends
the user input to the generative model. *------ Before we test our application, we need to
add the API key here. So, go to the Gemini Dashboard and click on Get API key.
From here you can select any project and generate the API key. Simply copy
this API and paste it into your project. Now, it’s time to test our application, so, go to the terminal window and
run the command, npm run dev. Ok, the input text is not visible. But Our code
is correct, So, we have to make a small change to our code, go to the global.css file,
and change the theme from dark to light. And that’s it, our project is working perfectly. You can ask questions, change themes, or
most importantly, customize this project. Thanks for watching! I hope you successfully
build the project. If yes, then hit the like and subscribe button. Thanks for
watching. See you in my next video.