GPT-3 and Google Sheets

Usage:

  1. Create a new Google Sheet (you can use https://sheets.new).
  2. Extensions > App Script.
  3. Overwrite all text in the text box by pasting all the code below.
  4. Add your new secret key from https://beta.openai.com/account/api-keys
  5. Click Save and Run icons.
  6. Close the script window. Back in your new sheet, as an example, type “France” into A1. Then type this formula into B1: =IF(ISBLANK(A1),,GPT("Answer in one word. The capital of "&A1&" is:"))


/**
* GPT-3 and Google Sheets
*
* @param {string} prompt Prompt.
* @param {number} temperature (Optional) Temperature.
* @param {string} model (Optional) GPT-3 Model.
* @return Response returned by GPT-3.
* @customfunction
*/

const SECRET_KEY = "sk-paste-your-API-secret-key-here";
const MAX_TOKENS = 10;
const MODEL_NAME = "text-davinci-002"; // more structured and deterministic: for data
//const MODEL_NAME = "davinci"; // more flexible and creative: for stories, chatbots
const MODEL_TEMP = 0.3;

function GPT(prompt) {
const url = "https://api.openai.com/v1/completions";
const payload = {
model: MODEL_NAME,
prompt: prompt,
temperature: MODEL_TEMP,
max_tokens: MAX_TOKENS,
};
const options = {
contentType: "application/json",
headers: { Authorization: "Bearer " + SECRET_KEY },
payload: JSON.stringify(payload),
};
const res = JSON.parse(UrlFetchApp.fetch(url, options).getContentText());
return res.choices[0].text.trim();
}