Skip to content

Instantly share code, notes, and snippets.

@MaxGSEO
Last active March 25, 2023 01:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save MaxGSEO/802d851c8701af7f3a73a1a57e2a9a57 to your computer and use it in GitHub Desktop.
Save MaxGSEO/802d851c8701af7f3a73a1a57e2a9a57 to your computer and use it in GitHub Desktop.
Script for adding a chatGPT formula in Google Sheet
// Constants
const API_KEY = "YOUR API KEY";
const MODEL_TYPE = "gpt-3.5-turbo"; //chatGPT model
const MAX_TOKENS = 4096;
function CHATGPT(promptCellRef, contentRangeRef) {
const sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
// Get the prompt from the specified cell
const promptCell = sheet.getRange(promptCellRef);
const prompt = promptCell.getValue();
// Append additional content from the specified range
const contentCells = sheet.getRange(contentRangeRef);
const contentValues = contentCells.getValues().flat().filter(value => value !== '');
const appendedPrompt = prompt + " " + contentValues.join(" ");
// Check if the total tokens are within the limit
const tokenCount = appendedPrompt.length; // A simple character count can be used as a rough estimation of token count
if (tokenCount > MAX_TOKENS) {
const truncatedPrompt = appendedPrompt.substring(0, MAX_TOKENS);
return callGPT(truncatedPrompt);
} else {
return callGPT(appendedPrompt);
}
}
function callGPT(prompt) {
const temperature = 0;
const maxTokens = 2050;
const requestBody = {
model: MODEL_TYPE,
messages: [{role: "user", content: prompt}],
temperature,
max_tokens: maxTokens,
};
const requestOptions = {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: "Bearer " + API_KEY,
},
payload: JSON.stringify(requestBody),
};
const response = UrlFetchApp.fetch("https://api.openai.com/v1/chat/completions", requestOptions);
const responseText = response.getContentText();
const json = JSON.parse(responseText);
const generatedText = json['choices'][0]['message']['content'];
return generatedText;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment