DEV Community

Rutam Prita Mishra
Rutam Prita Mishra

Posted on

Sentiment Analysis App using Gemini



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 page and click on the Get API key in Google AI Studio button.

AI Dev Page

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

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

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

Get API Key

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

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

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.

Enter fullscreen mode Exit fullscreen mode

Step 2: Now open this folder in your desired code editor. For this tutorial, we will use Visual Studio Code.

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.

npm init
Enter fullscreen mode Exit fullscreen mode

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

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.

npm i @google/generative-ai body-parser dotenv express
Enter fullscreen mode Exit fullscreen mode

Install Packages

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

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.

<!DOCTYPE html>
<html lang="en">
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Sentiment Analysis App</title>
  <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>
  <b><div id="result"></div></b>

<script src="./script.js"></script>
Enter fullscreen mode Exit fullscreen mode

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

    // Display sentiment result on the webpage
    document.getElementById('sentimentForm').addEventListener('submit', async function (event) {

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

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.

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.urlencoded({ extended: true }));

// Middleware to serve static files from the 'public' directory

// 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"/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
  } 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;
Enter fullscreen mode Exit fullscreen mode

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

Enter fullscreen mode Exit fullscreen mode

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.

node app.js
Enter fullscreen mode Exit fullscreen mode

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

Server Running

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

Sentiment Webpage

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

This verifies that your app is running as expected.


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 to explore further advanced topics and usages of the Gemini Model.

You can also check out the source code of this app here.

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.


Top comments (0)