CodeNewbie Community 🌱

Cover image for How To Create An AI Chatbot with Google GEMINI using Node.js
Devarshi Shimpi
Devarshi Shimpi

Posted on • Originally published at blog.devarshi.dev

How To Create An AI Chatbot with Google GEMINI using Node.js

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

Google Gemini 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
Enter fullscreen mode Exit fullscreen mode

This command will initialize a new Node.js project.

2. Add boilerplate from Google AI Studio

Get the initial code from Google AI Studio, then click Get Code and copy the code for the Node.js and paste it into a file called as index.js

aistudio-boilerplate

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

api-key

3. Install Dependencies:

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

npm install @google/generative-ai ora chalk prompt-sync
Enter fullscreen mode Exit fullscreen mode

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",:

"type": "module",
Enter fullscreen mode Exit fullscreen mode

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

{
  "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"
  },
Enter fullscreen mode Exit fullscreen mode

and continued...

Then, we update from using const to using import

import { GoogleGenerativeAI, HarmCategory, HarmBlockThreshold } from "@google/generative-ai";
import chalk from 'chalk';
import ora from 'ora';
import prompt from 'prompt-sync';
Enter fullscreen mode Exit fullscreen mode

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.

const userInput = promptSync(chalk.green('You: '));
Enter fullscreen mode Exit fullscreen mode

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

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());
}
Enter fullscreen mode Exit fullscreen mode

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

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

5. Final Output

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

GitHub logo devarshishimpi / google-gemini-nodejs-chatbot

Simple Google Gemini ChatBot for Nodejs

Google Gemini Node.js Chatbot

Simple Google Gemini ChatBot for Nodejs

Installation

npm install @google/generative-ai ora chalk prompt-sync
Enter fullscreen mode Exit fullscreen mode

Replace the API_KEY in index.js with your own API key.

node index.js
Enter fullscreen mode Exit fullscreen mode

Contributing

Pull requests are welcome. For major changes, please open an issue first to discuss what you would like to change. Please view the CONTRIBUTING.md for more information.






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

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!

Read more

Top comments (0)