Sentiment Analysis App using Gemini
Tags: ai, machinelearning, tutorial, node
Published: 2023-12-24 14:01:48

![Cover](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/jr2frzxvbse2b6cmj72m.png)

## Introduction

Google has recently launched its state-of-the-art AI model **Gemini**. Gemini is another Large Language Model that is built robustly for multimodality. This brand-new LLM claims to be better than its contender GPT-4 in many aspects. It is currently offered in 3 variations- Nano, Pro, and Ultra.

The Gemini API was made available for developers on the 13th of December. In this tutorial, we will be using it to build a simple Node Express app that can analyze the sentiments of texts.

## Generating the Gemini API Key

The first thing you need to do is to generate an API key which you will use later in your app. Follow the steps below to create one.

**Step 1:** Visit the [Google AI for Developers](https://ai.google.dev/) page and click on the `Get API key in Google AI Studio` button.

![AI Dev Page](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/7ry8i5r9wq38g3weghbe.png)

**Step 2:** In the next screen you will need to sign in with your Google account to proceed. Once you're signed in, you will be redirected to the Google AI Studio dashboard. 

![Sign In](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/74q48w759kmievnfq2u4.png)

If it's your first time logging in, you will need to accept some terms first. Select the appropriate ones and then click on `Continue`.

![AI Studio Terms](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/j8musiugnpwkjtyb97zn.png)

**Step 3:** Now on the `Build with Gemini` popup, click on the `Get API Key` button to proceed.

![Get API Key](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/546ck4ekwq3d33q4mxs7.png)

In the API keys dashboard, click on the `Create API key in new project` button and wait until the key is generated.

![API key generation](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/84e6u09wv3qu3ol6hsq1.png)

Now copy the new API key from the popup and store it safely so that you can use it later in the app.

![Copy API Key](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xtv4znatclewdok31802.png)

## Setting up the Node Express App

Now you will need to build a simple app using Node Express that will interact with Gemini through the API and return the sentiments of the user-given sentences/texts.

### Creating the Project Structure

Let's start with setting up a Node project directory for the app. Follow the steps below to do it easily.

**Step 1:** Create a new folder in your desired location and set a name for it.

```bash
sentiment-gemini
```
**Step 2:** Now open this folder in your desired code editor. For this tutorial, we will use [Visual Studio Code](https://code.visualstudio.com/download).

Now open the terminal by clicking on `Terminal` on the Title Menu and then selecting the `New Terminal` option. Use the command given below to initialize a Node project.

```bash
npm init
```

Provide the necessary details in the terminal to set up the `package.json` file for this Node app or hit enter each time to proceed with the default ones.

![NPM Init](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/f3903u2b0vf5uh429x39.png)

**Step 3:** You are now ready with the Node project directory. You can then install the necessary packages to run this app. 

Execute the command below to install all the required/essential packages.

```bash
npm i @google/generative-ai body-parser dotenv express
```

![Install Packages](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xq9kyceajso5qaebuftn.png)

### Creating the Client Webpage

You will need a webpage where the users can enter a sentence to fetch its sentiment.

To do so, follow the steps below.

**Step 1:** Create a `public` folder inside the app root directory and add a new file named `index.html` to it.

![Index HTML Page](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/c1l7w8o7u359s33gdncb.png)

**Step 2:** Add the following content to the HTML file to design a simple webpage with an input area, a submit button, and a result display area, all embedded within a `<form>` element.

```html
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Sentiment Analysis App</title>
</head>
<body>
  <h1>Sentiment Analysis App</h1>
  <form id="sentimentForm" action="/analyze" method="post">
    <label for="text">Enter a text sentence:</label>
    <input type="text" id="text" name="text" required>
    <button type="submit">Find Sentiment</button>
  </form>
  <b><div id="result"></div></b>

<script src="./script.js"></script>
</body>
</html>
```

**Step 3:** Now, add a `script.js` file in the same folder with the following content.

```javascript
    // Display sentiment result on the webpage
    document.getElementById('sentimentForm').addEventListener('submit', async function (event) {
        event.preventDefault();
  
        const text = document.getElementById('text').value;
  
        // Send a POST request to the server
        const response = await fetch('/analyze', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
          },
          body: JSON.stringify({ text }),
        });
      
        // Fetch the Result and display it on the webpage
        const result = await response.text();
        document.getElementById('result').innerText = result;
      });
```

This file handles the submit button action i.e., it sends the user request to the `/analyze` endpoint, fetches the result, and then sets it to the `result` div on the webpage.

### Creating the Server Application

You can now navigate back to the root folder of the application to proceed further with the following steps.

**Step 1:** Create an `app.js` file which serves as the main server file. You can use the following code for this file.

```javascript
require("dotenv").config();
const express = require("express");
const bodyParser = require("body-parser");
const { GoogleGenerativeAI } = require("@google/generative-ai");

const app = express();
const port = 3000;

const genAI = new GoogleGenerativeAI(process.env.API_KEY);

// Middleware to parse incoming JSON requests
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

// Middleware to serve static files from the 'public' directory
app.use(express.static("public"));

// Serve HTML Webpage to the user on Page Load
app.get("/", (req, res) => {
  res.sendFile("index.html", { root: "public" });
});
// Handle sentiment analysis when the form is submitted
app.post("/analyze", async (req, res) => {
  try {
    const userInput = req.body.text;

    // Call Gemini API for sentiment analysis
    const geminiResponse = await run(userInput);

    const sentimentResult = geminiResponse;

    // Send sentiment result back to the client
    res.send(sentimentResult);
  } catch (error) {
    console.error("Error:", error.message);
    res.status(500).send("Internal Server Error");
  }
});

// Start the server
app.listen(port, () => {
  console.log(`Server is running at http://localhost:${port}`);
});

// Basic Function API to generate content/result using Gemini
async function run(userInput) {
  // For text-only input, use the gemini-pro model
  const model = genAI.getGenerativeModel({ model: "gemini-pro" });

  const prompt = `Analyze the sentiment of the sentence given below.\n${userInput}\nThe output should be in the format- Semtiment: Value`;

  const result = await model.generateContent(prompt);
  const response = await result.response;
  const text = response.text();
  return text;
}
```

**Step 2:** Now create a `.env` file and paste the API Key value that you obtained in the earlier steps.

```javascript
API_KEY=<YOUR GEMINI API KEY VALUE HERE>
```

This completes the basic setup for the Node Express App.

## Testing the App

You are now ready to run the app and test the functionality. Use the command below in the terminal to start the app.

```bash
node app.js
```

Once it executes successfully, you should see a message that the server is running on port 3000.

![Server Running](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/60m9jkytc165rht6n16w.png)

Now, open your browser and navigate to `localhost:3000` to access your app. You should see a simple webpage as shown below.

![Sentiment Webpage](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0pzx6l33ibqanalhrq7g.png)

Enter a sentence in the input area and click on the `Find` button. It should return the sentiment of that sentence in a while on the webpage.

![Sentiment Analysis](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/w2hbqkbmo4s73wypuiy1.png)

This verifies that your app is running as expected.

## Conclusion

In this tutorial, you have successfully learned how to generate your own Gemini API key, set up a Node Express App with a webpage, and then run it to find the sentiments of user-given sentences.

While this is a simple example app to showcase how you can use the Gemini Developer API to build your applications seamlessly, feel free to explore the [Gemini documentation](https://ai.google.dev/docs) to explore further advanced topics and usages of the Gemini Model.

You can also check out the source code of this app [here](https://github.com/Rutam21/gemini-sentiment).

Lastly, before you leave, don't forget to drop a like and share it with your peers if you found this content valuable and learned something new today.


[![Sponsor](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/62eudpkqh1cxxachfdbx.png)](https://github.com/sponsors/Rutam21)