This article explores the process of building a text summarization web application using the Gemini API, a powerful language model from Google AI.
Text summarization is a natural language processing (NLP) technique that condenses a lengthy text into a shorter, more concise version that retains the most important information. It is commonly used for reducing reading time, improving comprehension, and supporting academic work.
Gemini AI, developed by Google AI, is a cutting-edge large language model (LLM) considered one of the most powerful and versatile AI models currently available, boasting exceptional capabilities in understanding and generating various forms of data, including text, images, audio, and code, all within a single, multimodal framework.
There are two main types of text summarization: extractive and abstractive.
This method selects a subset of sentences, phrases, or words from the original text to create the summary. It's similar to highlighting the most important parts of a text. Extractive summarization is a good choice for applications where correctness is important, like summarizing medical or legal documents.
This method uses natural language techniques to rewrite the main ideas of the text to create a more coherent summary. It's similar to writing a summary with a pen, as it can create new phrases and sentences. Abstractive summarization is often better for unstructured or convoluted information, like in conversations.
To develop a text summarization API, I am using Node.js as the backend.
First, I need to install Node.js on my machine, so I just visited Node.js Download. Now I am using Visual Studio Code Editor as my IDE.
To setup a node.js project, you need to open a folder on your VS Code Editor and use this command on your terminal.
npm init -y
Next step we need to create a file named something you like by ending .js remember to follow the rules of naming a file in computer programming. To access the Gemini API, we need to install @google/generative-ai this npm package on your project by using this command.
npm i @google/generative-ai
You can copy your Gemini API key by visiting Google's website, Gemini Developer.
To create a text summarisation API, we need to create a web server in node.js, so I chose the express.js npm package for it. You can download the express.js package from npm by using this command.
npm i express
To run the web server, we need to download some other npm packages named dotenv, body-parser, and cors.
npm i dotenv body-parser cors
All set, it's time to create a text summarization API by using the Gemini API. Our API server works by the user input valu sending to Gemini API by using a custom prompt, for example, "Summarize the following text in a concise paragraph:\n\n${content}. Provide only the summary paragraph without any introductory words or explanations," then the Gemini API response with the summarized paragraph.
Now is the time to create a web server that processes the user-given long text into a summarized paragraph, so you need to follow these steps to create a simple API server in Node.js.
require("dotenv").config();
const express = require("express");
const app = express();
const bp = require('body-parser');
const cors = require("cors");
const { GoogleGenerativeAI } = require("@google/generative-ai");
const genAI = new GoogleGenerativeAI(process.env.API_KEY); // Replace with your actual API key
const model = genAI.getGenerativeModel({ model: "gemini-1.5-flash" });
app.use(bp.json());
app.use(bp.urlencoded({ extended: true }));
app.use(cors({
origin: "*", // Allow any origin
methods: ["GET", "POST"], // Allow specific HTTP methods
allowedHeaders: ["Content-Type"] // Allow specific headers
}));
app.get("/", (req, res) => res.send("Hello world"));
app.post("/api/pargraph/summery", async (req, res) => {
try {
if (!req.body.content) return res.status(400).json({ error: "Invalid Request", message: "Content is required for summarization." });
const result = await model.generateContent(`Summarize the following text in a concise paragraph:\n\n${req.body.content}. Provide only the summary paragraph without any introductory words or explanations.`);
if (!result || !result.response || !result.response.candidates || !result.response.candidates[0]) return res.status(500).json({ error: "Processing Error", message: "Failed to generate summary. Please try again later." });
res.status(200).json({ response: result.response.candidates[0].content.parts[0].text });
} catch (error) {
console.error("Error generating content:", error);
res.status(500).json({
error: "Internal Server Error",
message: "An error occurred while processing your request. Currently, we are experiencing a high volume of traffic. Please try to generate your request one more time."
});
}
});
app.get("*", (req, res) => res.status(404).json({
error: "Not Found",
message: "The requested API route does not exist."
}));
app.post("*", (req, res) => res.status(404).json({
error: "Not Found",
message: "The requested API route does not exist."
}));
app.listen(3003, () => console.log("Server ready on port 3003."));
I just stored my Gemini API key on a .env file to secure my API key.
Its time to test our API. In this case, I am using insomnia to call my API from my local network. You can use any other tools to call the API, for example, Postman.
POST: http://localhost:3003/api/pargraph/summery
{
"content": "The journey of Muhammed Sajad PP, also known as Sajad or Saju, alongside his co-founder Adil Nasar KC, from navigating the challenges of Covid-19 to establishing a thriving tech startup exemplifies resilience, innovation, and a passion for technology. Early Ventures into Technology Born with a natural curiosity for computers and technology, Sajad’s journey began long before the pandemic. With a solid foundation in programming languages like JavaScript, TypeScript, Python, and C++, Sajad honed his skills through diverse projects ranging from backend development to video editing and photography. Navigating the Covid-19 Pandemic The onset of the Covid-19 pandemic presented unforeseen challenges globally. For Sajad and Adil, it became a pivotal moment. As the world adapted to remote work and digital transformation accelerated, they embraced these changes, leveraging their skills in web design, SEO, and machine learning to navigate the new normal. Founding Grovix Lab Fuelled by a passion for innovation and a desire to make a meaningful impact, Sajad and Adil founded Grovix Lab. This tech startup serves as a hub for AI research and product development, focusing on cutting-edge technologies that shape the future. Under their leadership, Grovix Lab has become synonymous with creativity and technical excellence. Diverse Skill Set and Leadership Sajad’s multifaceted background as a backend developer, video editor, photographer, and web designer, combined with Adil’s expertise, has been instrumental in Grovix Lab’s success. Their ability to seamlessly integrate technical expertise with creative vision has enabled the company to thrive in competitive landscapes. Inspiration and Vision Inspired by visionaries like Elon Musk and companies like Nvidia and OpenAI, Sajad and Adil continue to push boundaries. Their dedication to merging electronics, programming, videography, marketing, and entrepreneurship reflects a commitment to holistic innovation. Future Endeavors Looking ahead, Sajad, also known as Saju, and Adil remain focused on expanding Grovix Lab’s impact. Whether through groundbreaking AI projects, collaborative ventures, or community outreach, their journey from weathering a global crisis to founding a tech powerhouse serves as a testament to resilience, innovation, and the transformative power of technology."
}
{
"response": "Muhammed Sajad PP, or Sajad/Saju, and co-founder Adil Nasar KC, leveraged their diverse skillsets in technology and a passion for innovation to navigate the challenges of the Covid-19 pandemic and establish Grovix Lab, a thriving tech startup. Grovix Lab, driven by their expertise in AI research and product development, focuses on cutting-edge technologies shaping the future. Inspired by visionaries like Elon Musk and companies like Nvidia and OpenAI, Sajad and Adil continue to push boundaries, merging electronics, programming, videography, marketing, and entrepreneurship to achieve holistic innovation. Their journey exemplifies resilience, innovation, and the transformative power of technology. \n"
}
Join Sajad on Peerlist!
Join amazing folks like Sajad and thousands of other people in tech.
Create ProfileJoin with Sajad’s personal invite link.
1
7
0