DEV Community

Cover image for How to use Google Gemini AI with Node JS: A Beginner's guide
Rishav Raj
Rishav Raj

Posted on • Edited on • Originally published at rishavd3v.hashnode.dev

How to use Google Gemini AI with Node JS: A Beginner's guide

Introduction



Want to build cool projects using Generative AI? In this article, we will discuss how you can create Generative AI powered application in Node.js.

We will use a free API provided by Google that lets us integrate Google Gemini into our application.

We will build a simple Node.js application and integrate Google Gemini with it.

Overview of Google Gemini

Google Gemini, a Large Language Model by Google, is a versatile multimodal AI that supports various formats including text, images, and audio. The Gemini API, available with a free tier, enables developers to create innovative generative AI applications.

Prerequisites

  • Node.js and npm installed in your system.

  • Basic knowledge of Node.js and Express, that's it!

Set Up Project

1. Initialize Project

First let's create a Node.js project. Create a directory, open terminal in the directory and run the following command.

⚠ Ensure your terminal is in the project directory before executing any commands.
npm init
Enter fullscreen mode Exit fullscreen mode

It will ask for some details about the project, like name, description, and version. You can enter any information or just press Enter to skip. This will initialize a Node.js project in the directory and create a package.json file.

2. Install packages

Now it's time to install the required dependencies. Inside the terminal, run the following command.

npm install express dotenv
Enter fullscreen mode Exit fullscreen mode
  • Express is a Node.js framework which we are going to use to create routes and middlewares.

  • dotenv is used to access sensitive credentials like api keys from .env file.

Now let's install the SDK

npm install @google/generative-ai
Enter fullscreen mode Exit fullscreen mode

This will install Google Generative AI package.

3. Get API Key

To get the gemini working we will have to generate an API key from Google AI Studio.

Head over to https://aistudio.google.com/app/apikey . Sign in to your google account. You will see something like this:

Click on Create API key.

Click on Create API key in new project and copy the key that is generated.

4. Set up Environment Variables

Open the project directory in VS Code or any IDE and create a .env file. Our project directory will look something like this:

.env file is used to store sensitive information like API key. Inside your .env file paste the following code.

API_KEY = YOUR_API_KEY
Enter fullscreen mode Exit fullscreen mode

Replace YOUR_API_KEY with the actual key that we got earlier.

5. Create an Express server

We are finally done with all the setup, now it's time to code.

Create an index.js file in your directory and set up a basic express server.

// In index.js

const express = require("express");
const app = express();

app.get("/",(req,res)=>{
    res.send("Hello world");
});

app.listen(3000,()=>{
    console.log("App is running on port 3000");
});
Enter fullscreen mode Exit fullscreen mode

Let's run our app to check if everything is working correctly. But before that we are going to add a start script in our package.json file which will make running the app easier.

"scripts": {
  "start": "node index.js"
}
Enter fullscreen mode Exit fullscreen mode

Our package.json file will look something like this:

Let's run our application to check if it's working fine. Enter the following command inside the terminal (press ctrl + ~ to open terminal in VSCode).

npm start
Enter fullscreen mode Exit fullscreen mode

If there are no errors, our express server will start. Now if we go to http://localhost:3000/ we'll see this:

Great! Our server is now up and running. Now it's time to integrate Gemini in our project.

Adding Google Gemini

1. Create route

We are going to create a /gemini route, which will generate response according to the prompt given.

Inside index.js file add the following code to create a /gemini route.

const generateContent = require("./routes/gemini.js");

app.get("/gemini", generateContent);
Enter fullscreen mode Exit fullscreen mode

Our index.js file will look something like this:



2. Configure Gemini

Inside the root directory, create a folder routes. Inside the folder create gemini.js file and add the following code:

const dotenv = require("dotenv").config();
const { GoogleGenerativeAI } = require("@google/generative-ai");

const genAI = new GoogleGenerativeAI(process.env.API_KEY);
const model = genAI.getGenerativeModel({ model: "gemini-1.5-flash"});


const generateContent = async (req,res)=>{

    try{
        const prompt = "Create 5 funny and witty jokes about generative AI";

        const result = await model.generateContent(prompt);
        const response = await result.response;
        const text = response.text();
        res.send(text);
    }
    catch(err){
        console.log(err);
        res.send("Unexpected Error!!!");
    }
}

module.exports = generateContent;
Enter fullscreen mode Exit fullscreen mode

Here we are using gemini-1.5-flash model. You can read more about different models available and their details here - https://ai.google.dev/gemini-api/docs/models/gemini

We are defining our prompt inside the prompt variable and generating output using generateContent method. You can take prompt as user input and pass it to the method.

3. Run application

Execute the following code in terminal:

npm start
Enter fullscreen mode Exit fullscreen mode

Working perfectly! Without any errors :)

Check response

Go to http://localhost:3000/gemini to check the response from AI.

Congratulations! You just build your first Generative AI application. Now it's time to think about some use cases and build some cool projects.

Official documentation - https://ai.google.dev/gemini-api/docs/

Conclusion

In this article we covered the basic text generation from a prompt using Google Gemini. We'll cover things like Safety Settings, Conversation History, Image Processing in future articles.

Here's the GitHub link for the project: https://github.com/rishavd3v/gemini-text

If you found the article helpful, please consider liking it and sharing it with your friends. You can follow me for more such helpful and interesting articles.

Thanks for reading! Bye :)

Top comments (0)