GPT on Google Sheet Free with Apps Script

Usually when looking for GPT integration in Google Sheet we encounter several options available in extension stores, only that the vast majority are paid and expensive. Thinking about this, we will teach you how you can install a Free Apps Script to use your GPT API in formula on your spreadsheets.

Advantages of GPT integration with Google Sheets

A. Personalization and Flexibility: Unlike standard extensions, GPT integration allows for the creation of customized solutions to meet specific needs. This includes data analysis, report generation, automation of repetitive tasks, and natural language processing.

B. Time and Efficiency Savings: GPT can automate tasks that would normally take a lot of time, such as compiling data from different sources, writing data summaries, and generating insights from complex datasets.

C. Continuous Improvement: The GPT model is in constant evolution, receiving updates and enhancements that expand its capabilities and efficiency.

Aikit - wordpress ai writing assistant using gpt-3

Extension x Personalized script

Extensions often offer more options, a custom UI with an interface that is easy to access and configure. The big problem is the price used to perform something simple, consult the GPT.

Making a custom script in addition to saving money, will allow you to customize, place standardised instructions, create different formulas that meet your needs.

The big problem is that using the Apps Scripts Script even with the help of chatGPT can still cause errors.

How to integrate GPT into Google Sheets

Integrating GPT into Google Sheets involves a few technical steps, including:

A. API Configuration: First, it is necessary to obtain access to the OpenAI GPT API. This usually involves creating an account and obtaining an API key.

B. Use of Google Apps Script: Google Apps Script, a JavaScript-based scripting platform for automation in G Suite, can be used to integrate GPT with Google Sheets. This involves writing scripts that make calls to the GPT API and process the responses.

C. Automation and Customization: With the script running, it is possible to automate tasks, such as text generation, data analysis, and other functionalities, directly in Google Sheets.

Apps Script Code to Use GPT in Sheet

Below I share the code that I use to use a simple formula like GPT=(“promt”;CE1). Using this formula from Sheet, I can use different cells to generate content in my tables.

You can also customize and modify the code, create different formulas that perform different functions. With the help of the GPT chat you will be able to use the OpenAI API on Google Sheet for free.

var apiKey = 'SUACHAVEDEAPI';

function GPT() {
  var messages = [];
  for (var i = 0; i < arguments.length; i++) {
    var arg = arguments[i];
    if (typeof arg === 'string' && arg.trim() !== '') {
      messages.push({ 'role': 'user', 'content': arg.trim() });
    } else if (Array.isArray(arg)) {
      arg.forEach(function(cellValue) {
        if (typeof cellValue === 'string' && cellValue.trim() !== '') {
          messages.push({ 'role': 'user', 'content': cellValue.trim() });
        }
      });
    }
  }

  if (messages.length === 0) {
    return 'Nenhuma mensagem válida fornecida.';
  }

  var url = 'https://api.openai.com/v1/chat/completions';
  var headers = {
    'Authorization': 'Bearer ' + apiKey,
    'Content-Type': 'application/json'
  };

  var payload = {
    'model': 'gpt-3.5-turbo-1106', // Especificar o modelo desejado
    'messages': messages,
    'max_tokens': 700 // Configuração flexível do número máximo de tokens
  };

  var options = {
    'method': 'post',
    'headers': headers,
    'payload': JSON.stringify(payload),
    'muteHttpExceptions': true // Importante para tratar erros
  };

  try {
    var response = UrlFetchApp.fetch(url, options);
    var result = JSON.parse(response.getContentText());

    if (response.getResponseCode() === 200 && result.choices && result.choices.length > 0) {
      return result.choices[0].message.content; // Acessa o conteúdo da mensagem corretamente
    } else {
      Logger.log('Erro na resposta da API: ' + response.getContentText());
      return 'Erro na resposta da API.';
    }
  } catch (e) {
    Logger.log('Erro ao fazer a requisição para a API: ' + e.message);
    return 'Erro ao fazer a requisição para a API.';
  }
}

How to Install Code in Apps Script

To integrate OpenAI’s GPT with Google Sheets, you will need to use Google Apps Script, which allows you to automate tasks and interact with external APIs such as that of OpenAI. Below is a step-by-step tutorial on how to install the provided code and use a custom formula in Google Sheets to interact with GPT.

Step 1: Configuring the OpenAI API

  1. Acesse o site da OpenAI e crie uma conta ou faça login.
  2. Navegue até a seção de gerenciamento de API e gere uma nova chave de API. Guarde essa chave, pois você precisará dela para autenticar suas requisições.

Step 2: Open the Google Apps Script Editor

  1. Abra um novo ou existente Google Sheets onde você deseja usar o GPT.
  2. No menu, clique em Extensões > Apps Script.
  3. Isso abrirá o editor do Google Apps Script em uma nova aba.

Step 3: Install the code

  1. No editor do Apps Script, apague qualquer código existente.
  2. Copie e cole o código fornecido no editor.
  3. Substitua 'SUACHAVEDEAPI' pela chave de API real que você obteve da OpenAI.
  4. Salve o script com um nome de projeto relevante, usando Arquivo > Salvar ou o ícone de disquete.

Step 4: Use the Custom Function in Google Sheets

  1. Volte para a sua planilha do Google Sheets.
  2. Em uma célula, digite =GPT("Sua pergunta aqui") para fazer uma pergunta ao GPT. Você também pode referenciar outras células que contenham o texto que deseja enviar.
  3. Pressione Enter e aguarde a resposta ser gerada. Isso pode levar alguns segundos, dependendo da resposta da API.

Important considerations

  • Cotas e Limites: A API da OpenAI tem cotas de uso, que podem limitar a quantidade de requisições que você pode fazer. Fique atento a esses limites para evitar interrupções.
  • Segurança da Chave de API: Mantenha sua chave de API segura e não a compartilhe dentro do script ou de qualquer maneira que possa ser exposta publicamente.
  • Tratamento de Erros: O código inclui tratamento básico de erros, mas você pode querer expandi-lo para lidar melhor com falhas de rede ou respostas inesperadas da API.
  • Customização: Você pode ajustar o modelo ('model'), o número máximo de tokens ('max_tokens') e outras configurações conforme a necessidade do seu projeto.

Following these steps, you’ll be able to integrate OpenAI’s powerful GPT into Google Sheets, opening up a range of possibilities for automation, data analysis, content generation, and more.