Gemini API: Text Classification

You will use the Gemini API to classify what topics are relevant in the text.

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
        └── Text_Classification.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

const response = await ai.models.generateContent({
  model: MODEL_ID,
  contents: "Generate a 5 paragraph article about Sports, include one other topic",
});

tslab.display.markdown(response.text ?? "");

The Unseen Game: Sports and the Power of the Mind

From the roar of ancient coliseums to the hushed tension of a championship point, sports have captivated humanity across millennia. More than mere games, they are a universal language of competition, skill, and sheer human will. Whether it’s the electrifying speed of a sprinter, the strategic brilliance of a chess grandmaster (yes, it’s a sport!), or the coordinated ballet of a football team, sports offer a dynamic spectacle that transcends cultural boundaries. They celebrate the physical peak of human potential, demanding years of dedication, relentless training, and an unwavering commitment to mastery.

The physical demands of sport are undeniable. Athletes push their bodies to the absolute limit, developing incredible strength, endurance, agility, and precision. Every muscle fiber, every breath, every practiced movement is honed to perfection. Hours are spent in gyms, on tracks, and in arenas, refining techniques and building the physical resilience needed to endure the rigors of competition. This dedication not only showcases extraordinary athletic prowess but also inspires countless individuals to pursue healthier, more active lifestyles, recognizing the profound benefits of physical activity.

Yet, beneath the visible spectacle of physical exertion lies a profound and often overlooked battle: the psychological game. The field of sports psychology reveals that mental fortitude is as crucial as, if not more important than, physical talent. Athletes must possess incredible resilience to bounce back from defeat, the focus to execute complex strategies under immense pressure, and the self-belief to perform at their peak when everything is on the line. The ability to manage anxiety, maintain concentration amidst chaos, and foster unshakeable team synergy are all psychological skills that can separate a good athlete from a legendary one, turning potential into tangible victory.

Beyond individual performance, sports are potent crucibles for life lessons, deeply intertwined with the psychological skills they foster. They teach discipline, fair play, leadership, and the invaluable experience of both winning gracefully and losing with dignity. Team sports, in particular, underscore the importance of collaboration and communication, demonstrating how diverse individuals can unite for a common goal. For fans, sports provide a powerful sense of community and shared identity, offering an emotional outlet and a connection to something larger than themselves. The collective joy of victory or the shared anguish of defeat forge bonds that transcend everyday life.

In essence, sports are a rich tapestry woven with threads of physical artistry, mental resilience, and powerful community engagement. They reflect humanity’s innate drive to compete, to excel, and to connect. By pushing the boundaries of what’s physically possible and mastering the unseen game of the mind, athletes inspire us all to discover our own potential, proving that the true measure of success often lies not just in the final score, but in the journey of relentless self-improvement and the indomitable spirit that propels us forward.

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

const topicSchema = z.object({
  topic: z.string(),
  relevance: z.enum(["weak", "medium", "strong"]),
});

const responseSchema = z.object({
  topics: z.array(topicSchema),
});

const responseSchemaJson = zodToJsonSchema(responseSchema);

const SYSTEM_PROMPT = `
  Generate topics from text. Ensure that topics are general e.g. "Health".
  Strong relevance is obtained when the topic is a core tenent of the content
  and weak relevance reflects one or two mentions.
`;
const topicsResponse = await ai.models.generateContent({
  model: MODEL_ID,
  contents: response.text ?? "",
  config: {
    systemInstruction: SYSTEM_PROMPT,
    responseJsonSchema: responseSchemaJson,
    responseMimeType: "application/json",
  },
});
console.log(JSON.stringify(JSON.parse(topicsResponse.text ?? "{}"), null, 2));
{
  "topics": [
    {
      "relevance": "strong",
      "topic": "Sports"
    },
    {
      "relevance": "strong",
      "topic": "Sports Psychology"
    },
    {
      "relevance": "medium",
      "topic": "Physical Fitness"
    },
    {
      "relevance": "medium",
      "topic": "Teamwork"
    },
    {
      "relevance": "medium",
      "topic": "Personal Development"
    }
  ]
}

Summary

Now, you know how to classify text into different categories. Feel free to experiment with other texts, or provide a specific set of possible topics.

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