Gemini और Vertex AI की मदद से, Gmail में मौजूद मैसेज का विश्लेषण करना और उन्हें लेबल करना

क्या आपके पास पांच मिनट हैं?
ऑनलाइन सर्वे में हिस्सा लेकर, Google Workspace के दस्तावेज़ को बेहतर बनाने में हमारी मदद करें.

यह समाधान, Gmail मैसेज का विश्लेषण करने और उनके भाव के आधार पर उन्हें लेबल करने के लिए, Vertex AI और Gemini का इस्तेमाल करता है.

कोडिंग का लेवल: इंटरमीडिएट
अवधि: 30 मिनट
प्रोजेक्ट का टाइप: Google Workspace ऐड-ऑन

  • यह Google Workspace ऐड-ऑन है, जो Gmail को साइडबार में दिखाता है.
    पहली इमेज: भावनाओं का विश्लेषण करने वाले ऐड-ऑन से, Gmail में एक साइडबार दिखता है. इसमें उपयोगकर्ता, Gemini को मैसेज का विश्लेषण करने और भावनाओं के आधार पर लेबल लगाने के लिए प्रॉम्प्ट दे सकते हैं.
  • Gmail पर मिला ऐसा ईमेल जिसमें न तो सकारात्मक और न ही नकारात्मक भावनाएं ज़ाहिर की गई हैं.
    दूसरी इमेज: ऐड-ऑन, Gmail मैसेज को सामान्य टोन 😐 के तौर पर लेबल करता है.
  • खुशी ज़ाहिर करने वाला Gmail मैसेज.
    तीसरी इमेज: ऐड-ऑन, Gmail मैसेज को खुशमिज़ाज 😊 लेबल करता है.
  • Gmail पर भेजा गया ऐसा ईमेल जिसमें नाखुशी ज़ाहिर की गई हो.
    चौथी इमेज: ऐड-ऑन, Gmail मैसेज को गुस्से वाली टोन 😡 लेबल करता है.

मकसद

  • समझें कि समाधान क्या करता है.
  • जानें कि Google की सेवाएं, समाधान में क्या करती हैं.
  • एनवायरमेंट सेट अप करें.
  • Google Apps Script प्रोजेक्ट सेट अप करें.
  • स्क्रिप्ट चलाएं.

इस समाधान के बारे में जानकारी

भावनाओं का विश्लेषण करने वाले Google Workspace ऐड-ऑन का स्क्रीनशॉट

यह समाधान, Google Workspace का एक ऐड-ऑन है. यह Gmail मैसेज के भाव के आधार पर लेबल लागू करता है. मैसेज के कॉन्टेंट का विश्लेषण करने के लिए, ऐड-ऑन Vertex AI का इस्तेमाल करता है. इससे Gemini 2.5 Flash मॉडल को प्रॉम्प्ट किया जाता है. इसके बाद, यह मॉडल इनमें से कोई एक जवाब देता है:

  • अच्छी समीक्षाएं
  • नेगेटिव
  • ठीक-ठाक

Gemini से मिले जवाब के आधार पर, ऐड-ऑन मैसेज में Gmail का लेबल जोड़ता है.

Vertex AI API से किए जाने वाले अनुरोध को सीमित करने के लिए, यह ऐड-ऑन सिर्फ़ Gmail उपयोगकर्ता के इनबॉक्स में मौजूद 10 सबसे नए मैसेज का विश्लेषण करता है और उन पर लेबल लगाता है. कोटा और सीमाओं के बारे में ज़्यादा जानने के लिए, Vertex AI के दस्तावेज़ पर जाएं.

यह कैसे काम करता है

यह समाधान Google Apps Script में बनाया गया है. इसमें Google की इन सेवाओं और प्रॉडक्ट का इस्तेमाल किया जाता है:

  • Vertex AI API–यह Gemini 2.5 Flash मॉडल को Gmail मैसेज के कॉन्टेंट का विश्लेषण करने और भावना का पता लगाने के लिए प्रॉम्प्ट करता है.
  • Apps Script की सेवाएं:

    • Gmail सेवा–यह Gmail मैसेज के लिए लेबल वापस लाती है और उन्हें लागू करती है. यह ऐड-ऑन को टेस्ट करने के लिए, सैंपल मैसेज बनाता है. हालांकि, ऐसा करना ज़रूरी नहीं है.
    • कार्ड सेवा–यह ऐड-ऑन का यूज़र इंटरफ़ेस बनाती है. यह इंटरफ़ेस, Gmail में साइडबार के तौर पर दिखता है.
    • यूआरएल फ़ेच करने की सेवा–यह भावना विश्लेषण के लिए Vertex AI API से कनेक्ट होती है.
    • Script service– Vertex AI API को कॉल करने के लिए, यह getOAuthToken तरीके का इस्तेमाल करके, ऐड-ऑन के लिए OAuth 2.0 ऐक्सेस टोकन हासिल करता है.

ज़रूरी शर्तें

अपना एनवायरमेंट सेट अप करने का तरीका

इस सेक्शन में, Google Cloud Console और Apps Script में अपने एनवायरमेंट को कॉन्फ़िगर और सेट अप करने का तरीका बताया गया है.

Google Cloud Console में जाकर, अपना Cloud प्रोजेक्ट कॉन्फ़िगर करना

इस सेक्शन में, Vertex AI API को चालू करने और अपने Cloud प्रोजेक्ट में OAuth सहमति स्क्रीन को कॉन्फ़िगर करने का तरीका बताया गया है.

Vertex AI API चालू करना

  1. Google Cloud Console में, अपना Google Cloud प्रोजेक्ट खोलें और Vertex AI API चालू करें:

    एपीआई चालू करना

  2. पुष्टि करें कि आपने सही Cloud प्रोजेक्ट में एपीआई चालू किया है. इसके बाद, आगे बढ़ें पर क्लिक करें.

  3. पुष्टि करें कि आपने सही एपीआई चालू किया है. इसके बाद, चालू करें पर क्लिक करें.

उस स्क्रीन को कॉन्फ़िगर करना जहां OAuth के लिए सहमति दी जाती है

Google Workspace ऐड-ऑन के लिए, सहमति लेने वाली स्क्रीन को कॉन्फ़िगर करना ज़रूरी है. अपने ऐड-ऑन के लिए, OAuth की सहमति वाली स्क्रीन को कॉन्फ़िगर करने से यह तय होता है कि Google, उपयोगकर्ताओं को क्या दिखाएगा.

  1. Google Cloud Console में, मेन्यू &gt &gt ब्रैंडिंग पर जाएं.

    ब्रैंडिंग पर जाएं

  2. अगर आपने पहले ही को कॉन्फ़िगर कर लिया है, तो ब्रैंडिंग, दर्शक, और डेटा ऐक्सेस में जाकर, OAuth सहमति स्क्रीन की इन सेटिंग को कॉन्फ़िगर किया जा सकता है. अगर आपको अभी तक कॉन्फ़िगर नहीं किया गया है मैसेज दिखता है, तो शुरू करें पर क्लिक करें:
    1. ऐप्लिकेशन की जानकारी में जाकर, ऐप्लिकेशन का नाम में ऐप्लिकेशन का नाम डालें.
    2. उपयोगकर्ता सहायता के लिए ईमेल पता में, सहायता के लिए वह ईमेल पता चुनें जिस पर उपयोगकर्ता, सहमति से जुड़े सवालों के लिए आपसे संपर्क कर सकें.
    3. आगे बढ़ें पर क्लिक करें.
    4. दर्शक सेक्शन में जाकर, संगठन के अंदर से जनरेट होने वाला ट्रैफ़िक चुनें.
    5. आगे बढ़ें पर क्लिक करें.
    6. संपर्क जानकारी में जाकर, वह ईमेल पता डालें जिस पर आपको अपने प्रोजेक्ट में हुए किसी भी बदलाव की सूचना मिल सके.
    7. आगे बढ़ें पर क्लिक करें.
    8. पूरा करें में जाकर, Google API सेवाओं के उपयोगकर्ता के डेटा की नीति पढ़ें. अगर आप इससे सहमत हैं, तो मैं Google API सेवाओं के उपयोगकर्ता के डेटा की नीति से सहमत हूं को चुनें.
    9. जारी रखें पर क्लिक करें.
    10. बनाएं पर क्लिक करें.
  3. फ़िलहाल, स्कोप जोड़ने की प्रोसेस को स्किप किया जा सकता है. अगर आपको आने वाले समय में, अपने Google Workspace संगठन के बाहर इस्तेमाल करने के लिए कोई ऐप्लिकेशन बनाना है, तो आपको उपयोगकर्ता का टाइप बदलकर बाहरी करना होगा. इसके बाद, अपने ऐप्लिकेशन के लिए ज़रूरी अनुमति के स्कोप जोड़ें. ज़्यादा जानने के लिए, OAuth की सहमति कॉन्फ़िगर करना गाइड पढ़ें.

Apps Script प्रोजेक्ट बनाना और उसे सेट अप करना

ऐड-ऑन के लिए Apps Script प्रोजेक्ट बनाने और उसे सेट अप करने के लिए, यह तरीका अपनाएं:

  1. Gemini और Vertex AI की मदद से, Gmail में मौजूद ईमेल के बारे में जानकारी पाने की सुविधा वाले Apps Script प्रोजेक्ट को खोलने के लिए, यहां दिए गए बटन पर क्लिक करें.
    Apps Script प्रोजेक्ट खोलें

  2. खास जानकारी पर क्लिक करें.

  3. खास जानकारी वाले पेज पर, कॉपी बनाएं कॉपी बनाने का आइकॉन पर क्लिक करें.

  4. अपने Cloud प्रोजेक्ट का नंबर पाएं:

    1. Google Cloud console में, मेन्यू &gt IAM और एडमिन &gt सेटिंग पर जाएं.

      आईएएम और एडमिन सेटिंग पर जाएं

    2. प्रोजेक्ट नंबर फ़ील्ड में, वैल्यू कॉपी करें.
  5. अपने Cloud प्रोजेक्ट को Apps Script प्रोजेक्ट से कनेक्ट करें:

    1. कॉपी किए गए Apps Script प्रोजेक्ट में जाकर, प्रोजेक्ट सेटिंग प्रोजेक्ट सेटिंग का आइकॉन पर क्लिक करें.
    2. Google Cloud Platform (GCP) प्रोजेक्ट में जाकर, प्रोजेक्ट बदलें पर क्लिक करें.
    3. GCP प्रोजेक्ट नंबर में, Cloud प्रोजेक्ट नंबर चिपकाएं.
    4. प्रोजेक्ट सेट करें पर क्लिक करें.

ऐड-ऑन की जांच करना

ऐड-ऑन को आज़माने के लिए, टेस्ट डिप्लॉयमेंट इंस्टॉल करें. इसके बाद, Gmail में ऐड-ऑन खोलें:

  1. Apps Script का टेस्ट डिप्लॉयमेंट बनाएं और इंस्टॉल करें:
    1. कॉपी किए गए Apps Script प्रोजेक्ट में, एडिटर पर क्लिक करें.
    2. Code.gs फ़ाइल खोलें और चलाएं पर क्लिक करें. जब आपसे कहा जाए, तब स्क्रिप्ट की अनुमति दें.
    3. डिप्लॉय करें > टेस्ट डिप्लॉयमेंट पर क्लिक करें.
    4. इंस्टॉल करें > हो गया पर क्लिक करें.
  2. Gmail खोलें.

    Gmail पर जाएं

  3. दाईं ओर मौजूद साइडबार में, ऐड-ऑन Sentiment Analysis खोलें.

  4. अगर कहा जाए, तो ऐड-ऑन को अनुमति दें.

  5. ज़रूरी नहीं: अपने ऐड-ऑन के साथ टेस्ट करने के लिए मैसेज बनाने के लिए, सैंपल ईमेल जनरेट करें पर क्लिक करें. आपके इनबॉक्स में तीन मैसेज दिखते हैं. अगर आपको ये नहीं दिख रहे हैं, तो पेज को रीफ़्रेश करें.

  6. लेबल जोड़ने के लिए, ईमेल का विश्लेषण करें पर क्लिक करें.

यह ऐड-ऑन, आपके इनबॉक्स में मौजूद 10 नए मैसेज की समीक्षा करता है. इसके बाद, मैसेज के कॉन्टेंट के आधार पर, इनमें से कोई एक लेबल लागू करता है:

  • खुशी वाली टोन 😊
  • सामान्य टोन 😐
  • अपसेट टोन 😡

कोड की समीक्षा करना

इस समाधान के लिए, Apps Script कोड की समीक्षा करें:

सोर्स कोड देखें

Code.gs

gmail-sentiment-analysis/Code.gs
/*
Copyright 2024 Google LLC

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    https://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

/**
 * Triggered when the add-on is opened from the Gmail homepage.
 *
 * @param {Object} e - The event object.
 * @returns {Card} - The homepage card.
 */
function onHomepageTrigger(e) {
  return buildHomepageCard();
}

Cards.gs

gmail-sentiment-analysis/Cards.gs
/*
Copyright 2024-2025 Google LLC

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    https://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

/**
 * Builds the main card displayed on the Gmail homepage.
 *
 * @returns {Card} - The homepage card.
 */
function buildHomepageCard() {
  // Create a new card builder
  const cardBuilder = CardService.newCardBuilder();

  // Create a card header
  const cardHeader = CardService.newCardHeader();
  cardHeader.setImageUrl('https://fonts.gstatic.com/s/i/googlematerialicons/mail/v6/black-24dp/1x/gm_mail_black_24dp.png');
  cardHeader.setImageStyle(CardService.ImageStyle.CIRCLE);
  cardHeader.setTitle("Analyze your Gmail");

  // Add the header to the card
  cardBuilder.setHeader(cardHeader);

  // Create a card section
  const cardSection = CardService.newCardSection();

  // Create buttons for generating sample emails and analyzing sentiment
  const buttonSet = CardService.newButtonSet();

  // Create "Generate sample emails" button
  const generateButton = createFilledButton('Generate sample emails', 'generateSampleEmails', '#34A853');
  buttonSet.addButton(generateButton);

  // Create "Analyze emails" button
  const analyzeButton = createFilledButton('Analyze emails', 'analyzeSentiment', '#FF0000');
  buttonSet.addButton(analyzeButton);

  // Add the button set to the section
  cardSection.addWidget(buttonSet);

  // Add the section to the card
  cardBuilder.addSection(cardSection);

  // Build and return the card
  return cardBuilder.build();
}

/**
 * Creates a filled text button with the specified text, function, and color.
 *
 * @param {string} text - The text to display on the button.
 * @param {string} functionName - The name of the function to call when the button is clicked.
 * @param {string} color - The background color of the button.
 * @returns {TextButton} - The created text button.
 */
function createFilledButton(text, functionName, color) {
  // Create a new text button
  const textButton = CardService.newTextButton();

  // Set the button text
  textButton.setText(text);

  // Set the action to perform when the button is clicked
  const action = CardService.newAction();
  action.setFunctionName(functionName);
  textButton.setOnClickAction(action);

  // Set the button style to filled
  textButton.setTextButtonStyle(CardService.TextButtonStyle.FILLED);

  // Set the background color
  textButton.setBackgroundColor(color);

  return textButton;
}

/**
 * Creates a notification response with the specified text.
 *
 * @param {string} notificationText - The text to display in the notification.
 * @returns {ActionResponse} - The created action response.
 */
function buildNotificationResponse(notificationText) {
  // Create a new notification
  const notification = CardService.newNotification();
  notification.setText(notificationText);

  // Create a new action response builder
  const actionResponseBuilder = CardService.newActionResponseBuilder();

  // Set the notification for the action response
  actionResponseBuilder.setNotification(notification);

  // Build and return the action response
  return actionResponseBuilder.build();
}

Gmail.gs

gmail-sentiment-analysis/Gmail.gs
/*
Copyright 2024-2025 Google LLC

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    https://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

/**
 * Analyzes the sentiment of the first 10 threads in the inbox
 * and labels them accordingly.
 *
 * @returns {ActionResponse} - A notification confirming completion.
 */
function analyzeSentiment() {
  // Analyze and label emails
  analyzeAndLabelEmailSentiment();

  // Return a notification
  return buildNotificationResponse("Successfully completed sentiment analysis");
}

/**
 * Analyzes the sentiment of emails and applies appropriate labels.
 */
function analyzeAndLabelEmailSentiment() {
  // Define label names
  const labelNames = ["HAPPY TONE 😊", "NEUTRAL TONE 😐", "UPSET TONE 😡"];

  // Get or create labels for each sentiment
  const positiveLabel = GmailApp.getUserLabelByName(labelNames[0]) || GmailApp.createLabel(labelNames[0]);
  const neutralLabel = GmailApp.getUserLabelByName(labelNames[1]) || GmailApp.createLabel(labelNames[1]);
  const negativeLabel = GmailApp.getUserLabelByName(labelNames[2]) || GmailApp.createLabel(labelNames[2]);

  // Get the first 10 threads in the inbox
  const threads = GmailApp.getInboxThreads(0, 10);

  // Iterate through each thread
  for (const thread of threads) {
    // Iterate through each message in the thread
    const messages = thread.getMessages();
    for (const message of messages) {
      // Get the plain text body of the message
      const emailBody = message.getPlainBody();

      // Analyze the sentiment of the email body
      const sentiment = processSentiment(emailBody);

      // Apply the appropriate label based on the sentiment
      if (sentiment === 'positive') {
        thread.addLabel(positiveLabel);
      } else if (sentiment === 'neutral') {
        thread.addLabel(neutralLabel);
      } else if (sentiment === 'negative') {
        thread.addLabel(negativeLabel);
      }
    }
  }
}

/**
 * Generates sample emails for testing the sentiment analysis.
 *
 * @returns {ActionResponse} - A notification confirming email generation.
 */
function generateSampleEmails() {
  // Get the current user's email address
  const userEmail = Session.getActiveUser().getEmail();

  // Define sample emails
  const sampleEmails = [
    {
      subject: 'Thank you for amazing service!',
      body: 'Hi, I really enjoyed working with you. Thank you again!',
      name: 'Customer A'
    },
    {
      subject: 'Request for information',
      body: 'Hello, I need more information on your recent product launch. Thank you.',
      name: 'Customer B'
    },
    {
      subject: 'Complaint!',
      body: '',
      htmlBody: `<p>Hello, You are late in delivery, again.</p>
<p>Please contact me ASAP before I cancel our subscription.</p>`,
      name: 'Customer C'
    }
  ];

  // Send each sample email
  for (const email of sampleEmails) {
    GmailApp.sendEmail(userEmail, email.subject, email.body, {
      name: email.name,
      htmlBody: email.htmlBody
    });
  }

  // Return a notification
  return buildNotificationResponse("Successfully generated sample emails");
}

Vertex.gs

gmail-sentiment-analysis/Vertex.gs
/*
Copyright 2024-2025 Google LLC

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    https://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

// Replace with your project ID
const PROJECT_ID = '[ADD YOUR GCP PROJECT ID HERE]';

// Location for your Vertex AI model
const VERTEX_AI_LOCATION = 'us-central1';

// Model ID to use for sentiment analysis
const MODEL_ID = 'gemini-2.5-flash';

/**
 * Sends the email text to Vertex AI for sentiment analysis.
 *
 * @param {string} emailText - The text of the email to analyze.
 * @returns {string} - The sentiment of the email ('positive', 'negative', or 'neutral').
 */
function processSentiment(emailText) {
  // Construct the API endpoint URL
  const apiUrl = `https://${VERTEX_AI_LOCATION}-aiplatform.googleapis.com/v1/projects/${PROJECT_ID}/locations/${VERTEX_AI_LOCATION}/publishers/google/models/${MODEL_ID}:generateContent`;

  // Prepare the request payload
  const payload = {
    contents: [
      {
        role: "user",
        parts: [
          {
            text: `Analyze the sentiment of the following message: ${emailText}`
          }
        ]
      }
    ],
    generationConfig: {
      temperature: 0.9,
      maxOutputTokens: 1024,
      responseMimeType: "application/json",
      // Expected response format for simpler parsing.
      responseSchema: {
        type: "object",
        properties: {
          response: {
            type: "string",
            enum: ["positive", "negative", "neutral"]
          }
        }
      }
    }
  };

  // Prepare the request options
  const options = {
    method: 'POST',
    headers: {
      'Authorization': `Bearer ${ScriptApp.getOAuthToken()}`
    },
    contentType: 'application/json',
    muteHttpExceptions: true, // Set to true to inspect the error response
    payload: JSON.stringify(payload)
  };

  // Make the API request
  const response = UrlFetchApp.fetch(apiUrl, options);

  // Parse the response. There are two levels of JSON responses to parse.
  const parsedResponse = JSON.parse(response.getContentText());
  const sentimentResponse = JSON.parse(parsedResponse.candidates[0].content.parts[0].text).response;

  // Return the sentiment
  return sentimentResponse;
}

appsscript.json

gmail-sentiment-analysis/appsscript.json
{
  "timeZone": "America/Toronto",
  "oauthScopes": [
    "https://www.googleapis.com/auth/cloud-platform",
    "https://www.googleapis.com/auth/gmail.addons.execute",
    "https://www.googleapis.com/auth/gmail.labels",
    "https://www.googleapis.com/auth/gmail.modify",
    "https://www.googleapis.com/auth/script.external_request",
    "https://www.googleapis.com/auth/userinfo.email"
  ],
  "addOns": {
    "common": {
      "name": "Sentiment Analysis",
      "logoUrl": "https://fonts.gstatic.com/s/i/googlematerialicons/sentiment_extremely_dissatisfied/v6/black-24dp/1x/gm_sentiment_extremely_dissatisfied_black_24dp.png"
    },
    "gmail": {
      "homepageTrigger": {
        "runFunction": "onHomepageTrigger",
        "enabled": true
      }
    }
  },
  "exceptionLogging": "STACKDRIVER",
  "runtimeVersion": "V8"
}

व्यवस्थित करें

इस ट्यूटोरियल में इस्तेमाल किए गए संसाधनों के लिए, अपने Google Cloud खाते से शुल्क न लिए जाने से बचने के लिए, हमारा सुझाव है कि आप Cloud प्रोजेक्ट मिटा दें.

  1. Google Cloud Console में, संसाधन मैनेज करें पेज पर जाएं. मेन्यू > IAM और एडमिन > संसाधन मैनेज करें पर क्लिक करें.

    Resource Manager पर जाएं

  2. प्रोजेक्ट की सूची में, वह प्रोजेक्ट चुनें जिसे आपको मिटाना है. इसके बाद, मिटाएं पर क्लिक करें.
  3. डायलॉग बॉक्स में, प्रोजेक्ट आईडी टाइप करें. इसके बाद, प्रोजेक्ट मिटाने के लिए बंद करें पर क्लिक करें.

अगले चरण