Use AI in a Google Sheets

I want to be able to use generative AI in spreadsheets to solve unique problems. I want to call OpenAI from a cell that passes in a prompt and a value from a column then returns an answer I can easily parse.

Thankfully, you can do this in Google Sheets and Apps Script!

First, create the script using App Script. In your spreadsheet go to Extensions -> Apps Script then add the script.

function AI(prompt, value) {
  // Replace YOUR_API_KEY with your actual OpenAI API key
  const apiKey = 'YOUR_KEY';
  const apiURL = 'https://api.openai.com/v1/chat/completions';

  const payload = JSON.stringify({
    "model": "gpt-4-turbo",
    "frequency_penalty": 0,
    "presence_penalty": 0,
    "temperature": 0,
    "messages": [
      {"role": "system", "content": `${prompt}`},
      {"role": "user", "content": `${value}`}
    ]
  });

  const options = {
    "method": "post",
    "contentType": "application/json",
    "payload": payload,
    "headers": {
      "Authorization": "Bearer " + apiKey
    },
    "muteHttpExceptions": false
  };

  try {
    const response = UrlFetchApp.fetch(apiURL, options);
    const json = JSON.parse(response.getContentText());
    const resultText = json.choices[0].message.content;
    return resultText;
  } catch (e) {
    Logger.log(e.toString());
  }
}

Finally, call the App Script from a cell like you would any formula =AI(PROMPT, COLUMN).

(Based on this thread in the OpenAI forum)

See also: