Created
July 4, 2024 02:14
-
-
Save primaryobjects/8e376306b17f390b3d83281ebbc696b8 to your computer and use it in GitHub Desktop.
Example Google Spreadsheet Apps Script to call Cohere API. Integrate AI LLM large language model in a spreadsheet.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function callCohereAPI(user_prompt) { | |
const sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet(); // get active sheet | |
user_prompt = user_prompt || sheet.getRange('B1').getValue(); | |
const dataRange = sheet.getRange('E2:G100').getValues(); | |
let dataStrings = dataRange.map(function(row) { | |
// Check if the row is not empty | |
if (row.filter(String).length) { | |
return row.join(','); | |
} | |
}); | |
// Filter out undefined values | |
dataStrings = dataStrings.filter(function(str) { | |
return str !== undefined && str.replace(/,/g, '').trim() !== ''; | |
}); | |
// Clear existing output. | |
const outputCell = sheet.getRange('B6'); | |
//outputCell.clearContent(); | |
outputCell.setValue('Processing analysis, please wait ..'); | |
SpreadsheetApp.flush(); | |
// Combine all strings into one, separated by commas | |
var dataString = dataStrings.join(','); | |
const prompt = `You are an expert dietician and professional fitness coach experienced with the latest research on diets and intermittent fasting. | |
Analyze the following list of weights recorded from an individual doing intermittent fasting on a 16/8 schedule. | |
The analysis should be no longer than three short paragraphs. It should include a review of the weight trend, any fluctuations, a conclusion of the overall data, and recommendations for continued weight loss going forward. | |
${user_prompt} | |
Date,Value,Description | |
${dataString}`; | |
var url = 'https://api.cohere.com/v1/chat'; // Cohere API endpoint | |
const api_key = '<YOUR_API_KEY>'; // https://dashboard.cohere.com/api-keys | |
var options = { | |
method: 'POST', | |
headers: { | |
'Authorization': `Bearer ${api_key}`, | |
'Content-Type': 'application/json' | |
}, | |
payload: JSON.stringify({ | |
message: prompt, | |
}) | |
}; | |
let output = ''; | |
try { | |
var response = UrlFetchApp.fetch(url, options); // make the API call | |
var json = response.getContentText(); // get the response content as text | |
var data = JSON.parse(json); // parse text into JSON | |
output = data.text; | |
} | |
catch (ex) { | |
console.log(ex); | |
output = ex; | |
} | |
outputCell.setValue(output); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment