Skip to content

Commit

Permalink
fix: update gemini-sheets integration (GoogleCloudPlatform#748)
Browse files Browse the repository at this point in the history
Better handling for empty or invalid inputs
  • Loading branch information
kweinmeister authored Jun 4, 2024
1 parent 3d5aa88 commit f9d58f1
Showing 1 changed file with 16 additions and 4 deletions.
20 changes: 16 additions & 4 deletions gemini/use-cases/sheets-integration/Code.gs
Original file line number Diff line number Diff line change
Expand Up @@ -120,7 +120,7 @@ function query() {
}

// Populate temporary table in BigQuery with selected data from sheet
const prompts = SpreadsheetApp.getActiveRange().getValues();
const prompts = sanitizePrompts(SpreadsheetApp.getActiveRange().getValues());
populateTable(prompts);

const query = `SELECT * FROM ML.GENERATE_TEXT( MODEL \`${datasetId}.${modelId}\`, ` +
Expand All @@ -146,11 +146,13 @@ function query() {
console.log(jsonString);
const jsonData = JSON.parse(jsonString);
console.log(jsonData);
content = jsonData.candidates[0].content;
if (jsonData.candidates) {
content = jsonData.candidates[0].content;
}

// Is it missing content, e.g. due to a finish reason of 4 (RECITATION)?
var response = "";
if (!content) {
if (!jsonData.candidates || !content) {
invalidResponses = true;
SpreadsheetApp.getUi().alert(row);
} else {
Expand All @@ -161,7 +163,7 @@ function query() {
}

if (invalidResponses) {
SpreadsheetApp.getUi().alert("Some prompts did not return a response. Check prompts and safety settings.");
SpreadsheetApp.getActiveSpreadsheet().toast("Some prompts did not return a response. Check prompts and safety settings.");
}

// Responses come back in any order.
Expand All @@ -174,6 +176,16 @@ function query() {
writeResponses(responses);
}

function sanitizePrompts(prompts) {
// Sanitize each prompt in the array
return prompts.map(row => row.map(prompt => {
if (typeof prompt !== 'string') return prompt;

// Keep only letters, numbers, and whitespace
return prompt.replace(/[^a-zA-Z0-9\s]/g, '');
}));
}

/**
* Given a set of responses, write them one cell to the right of the selected prompts.
*/
Expand Down

0 comments on commit f9d58f1

Please sign in to comment.