Integrate Generative AI with Node JS: A Beginner's guide
Tags: webdev, javascript, node, ai
Published: 2024-07-07 15:21:09

## Introduction  

<br>
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.
<br>

## Overview of Google Gemini

![](https://res.cloudinary.com/dvzkzccvn/images/f_auto,q_auto/v1702100310/Google-Gemini-AI-Sign-up-and-Login-process/Google-Gemini-AI-Sign-up-and-Login-process.jpg?_i=AA align="center")

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.
<br>

## Prerequisites

* Node.js and npm installed in your system.
    
* Basic knowledge of Node.js and Express, that's it!
<br>    

## Set Up Project<br><br>

### 1. Initialize Project

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

<div data-node-type="callout">
<div data-node-type="callout-emoji">⚠ Ensure your terminal is in the project directory before executing any commands.</div>
</div>

```powershell
npm init
```

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.
<br>

### 2. Install packages    

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

```powershell
npm install express dotenv
```

* *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

```powershell
npm install @google/generative-ai
```

This will install Google Generative AI package.
<br>

### 3. Get API Key
<br>
    

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](https://aistudio.google.com/app/apikey) . Sign in to your google account. You will see something like this:

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1720282550339/cab6093e-abfb-456a-9511-38054c7b5e2b.png)

Click on *Create API key*.

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1720282641717/f2b1ba4e-b3ce-4f50-9f25-dc0df42975cf.png)

Click on *Create API key in new project* and copy the key that is generated.
<br>

### 4. Set up Environment Variables
<br>
    

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

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1720283129982/0891f5c8-cf67-44ba-a378-b2122660346e.png)

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

```basic
API_KEY = YOUR_API_KEY
```

Replace `YOUR_API_KEY` with the actual key that we got earlier.
<br>

### 5. Create an Express server
<br>
    

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.

```javascript
// 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");
});
```

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.

```javascript
"scripts": {
  "start": "node index.js"
}
```

Our `package.json` file will look something like this:

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1720284940965/5291b154-125d-40c9-a85a-ff0ec84eda72.png)

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).

```bash
npm start
```

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

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1720285314582/c99c7fcf-a087-4243-937a-190eeeafc731.png)

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

## Adding Google Gemini<br><br>

### 1. Create route
<br>

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.

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

app.get("/gemini", generateContent);
```

Our index.js file will look something like this:

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1720328557573/501f0516-d969-4e6a-a22b-88eeec905b10.png)
<br>

### 2. Configure Gemini
<br>
    
Inside the root directory, create a folder `routes`. Inside the folder create `gemini.js` file and add the following code:

```javascript
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;
```

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](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.
<br>

### 3. Run application
<br>
    

Execute the following code in terminal:

```bash
npm start
```

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1720330494101/1869503a-4183-4e58-ba53-a699f66ca58e.png)

Working perfectly! Without any errors :)
<br>

### Check response
<br>

Go to [**http://localhost:3000/gemini**](http://127.0.0.1:3000/gemini) to check the response from AI.

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1720330837248/9ba9e373-8bee-4efa-aac7-11d373ab688a.png)

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/](https://ai.google.dev/gemini-api/docs/quickstart?lang=node)
<br>
## Conclusion
<br>

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](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 :)