From 8760fa1ea7d53b237859fda9f8a83c86e7e98bea Mon Sep 17 00:00:00 2001 From: Chanel Greco Date: Fri, 18 Oct 2024 13:37:57 +0200 Subject: [PATCH 1/3] Add new sample that is for a Google Workspace Add-on that adds sentiment analysis capabilities to Gmail. --- gmail-sentiment-analysis/Cards.gs | 67 +++++++++++++++++ gmail-sentiment-analysis/Code.gs | 25 +++++++ gmail-sentiment-analysis/Gmail.gs | 50 +++++++++++++ gmail-sentiment-analysis/README.md | 31 ++++++++ gmail-sentiment-analysis/Vertex.gs | 92 ++++++++++++++++++++++++ gmail-sentiment-analysis/appsscript.json | 33 +++++++++ 6 files changed, 298 insertions(+) create mode 100644 gmail-sentiment-analysis/Cards.gs create mode 100644 gmail-sentiment-analysis/Code.gs create mode 100644 gmail-sentiment-analysis/Gmail.gs create mode 100644 gmail-sentiment-analysis/README.md create mode 100644 gmail-sentiment-analysis/Vertex.gs create mode 100644 gmail-sentiment-analysis/appsscript.json diff --git a/gmail-sentiment-analysis/Cards.gs b/gmail-sentiment-analysis/Cards.gs new file mode 100644 index 000000000..566c1ca47 --- /dev/null +++ b/gmail-sentiment-analysis/Cards.gs @@ -0,0 +1,67 @@ +/* +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. +*/ + + +/** + * Builds the card for to display in the sidepanel of gmail. + * @return {CardService.Card} The card to show to the user. + */ + +function buildCard_GmailHome(notifyOk=false){ + const imageUrl ='https://icons.iconarchive.com/icons/roundicons/100-free-solid/48/spy-icon.png'; + const image = CardService.newImage() + .setImageUrl(imageUrl); + + const cardHeader = CardService.newCardHeader() + .setImageUrl(imageUrl) + .setImageStyle(CardService.ImageStyle.CIRCLE) + .setTitle("Analyze your GMail"); + + const action = CardService.newAction() + .setFunctionName('analyzeSentiment'); + const button = CardService.newTextButton() + .setText('Identify angry customers') + .setOnClickAction(action) + .setTextButtonStyle(CardService.TextButtonStyle.FILLED); + const buttonSet = CardService.newButtonSet() + .addButton(button); + + const section = CardService.newCardSection() + .setHeader("Emails sentiment analysis") + .addWidget(buttonSet); + + const card = CardService.newCardBuilder() + .setHeader(cardHeader) + .addSection(section); + +/** + * This builds the card that contains the footer that informs + * the user about the successful execution of the Add-on. + */ + +if(notifyOk==true){ + let fixedFooter = CardService.newFixedFooter() + .setPrimaryButton( + CardService.newTextButton() + .setText("Analysis complete") + .setOnClickAction( + CardService.newAction() + .setFunctionName( + "buildCard_GmailHome"))); + card.setFixedFooter(fixedFooter); +} + return card.build(); +} \ No newline at end of file diff --git a/gmail-sentiment-analysis/Code.gs b/gmail-sentiment-analysis/Code.gs new file mode 100644 index 000000000..143a5e1d9 --- /dev/null +++ b/gmail-sentiment-analysis/Code.gs @@ -0,0 +1,25 @@ +/* +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. +*/ + +/** + * Callback for rendering the homepage card. + * @return {CardService.Card} The card to show to the user. + */ +function onHomepage(e) { + if(e.hostApp =="gmail"){ + return buildCard_GmailHome(); + } +} \ No newline at end of file diff --git a/gmail-sentiment-analysis/Gmail.gs b/gmail-sentiment-analysis/Gmail.gs new file mode 100644 index 000000000..e3fab9463 --- /dev/null +++ b/gmail-sentiment-analysis/Gmail.gs @@ -0,0 +1,50 @@ +/* +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. +*/ + +/** + * Callback for initiating the sentiment analysis. + * @return {CardService.Card} The card to show to the user. + */ + +function analyzeSentiment(){ + emailSentiment(); + return buildCard_GmailHome(true); +} + +/** + * Gets the last 10 threads in the inbox and the corresponding messages. + * Fetches the label that should be applied to negative messages. + * The processSentiment is called on each message + * and testet with RegExp to check for a negative answer from the model + */ + +function emailSentiment() { + const threads = GmailApp.getInboxThreads(0, 10); + const msgs = GmailApp.getMessagesForThreads(threads); + const label_upset = GmailApp.getUserLabelByName("UPSET TONE 😡"); + const regex = new RegExp('N'); + let currentPrediction; + + for (let i = 0 ; i < msgs.length; i++) { + for (let j = 0; j < msgs[i].length; j++) { + let emailText = msgs[i][j].getPlainBody(); + currentPrediction = processSentiment(emailText); + if(regex.test(currentPrediction)){ + label_upset.addToThread(msgs[i][j].getThread()); + } + } + } +} \ No newline at end of file diff --git a/gmail-sentiment-analysis/README.md b/gmail-sentiment-analysis/README.md new file mode 100644 index 000000000..1638b0977 --- /dev/null +++ b/gmail-sentiment-analysis/README.md @@ -0,0 +1,31 @@ +# Gmail sentiment analysis with Vertex AI + +## Project Description + +Google Workspace Add-on that extends Gmail and adds sentiment analysis capabilities. + +## Prerequisites + +* Google Cloud Project (aka Standard Cloud Project for Apps Script) with billing enabled + +## Set up your environment + +1. Create a Cloud Project + 1. Enable the Vertex AI API + 1. Create a Service Account and grant the role `Vertex AI User` + 1. Create a private key with type JSON. This will download the JSON file for use in the next section. +1. Open an Apps Script Project bound to a Google Sheets Spreadsheet + 1. From Project Settings, change project to GCP project number of Cloud Project from step 1 + 1. Add a Script Property. Enter `service_account_key` as the property name and paste the JSON key from the service account as the value. +1. Add OAuth2 v43 Apps Script Library using the ID `1B7FSrk5Zi6L1rSxxTDgDEUsPzlukDsi4KGuTMorsTQHhGBzBkMun4iDF`. +1. Add the project code to Apps Script + +## Usage + +1. Create a label in Gmail with this exact text and emojy (case sensitive!): UPSET TONE 😡 +1. In Gmail, click on the Productivity toolbox icon (icon of a spy) in the sidepanel. +1. The sidepanel will open up. Grant the Add-on autorization to run. +1. The Add-on will load. Click on the blue button "Identify angry customers." +1. Close the Add-on by clicking on the X in the top right corner. +1. It can take a couple of minutes until the label is applied to the messages that have a negative tone. +1. If you don't want to wait until the labels are added, you can refresh the browser. \ No newline at end of file diff --git a/gmail-sentiment-analysis/Vertex.gs b/gmail-sentiment-analysis/Vertex.gs new file mode 100644 index 000000000..9703c97e7 --- /dev/null +++ b/gmail-sentiment-analysis/Vertex.gs @@ -0,0 +1,92 @@ +/* +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. +*/ + +const PROJECT_ID = [ADD YOUR GCP PROJECT ID HERE]; +const VERTEX_AI_LOCATION = 'europe-west2'; +const MODEL_ID = 'text-bison'; +const SERVICE_ACCOUNT_KEY = PropertiesService.getScriptProperties().getProperty('service_account_key'); + +/** + * Packages prompt and necessary settings, then sends a request to + * Vertex API. Returns the response as an JSON object extracted from the + * Vertex API response object. + * + * @param emailText - Email message that is sent to the model. + */ + +function processSentiment(emailText) { + const prompt = `Analyze the following message: ${emailText}. If the sentiment of this message is negative, answer with NEGATIVE. If the sentiment of this message is neutral or positive, answer with OK. Do not use any other words than the ones requested in this prompt as a response!`; + const request = { + "instances": [{ + "prompt": prompt + }], + "parameters": { + "temperature": 0.9, + "maxOutputTokens": 1024, + "topK": 1, + "topP": 1 + }, + + }; + + const credentials = credentialsForVertexAI(); + + const fetchOptions = { + method: 'POST', + headers: { + 'Authorization': `Bearer ${credentials.accessToken}` + }, + contentType: 'application/json', + muteHttpExceptions: true, + payload: JSON.stringify(request) + } + + const url = `https://${VERTEX_AI_LOCATION}-aiplatform.googleapis.com/v1/projects/${PROJECT_ID}/` + + `locations/${VERTEX_AI_LOCATION}/publishers/google/models/${MODEL_ID}:predict` + + const response = UrlFetchApp.fetch(url, fetchOptions); + const payload = JSON.parse(response.getContentText()); + console.log(payload.predictions[0].content); + + return payload.predictions[0].content; +} + +/** + * Gets credentials required to call Vertex API using a Service Account. + * Requires use of Service Account Key stored with project + * + * @return {!Object} Containing the Cloud Project Id and the access token. + */ + +function credentialsForVertexAI() { + const credentials = SERVICE_ACCOUNT_KEY; + if (!credentials) { + throw new Error("service_account_key script property must be set."); + } + + const parsedCredentials = JSON.parse(credentials); + + const service = OAuth2.createService("Vertex") + .setTokenUrl('https://oauth2.googleapis.com/token') + .setPrivateKey(parsedCredentials['private_key']) + .setIssuer(parsedCredentials['client_email']) + .setPropertyStore(PropertiesService.getScriptProperties()) + .setScope("https://www.googleapis.com/auth/cloud-platform"); + return { + projectId: parsedCredentials['project_id'], + accessToken: service.getAccessToken(), + } +} \ No newline at end of file diff --git a/gmail-sentiment-analysis/appsscript.json b/gmail-sentiment-analysis/appsscript.json new file mode 100644 index 000000000..acf10a04c --- /dev/null +++ b/gmail-sentiment-analysis/appsscript.json @@ -0,0 +1,33 @@ +{ + "timeZone": "Europe/Madrid", + "dependencies": { + "libraries": [ + { + "userSymbol": "OAuth2", + "version": "43", + "libraryId": "1B7FSrk5Zi6L1rSxxTDgDEUsPzlukDsi4KGuTMorsTQHhGBzBkMun4iDF" + } + ] + }, + "addOns": { + "common": { + "name": "Productivity toolbox", + "logoUrl": "https://icons.iconarchive.com/icons/roundicons/100-free-solid/64/spy-icon.png", + "useLocaleFromApp": true, + "homepageTrigger": { + "runFunction": "onHomepage", + "enabled": true + } + }, + "gmail": { + "contextualTriggers": [ + { + "unconditional": {}, + "onTriggerFunction": "onGmailMessage" + } + ] + } + }, + "exceptionLogging": "STACKDRIVER", + "runtimeVersion": "V8" + } \ No newline at end of file From 3d18bd0c1b168d7695092d3d0f8a8f8a7c787246 Mon Sep 17 00:00:00 2001 From: Chanel Greco Date: Tue, 22 Oct 2024 16:51:13 +0200 Subject: [PATCH 2/3] Applied changes are suggested. --- gmail-sentiment-analysis/Code.gs | 7 ++- gmail-sentiment-analysis/Gmail.gs | 6 +-- gmail-sentiment-analysis/Vertex.gs | 33 +++++++++------ gmail-sentiment-analysis/appsscript.json | 54 +++++++++++------------- 4 files changed, 49 insertions(+), 51 deletions(-) diff --git a/gmail-sentiment-analysis/Code.gs b/gmail-sentiment-analysis/Code.gs index 143a5e1d9..7b353e735 100644 --- a/gmail-sentiment-analysis/Code.gs +++ b/gmail-sentiment-analysis/Code.gs @@ -19,7 +19,6 @@ limitations under the License. * @return {CardService.Card} The card to show to the user. */ function onHomepage(e) { - if(e.hostApp =="gmail"){ - return buildCard_GmailHome(); - } -} \ No newline at end of file + return buildCard_GmailHome(); +} + diff --git a/gmail-sentiment-analysis/Gmail.gs b/gmail-sentiment-analysis/Gmail.gs index e3fab9463..b8ac5b3d5 100644 --- a/gmail-sentiment-analysis/Gmail.gs +++ b/gmail-sentiment-analysis/Gmail.gs @@ -28,21 +28,21 @@ function analyzeSentiment(){ * Gets the last 10 threads in the inbox and the corresponding messages. * Fetches the label that should be applied to negative messages. * The processSentiment is called on each message - * and testet with RegExp to check for a negative answer from the model + * and tested with RegExp to check for a negative answer from the model */ function emailSentiment() { const threads = GmailApp.getInboxThreads(0, 10); const msgs = GmailApp.getMessagesForThreads(threads); const label_upset = GmailApp.getUserLabelByName("UPSET TONE 😡"); - const regex = new RegExp('N'); let currentPrediction; for (let i = 0 ; i < msgs.length; i++) { for (let j = 0; j < msgs[i].length; j++) { let emailText = msgs[i][j].getPlainBody(); currentPrediction = processSentiment(emailText); - if(regex.test(currentPrediction)){ + if(currentPrediction === true){ + console.log("In condition:", currentPrediction) label_upset.addToThread(msgs[i][j].getThread()); } } diff --git a/gmail-sentiment-analysis/Vertex.gs b/gmail-sentiment-analysis/Vertex.gs index 9703c97e7..f6299ecde 100644 --- a/gmail-sentiment-analysis/Vertex.gs +++ b/gmail-sentiment-analysis/Vertex.gs @@ -16,30 +16,33 @@ limitations under the License. const PROJECT_ID = [ADD YOUR GCP PROJECT ID HERE]; const VERTEX_AI_LOCATION = 'europe-west2'; -const MODEL_ID = 'text-bison'; +const MODEL_ID = 'gemini-1.5-pro-002'; const SERVICE_ACCOUNT_KEY = PropertiesService.getScriptProperties().getProperty('service_account_key'); /** * Packages prompt and necessary settings, then sends a request to - * Vertex API. Returns the response as an JSON object extracted from the - * Vertex API response object. + * Vertex API. + * A check is performed to see if the response from Vertex AI contains FALSE as a value. + * Returns the outcome of that check which is a boolean. * * @param emailText - Email message that is sent to the model. */ function processSentiment(emailText) { - const prompt = `Analyze the following message: ${emailText}. If the sentiment of this message is negative, answer with NEGATIVE. If the sentiment of this message is neutral or positive, answer with OK. Do not use any other words than the ones requested in this prompt as a response!`; + const prompt = `Analyze the following message: ${emailText}. If the sentiment of this message is negative, answer with FALSE. If the sentiment of this message is neutral or positive, answer with TRUE. Do not use any other words than the ones requested in this prompt as a response!`; + const request = { - "instances": [{ - "prompt": prompt + "contents": [{ + "role": "user", + "parts": [{ + "text": prompt + }] }], - "parameters": { + "generationConfig": { "temperature": 0.9, "maxOutputTokens": 1024, - "topK": 1, - "topP": 1 - }, - + + } }; const credentials = credentialsForVertexAI(); @@ -55,13 +58,15 @@ function processSentiment(emailText) { } const url = `https://${VERTEX_AI_LOCATION}-aiplatform.googleapis.com/v1/projects/${PROJECT_ID}/` - + `locations/${VERTEX_AI_LOCATION}/publishers/google/models/${MODEL_ID}:predict` + + `locations/${VERTEX_AI_LOCATION}/publishers/google/models/${MODEL_ID}:generateContent` const response = UrlFetchApp.fetch(url, fetchOptions); const payload = JSON.parse(response.getContentText()); - console.log(payload.predictions[0].content); - return payload.predictions[0].content; + const regex = /FALSE/; + + return regex.test(payload.candidates[0].content.parts[0].text); + } /** diff --git a/gmail-sentiment-analysis/appsscript.json b/gmail-sentiment-analysis/appsscript.json index acf10a04c..80b231e9a 100644 --- a/gmail-sentiment-analysis/appsscript.json +++ b/gmail-sentiment-analysis/appsscript.json @@ -1,33 +1,27 @@ { - "timeZone": "Europe/Madrid", - "dependencies": { - "libraries": [ - { - "userSymbol": "OAuth2", - "version": "43", - "libraryId": "1B7FSrk5Zi6L1rSxxTDgDEUsPzlukDsi4KGuTMorsTQHhGBzBkMun4iDF" - } - ] - }, - "addOns": { - "common": { - "name": "Productivity toolbox", - "logoUrl": "https://icons.iconarchive.com/icons/roundicons/100-free-solid/64/spy-icon.png", - "useLocaleFromApp": true, - "homepageTrigger": { - "runFunction": "onHomepage", - "enabled": true - } - }, - "gmail": { - "contextualTriggers": [ - { - "unconditional": {}, - "onTriggerFunction": "onGmailMessage" - } - ] + "timeZone": "Europe/Madrid", + "dependencies": { + "libraries": [ + { + "userSymbol": "OAuth2", + "version": "43", + "libraryId": "1B7FSrk5Zi6L1rSxxTDgDEUsPzlukDsi4KGuTMorsTQHhGBzBkMun4iDF" } + ] + }, + "addOns": { + "common": { + "name": "Productivity toolbox", + "logoUrl": "https://icons.iconarchive.com/icons/roundicons/100-free-solid/64/spy-icon.png", + "useLocaleFromApp": true }, - "exceptionLogging": "STACKDRIVER", - "runtimeVersion": "V8" - } \ No newline at end of file + "gmail": { + "homepageTrigger": { + "runFunction": "onHomepage", + "enabled": true + } + } + }, + "exceptionLogging": "STACKDRIVER", + "runtimeVersion": "V8" +} \ No newline at end of file From 8d8cdace71ca9dfbb2b3f48a44a98edc05a4a944 Mon Sep 17 00:00:00 2001 From: Chanel Greco Date: Tue, 22 Oct 2024 16:55:09 +0200 Subject: [PATCH 3/3] Deleted console.log statement --- gmail-sentiment-analysis/Gmail.gs | 1 - 1 file changed, 1 deletion(-) diff --git a/gmail-sentiment-analysis/Gmail.gs b/gmail-sentiment-analysis/Gmail.gs index b8ac5b3d5..1bf87b1a9 100644 --- a/gmail-sentiment-analysis/Gmail.gs +++ b/gmail-sentiment-analysis/Gmail.gs @@ -42,7 +42,6 @@ function emailSentiment() { let emailText = msgs[i][j].getPlainBody(); currentPrediction = processSentiment(emailText); if(currentPrediction === true){ - console.log("In condition:", currentPrediction) label_upset.addToThread(msgs[i][j].getThread()); } }