Skip to content

Instantly share code, notes, and snippets.

@tonycoco
Last active November 3, 2022 17:59
Show Gist options
  • Save tonycoco/2ab5bba18a13f6be1d23b9166d3b40e5 to your computer and use it in GitHub Desktop.
Save tonycoco/2ab5bba18a13f6be1d23b9166d3b40e5 to your computer and use it in GitHub Desktop.
=GPT3() for Google Sheets (Google Apps Script)
// Useage: =GPT3(prompt)
// Example: =GPT3("This bot will generate a creative ad headline that is will increase views, clicks, and impressions, based on a website category.\n\nWebsite Category: tech\nHeadline: Why Google will win the AI wars\n\nWebsite Category: retail\nHeadline: Need a break? Check out our new fall selections now!\n\nWebsite Category: pharma\nHeadline: Are you ready for the next pandemic? Be prepared with your own pandemic survival kit today\n\nWebsite Category: travel\nHeadline: We noticed that cruise lines are super cheap now, find out why!\n\nWebsite Category: holiday\nHeadline: Partying for the holidays? Find a new coat to go out in!\n\nWebsite Category: sports\nHeadline:")
class OpenAIApp {
static get API_KEY_PROP() {
return "OPENAI_API_KEY";
}
constructor(apiKey) {
this.apiKey = apiKey;
this.baseUrl = "https://api.openai.com/v1/completions";
}
getCompletions(options) {
const response = UrlFetchApp.fetch(this.baseUrl, {
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${this.apiKey}`,
},
payload: JSON.stringify(options),
});
const responseJSON = JSON.parse(response.getContentText());
return responseJSON.choices[0].text;
}
}
function setApiKey(apiKey) {
const userProperties = PropertiesService.getUserProperties();
userProperties.setProperty(OpenAIApp.API_KEY_PROP, apiKey);
}
function promptApiKey() {
const ui = SpreadsheetApp.getUi();
const result = ui.prompt("Please enter your OpenAI API key");
const apiKey = result.getResponseText();
setApiKey(apiKey);
}
function resetApiKey() {
const userProperties = PropertiesService.getUserProperties();
userProperties.deleteProperty(OpenAIApp.API_KEY_PROP);
}
function onOpen() {
const ui = SpreadsheetApp.getUi();
ui.createMenu("GPT3")
.addItem("Set OpenAI API key", "promptApiKey")
.addItem("Reset OpenAI API key", "resetApiKey")
.addToUi();
}
function GPT3(prompt) {
const userProperties = PropertiesService.getUserProperties();
const userApiKey = userProperties.getProperty(OpenAIApp.API_KEY_PROP);
if (!userApiKey) {
throw "Please set your OpenAI API key";
}
const api = new OpenAIApp(userApiKey);
return api.getCompletions({
prompt,
model: "text-davinci-002",
temperature: 0.7,
max_tokens: 256,
top_p: 1,
frequency_penalty: 0,
presence_penalty: 0,
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment