var secretKey = '$SECRET KEY$';
function onOpen() {
var ui = SpreadsheetApp.getUi();
// Or DocumentApp or FormApp.
ui.createMenu('Trickle')
.addItem('Use AI to generate formula', 'genForm')
.addToUi();
}
function genForm()
{
var ui = SpreadsheetApp.getUi();
var response = ui.prompt('AI prompt', 'Describe your desired outcome as precisely as possible', ui.ButtonSet.OK_CANCEL);
if (response.getSelectedButton() == ui.Button.OK) {
SpreadsheetApp.getActiveSheet().getActiveRange().setFormula(askTheAI(response.getResponseText() + '. Use semicolon as the parameter delimiter.'));
}
}
/**
* Use GPT-3 to generate a response
*
* @param {string} topic - the topic for the article
* @return {string} the generated article
* @customfunction
*/
function askTheAI(_prompt) {
var _model = 'text-davinci-003';
const api_endpoint = '<https://api.openai.com/v1/completions>';
const api_key = secretKey;
const api_params = {
prompt: _prompt,
max_tokens: 1024,
temperature: 0.7,
model: _model,
};
const response = UrlFetchApp.fetch(api_endpoint, {
method: 'post',
headers: {
Authorization: 'Bearer ' + api_key,
'Content-Type': 'application/json',
},
payload: JSON.stringify(api_params),
});
var json_resp = JSON.parse(response.getContentText());
var lines = json_resp.choices[0].text.split('\\n');
lines.shift();
lines.shift();
return lines.join('\\n');
}
var secretKey = 'helloworld';
What you have done, is that you have created a very own custom function in this Google Sheets file. Just as =AVERAGE() is a function that calculates the average value of a set of values, =LEN() counts the number of characters in a string, you can now use the function =askTheAI() to send prompts to ChatGPT: