How to integrate OpenAI with Google Sheets for FREE

How to integrate OpenAI with Google Sheets for FREE

Integration of OpenAI with Google Sheets can be easily done using Apps Script. From the Google Sheet, you will be able to pass custom prompts to get the OpenAI model to do anything you like.

To setup the integration, go to any Google Sheet and add “Apps Script” from the main menu by browsing to “Extensions -> Apps Script”

// Replace the API_KEY variable with your actual API key
var API_KEY = 'YOUR_API_KEY';

// Create a custom function that can be used as a formula in Google Sheets
function GPT_EXTRACT(prompt) {
    var url = 'https://api.openai.com/v1/completions';
    var options = {
        'method': 'post',
        'headers': {
            'Content-Type': 'application/json',
            'Authorization': 'Bearer '+ API_KEY,
        },
        'payload': JSON.stringify({
            'prompt': prompt,
            'max_tokens': 100,
            'model': 'text-davinci-003',
            'temperature': 0.5,
        })
    };
    var response = UrlFetchApp.fetch(url, options);
    var json = JSON.parse(response.getContentText());
    return json.choices[0].text;
}

// Create a menu item in the Spreadsheet UI to call the function
function onOpen() {
    var ui = SpreadsheetApp.getUi();
    ui.createMenu('OpenAI')
        .addItem('Extract Data from OpenAI', 'extractData')
        .addToUi();
}


// Function that allow the user to select the cells for the prompt and the result
function extractData() {
    var sheet = SpreadsheetApp.getActiveSheet();
    var promptRange = SpreadsheetApp.getUi().prompt("Select the cell(s) for the prompt:").getResponse();
    var resultRange = SpreadsheetApp.getUi().prompt("Select the cell(s) to return the result:").getResponse();
    var prompt = sheet.getRange(promptRange).getValues();
    var extractedData = GPT_EXTRACT(prompt);
    var nextCol = sheet.getRange(resultRange).offset(0, 1);
    nextCol.setValues(extractedData);
}

This script lets you use GPT-3 like a custom function =GPT_EXTRACT from Google sheets.

You can adjust the parameters and use different OpenAI models depending on your requirement.

You need to sign up with your account here and use the $18 free credit. You can sign up for paid access later if this helps you somehow.