Gemini API: Sentiment Analysis

You will use the Gemini to extract sentiment scores of reviews.

Setup

Install the Google GenAI SDK

Install the Google GenAI SDK from npm.

$ npm install @google/genai

Setup your API key

You can create your API key using Google AI Studio with a single click.

Remember to treat your API key like a password. Don’t accidentally save it in a notebook or source file you later commit to GitHub. In this notebook we will be storing the API key in a .env file. You can also set it as an environment variable or use a secret manager.

Here’s how to set it up in a .env file:

$ touch .env
$ echo "GEMINI_API_KEY=<YOUR_API_KEY>" >> .env
Tip

Another option is to set the API key as an environment variable. You can do this in your terminal with the following command:

$ export GEMINI_API_KEY="<YOUR_API_KEY>"

Load the API key

To load the API key from the .env file, we will use the dotenv package. This package loads environment variables from a .env file into process.env.

$ npm install dotenv

Then, we can load the API key in our code:

const dotenv = require("dotenv") as typeof import("dotenv");

dotenv.config({
  path: "../../.env",
});

const GEMINI_API_KEY = process.env.GEMINI_API_KEY ?? "";
if (!GEMINI_API_KEY) {
  throw new Error("GEMINI_API_KEY is not set in the environment variables");
}
console.log("GEMINI_API_KEY is set in the environment variables");
GEMINI_API_KEY is set in the environment variables
Note

In our particular case the .env is is two directories up from the notebook, hence we need to use ../../ to go up two directories. If the .env file is in the same directory as the notebook, you can omit it altogether.

│
├── .env
└── examples
    └── json_capabilities
        └── Sentiment_Analysis.ipynb

Initialize SDK Client

With the new SDK, now you only need to initialize a client with you API key (or OAuth if using Vertex AI). The model is now set in each call.

const google = require("@google/genai") as typeof import("@google/genai");

const ai = new google.GoogleGenAI({ apiKey: GEMINI_API_KEY });

Select a model

Now select the model you want to use in this guide, either by selecting one in the list or writing it down. Keep in mind that some models, like the 2.5 ones are thinking models and thus take slightly more time to respond (cf. thinking notebook for more details and in particular learn how to switch the thiking off).

const tslab = require("tslab") as typeof import("tslab");

const MODEL_ID = "gemini-2.5-flash-preview-05-20";

Example

import { z } from "zod";
import { zodToJsonSchema } from "zod-to-json-schema";

const magnitudeEnum = z.enum(["weak", "medium", "strong"]);
const sentimentSchema = z.object({
  postiveSentimentScore: magnitudeEnum,
  negativeSentimentScore: magnitudeEnum,
  neutralSentimentScore: magnitudeEnum,
});

const sentimentSchemaJson: Record<string, unknown> = zodToJsonSchema(sentimentSchema, {
  $refStrategy: "none",
});

const SYSTEM_PROMPT = `Generate each sentiment score probability (positive, negative, or neutral) for the whole text.`;
const negative_review =
  "This establishment is an insult to the culinary arts, with inedible food that left me questioning the chef's sanity and the health inspector's judgment.";
const positive_review =
  "This restaurant is a true gem with impeccable service and a menu that tantalizes the taste buds. Every dish is a culinary masterpiece, crafted with fresh ingredients and bursting with flavor.";
const neutral_review =
  "The restaurant offers a decent dining experience with average food and service, making it a passable choice for a casual meal.";

Take a look at each of the probabilities returned to see how each of these reviews would be classified by the Gemini model.

Helper function to generate content from sentiment llm:

async function generateReview(content: string) {
  const response = await ai.models.generateContent({
    model: MODEL_ID,
    contents: content,
    config: {
      systemInstruction: SYSTEM_PROMPT,
      responseMimeType: "application/json",
      responseSchema: sentimentSchemaJson,
    },
  });
  tslab.display.markdown(`\n\`\`\`json\n${JSON.stringify(JSON.parse(response.text ?? "{}"), null, 2)}\n\`\`\``);
}
await generateReview(negative_review);
{
  "negativeSentimentScore": "strong",
  "neutralSentimentScore": "weak",
  "postiveSentimentScore": "weak"
}
await generateReview(positive_review);
{
  "negativeSentimentScore": "weak",
  "neutralSentimentScore": "weak",
  "postiveSentimentScore": "strong"
}
await generateReview(neutral_review);
{
  "negativeSentimentScore": "weak",
  "neutralSentimentScore": "strong",
  "postiveSentimentScore": "weak"
}

Summary

You have now used the Gemini API to analyze the sentiment of restaurant reviews using structured data. Try out other types of texts, such as comments under a video or emails.

Please see the other notebooks in this directory to learn more about how you can use the Gemini API for other JSON related tasks.