How To Create An AI Chatbot with Google GEMINI using Node.js
Tags: javascript, webdev, beginners, ai
Published: 2024-04-17 10:29:23

## Introduction

Generative AI has become a popular topic in the field of technology over the past year. Many developers are creating interesting projects using this technology. Google has developed its own generative AI model called Gemini.

In this article, we will be building a simple Node.js ChatBot and integrating Google Gemini into it. We will utilize the Google Gemini SDK for this purpose.

### What is Gemini?

![gemini-google](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/x75phpvdb1a8ifdh185t.png)

[Google Gemini](https://en.wikipedia.org/wiki/Gemini_(language_model)) is an advanced AI model developed by Google AI. Unlike traditional AI models, Gemini is not limited to processing text alone. It can also comprehend and operate on diverse formats such as code, audio, images, and video. This feature opens up exciting possibilities for your Node.js projects.

### Project Setup

#### 1. Creating a Node.js Project

To begin our project, we need to set up a Node.js environment. Let's create a new Node.js project by running the following command in the terminal:

```
npm init -y
```

This command will initialize a new Node.js project.

#### 2. Add boilerplate from Google AI Studio

Get the initial code from [Google AI Studio](https://aistudio.google.com/app/prompts/new_chat), then click **Get Code** and copy the code for the Node.js and paste it into a file called as `index.js`

![aistudio-boilerplate](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/fymx6mcetqjq58s8fmzt.png)

Also, make sure to generate an API key from the AI Studio. Select your Google Cloud project and click **Create**

![api-key](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/lq6ywe97pn5dhsocmc7a.png)

#### 3. Install Dependencies:

Now, We'll install the required dependencies of our project.

```
npm install @google/generative-ai ora chalk prompt-sync
```

The packages are used for the following:

1. `@google/generative-ai`: Google's package for generative AI tasks like text and image generation.
2. `ora`: Creates loading spinners and progress bars in the terminal.
3. `chalk`: Styles text in the terminal with colors and styles.
4. `prompt-sync`: Allows synchronous user input prompts in Node.js applications.

#### 4. Create a chatbot and customize it

In the initial version of our chatbot script, we relied on CommonJS require statements for importing modules. However, in the final iteration, we embraced ES6 import syntax for cleaner and more modern code organization.

Go to your `package.json` file and add the following line below `"main": "index.js",`:

```json
"type": "module",
```

It should look something like this (Top section only):

```json
{
  "name": "devarshishimpi-google-gemini-nodejs-chatbot",
  "version": "1.0.0",
  "description": "Simple Google Gemini ChatBot for Nodejs",
  "main": "index.js",
  "type": "module",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
```
and continued...

Then, we update from using `const` to using `import`

```javascript
import { GoogleGenerativeAI, HarmCategory, HarmBlockThreshold } from "@google/generative-ai";
import chalk from 'chalk';
import ora from 'ora';
import prompt from 'prompt-sync';
```

One significant enhancement was the introduction of a user input mechanism using the `prompt-sync` library. This allowed users to interact with the chatbot in real-time, entering their messages directly into the console.

```javascript
const userInput = promptSync(chalk.green('You: '));
```

Then, we customize the user interface with `ora` and `chalk` and make it more user responsive and easy to use

```javascript
while (true) {
    const userInput = promptSync(chalk.green('You: '));
    if (userInput.toLowerCase() === 'exit') {
        console.log(chalk.yellow('Goodbye!'));
        process.exit(0);
    }
    const result = await chat.sendMessage(userInput);
    const response = result.response;
    console.log(chalk.blue('AI:'), response.text());
}
```

Then, we add some error handling logic to our code:

```javascript
if (result.error) {
    console.error(chalk.red('AI Error:'), result.error.message);
    continue;
}
const response = result.response.text();
console.log(chalk.blue('AI:'), response);
```

#### 5. Final Output

Please find the final code for project at, please star ⭐️ the repo if you found it useful:

{% github devarshishimpi/google-gemini-nodejs-chatbot %}

Output:

We use `node index.js` to run our code. Make sure to replace `YOUR_API_KEY` with your generated API Key from Google API Studio.

![gemini-chatbot-output](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/jy5ttcgr3ca0cpomhwfq.gif)

## Conclusion

Thank you for reading! If you found this blog post helpful, please consider sharing it with others who might benefit. Feel free to check out my other blog posts and visit my socials!

- [Profile](https://bio.link/devarshishimpi)
- [Linkedin](https://linkedin.com/in/devarshi-shimpi)
- [Twitter](https://twitter.com/devarshishimpi)
- [Youtube](https://youtube.com/@devarshishimpi)
- [Hashnode](https://devarshishimpi.hashnode.dev)
- [DEV](https://dev.to/devarshishimpi)

### Read more

- [Top 10 VS CODE Extensions You Need In 2022!](https://blog.devarshi.dev/top-ten-vscode-extensions-you-need-in-twentytwentytwo)
- [Easiest Way to Install WordPress Locally for Beginners](https://blog.devarshi.dev/easiest-way-to-install-wordpress-for-beginners)
- [What is DigitalOcean? - Everything You Need to Know](https://blog.devarshi.dev/what-is-digitalocean-everything-you-need-to-know)