Today, you’ll learn how to use the OpenAI GPT APIs with Google Sheets without an extension. We focus on the ChatGPT API, but you can use other models if you want to.
This method can be used for simple text suggestions, content edits, summarizing text, getting answers and even generating Google Sheets formulas from text descriptions. In addition, you can use a similar method to connect to other APIs such as image generation, translation, audio transcription, and others.
You need three elements to complete your OpenAI GPT Google Sheets integration.
- OpenAI API access
- A Google Sheet
- Apps Script to connect your sheet with the API
Therefore, the first step to integrate the OpenAI API with Google Sheets is to sign up for API access. OpenAI makes it easy to sign up, and you can get some credits once you do so. At the time of this writing, you get $5 when you sign up. It used to be $18, so it can change again in the future.
You need to create the Google Sheet you are going to use to add the setup data and your prompts. This is the example we are going to use:

To make our lives easier, in addition to that sheet we use another sheet for raw data:

Furthermore, you need Apps Script functions to connect to the API and write to the Google Sheet.
App Script is a programming language that you can use to interact with Google Sheets. It is heavily based on Javascript and it allows you to execute programming commands to modify Google Sheets with programming logic, variables, API calls, and more.
In our example, the script functions get the parameters from the “setup” section, get the prompt you have typed down, and send this data to the OpenAI API. After that, they get the response and write to your Google Sheet.
It’s worth mentioning that the OpenAI API pricing varies depending on the model you use. Each model is better suited for some types of jobs, but in general, ChatGPT3.5 is the most cost-efficient model at the moment.
Also, the text-based APIs are charged in dollars per thousands of tokens. For example, ChatGPT costs $0.002/1k tokens. This means that you can process 500,000 tokens for $1.
A token is equal to roughly 4 characters or 0.75 word, but it depends. This sentence, for example, would cost 10 tokens. Even though it's 49 characters long, with 8 words – as opposed to 40 characters and 7.5 words that you would presumably get with 10 tokens.
Therefore, if you spend $1 you can process around 350,000 words. Tokens are consumed both in your prompt and in the response.
How to get access to the OpenAI API
Cost: $0
Time: 1h
OpenAI provides multiple AI tools. This includes ChatGPT, other text-based AI models, DALL-E, audio transcription models (Whisper) and more.
In addition to the API, OpenAI provides access to ChatGPT via browser. In terms of data processing and AI responses, ChatGPT and the GPT3.5 API are the same. They just use different interfaces.
GPT4 is still in closed beta, but if you have access to it, you can use it in this tutorial as well.
Since the API is one of the OpenAI services, in order to get access to the API, you need to sign up for an OpenAI account, and then request API access afterwards.
Let’s see how you can do it.
Step 1: Go to the sign-up page
Go to the sign-up page. You might need to solve a captcha to prove that you are human.

Step 2: Enter your email or use a Google or a Microsoft account
Type in your email or use a Google or Microsoft account to sign up.

Step 3: Fill in your name
After the sign-up process, during which you might need to verify your email, you can add your first name, last name, and organization name.

Step 4: Verify a phone number
To prevent abuse, OpenAI requires you to add a phone number to your account. If you prefer not to use your personal number, you can use a free virtual number, to verify your account instead.

Step 5: Enter the code
After you get a text message with the verification code, add it to the OpenAI registration page.

Step 6: Go to your profile > View API Keys
Once you add the verification code, you should be logged in automatically. Click on your avatar and click on “View API Keys.”

Step 7: Generate an API key
Click on “Create new secret key” and store this information in a safe place. This API key is shown only once, so if you don’t copy it, you’ll need to delete it and generate a new one.

Step 8: Check if you have credits
Go to “Usage” and double-check if you have any free trial credits. If you don’t have any, you’ll need to add a payment method to continue.

How to create a Google Sheet to integrate with OpenAI GPT
Cost: $0
Time: 2h
Now you have access to the OpenAI API. Let’s create a Google Sheet to store your setup and prompts.
In general, you can use the OpenAI GPT API by adding the setup rules, writing down a prompt, and clicking a button to get the results. To make it easier to process data, we use a raw_chats sheet, and we copy data from the raw_chats to the main sheet using formulas.
Step 1: Create a new Google Sheet
Create a new sheet, or open an existing sheet, in case you want to add AI to an existing file. You can visit the https://sheets.new URL to create a new Google Sheet directly.

Step 2: Create headers
Create the main headers to help you to organize your content. You can follow this structure:

Step 3: Add the setup options
Add some default values for the setup options and costs. Here is a short description along with the recommended default values for each:
- Temperature: Default: 0.7. Range: 0 to 2. Defines how “hot” or random the responses will be. With 0, you should expect the same response every time, with 1 you should expect similar replies with different wordings, and with 2 you can expect very different replies with the same prompt.
- Maximum length: Default 256. Range: 0 to infinity. The maximum number of tokens to use. More tokens usually means better, longer and more complex responses.
- Top P: Default 1. Range 0 to 1. Selects the top percentage of the sampling pool that will be used. So if you use 0.3, for example, only the top 30% of the sampling pool is considered for the replies.
- Frequency penalty: Default: 0. Range: -2 to 2. Positive values penalize repeated words, meaning that it is less likely to get the same lines verbatim.
- Presence penalty: Default 0. Range: -2 to 2. Positive values penalize current tokens that have already appeared, meaning that you will probably get new topics further down the line.
The “Tokens used” section is just a sum of all tokens in the chats section, with the formula =SUM(F:F)+SUM(G:G)
The “Price” cell just gets this value and converts it to dollars, like this:
=B10*0.002/1000

Step 4: Set up the chats section
The chats section consists of a prompt and a reply, along with the usage tokens. But on the main sheet, users can type down only the prompt. The response and the tokens count comes from the raw_chats sheet.
You can load them with these formulas:
=raw_chats!A2
=raw_chats!B2
=raw_chats!C2
You can copy and paste the first row until the end of your file, to make sure that this formula is there for a lot of prompts with the right line number (a2, a3, a4…).

Step 5: Set up the raw_chats sheet
Create a new sheet for raw_sheets. Copy this structure in it:

Notice that the prompt in this case is a formula:
=GPT!D5
Make sure to copy this formula over to as many cells as possible, so they will auto-populate with the user’s prompts.
How to write a script to integrate OpenAI GPT and Google Sheets
Cost: $0
Time: 2h
Now you need to create a script that takes all these settings and sends them to the OpenAI GPT API. In this example, we are creating two functions.
The first one is the API call itself: chatGPT(). If you want to use it directly in a cell you can do so, passing the parameters in a formula, such as =chatGPT(“prompt”, …).
The second function is the buttonGPT() function. This function loads the setup data from your sheet, sends the API request using chatGPT(), then adds data to your sheet.
Let’s see how you can do this in detail.
Step 1: Open the Apps Script editor
Go to Extensions > Apps Script to see the script editor:

Step 2: Paste the code
Replace the current function with this code:
/**
* Return a ChatGPT response from a given prompt, along with the request tokens and prompt tokens
* @constructor
* @param {string} prompt - the request prompt to be processed by ChatGPT
* @param {boolean} returnUsage [OPTIONAL] - If the return values should include the usage token or just the prompt answer - Default is true
* @param {number} temperature [OPTIONAL] - How random the responses will be from 0 to 2 - Default is 0.7
* @param {integer} maxLeght [OPTIONAL] - The maximum number of tokens used to generate a response - Default is 256
* @param {number} topP [OPTIONAL] - Get the top X% of the sampling pool from 0 to 1 - Default is 1
* @param {number} frequencyPenalty [OPTIONAL] - Positive values make it less likely to repeat the same lines verbatim, from -2 to 2 - Default is 0
* @param {number} presencePenalty [OPTIONAL] - Positive values make it more likely to talk about new topics, from -2 to 2 - Default is 0
* @customfunction
*/
function chatGPT( prompt = "Hello!", returnUsage = true, temperature = 0.7, maxLeght = 256, topP = 1, frequencyPenalty = 0, presencePenalty = 0) {
//initialize the return array
var contents = [];
//use your API Key here
const apiKey = 'ADD YOUR API KEY HERE’;
//change the API URL here if you want to use a different API
const url = 'https://api.openai.com/v1/chat/completions';
//change the model here
const model = 'gpt-3.5-turbo';
//request along with the parameters
const request = {
model: model,
messages: [{"role": "user", "content": prompt}],
temperature: temperature,
top_p: topP,
max_tokens: maxLeght,
frequency_penalty: frequencyPenalty,
presence_penalty: presencePenalty
};
//headers
const data = {
contentType: "application/json",
headers: { Authorization: "Bearer "+ apiKey },
payload: JSON.stringify(request),
};
//connect to the OpenAI API, sending the headers and parse the JSON response
const response = JSON.parse(UrlFetchApp.fetch(url, data).getContentText());
//add the response message to the return array
contents.push( response.choices[0].message.content );
if ( returnUsage ) {
//if the return usage is enabled, return the promtp_tokens and completion_tokens as well
contents.push(response.usage.prompt_tokens);
contents.push(response.usage.completion_tokens);
}
return contents;
}
function buttonGPT() {
//select a file
const ss = SpreadsheetApp.getActiveSpreadsheet();
//selecting each of the sheets in a variable
const raw = ss.getSheetByName('raw_chats');
const main = ss.getSheetByName('GPT');
//get the last populated rown
const lastRow = raw.getLastRow();
//generate the formula used on the prompt copy column for the raw sheet
var formula = lastRow + 3;
var formula = '=GPT!D' + formula;
//get settings
const temperature = main.getRange(4,2).getValue();
const maxLeght = main.getRange(5,2).getValue();
const topP = main.getRange(6,2).getValue();
const frequencyPenalty = main.getRange(7,2).getValue();
const presencePenalty = main.getRange(8,2).getValue();
const prompt = raw.getRange(lastRow,4).getValue();
//remove the last prompt
raw.getRange(lastRow,4).clear();
//connect with OpenAI
var contents = chatGPT( prompt, true, temperature, maxLeght, topP, frequencyPenalty, presencePenalty);
//add a new row with the response contents
raw.appendRow(contents);
//add the last prompt formula back
raw.getRange(lastRow,4).setFormula(formula);
return 1;
}
The logic behind this code is:
- chatGPT() - take the parameters, build the POST request, send it. Returns either the prompt response or the response along with the token usage.
- buttonGPT() - this function gets the current sheets, finds the last row, reads the prompt, deletes the cell with the prompt values, connects to ChatGPT(), writes the response.
You can use one of these models: gpt-4, gpt-4-0314, gpt-4-32k, gpt-4-32k-0314, gpt-3.5-turbo, gpt-3.5-turbo-0301
Step 3: Save and run these functions
Once you save/run these functions, you’ll see an authorization request that looks like this:

Make sure you authorize it.
Step 4: Log in to your Google Account
After you click on “Review permissions,” you need to log in to your Google account to authorize it.

How to use Google Sheets with OpenAI GPT
Cost: $0
Time: 2h
Now it’s time to see the magic working. Let’s see how you can use your Google Sheets to get OpenAI GPT responses.
Step 1: Write down your prompt
Write down anything you want ChatGPT to do on the first empty line.

Step 2: Make sure to hit enter
Apps Script runs on Google’s servers. So make sure you hit “enter” or select a different cell so the prompt value is correctly saved and propagated in your sheet.

Step 3: Click run
Click the “Run” button and wait a little bit. You should see a message about the script running, and then the results.

(Optional) Step 4: Use the chatGPT() function directly
If you want, you can add the chatGPT() function to a cell directly, passing the prompt and any of the arguments you want.
The downside of this approach is that the API call runs every time you load your Google Sheet, which might load significantly different answers and will consume API credits on each load.

Conclusion
Today you learned how you can integrate OpenAI GPT with Google Sheets. From setting up an account to creating a template to coding the Apps Script function.
You can certainly work on this concept further and add new elements such as using different AI tools (image, audio, video…) as well as improving the API integration (such as passing all messages from the current chat as an argument).
In addition, you can use Softr.io if you want to build a better interface for your Google Sheets OpenAI integration. You can use it to improve how you present answers to users, to make it easier for users to access it - without the authorization prompts for apps script. In addition, you can create filtered forms, avoiding data entry issues.
Frequently asked questions about Investor Portal
Do ChatGPT Plus Users get free API access?
ChatGPT Plus is a paid service for higher priority and better answers for the chat.openai.com service. This does not include API usage, which is billed separately.
How do I know how much I’m spending?
The tokens and cost calculation columns can give you a rough idea of how many API credits you are using. But you can always check this on your OpenAI account for a detailed breakdown.
Can I run other AI models in Google Sheets?
Yes, you can run any model you want in Google Sheets, as long as you use the correct API endpoint and variables.
Why am I getting the prompt answer as a reply to my previous prompt?
If you don’t hit enter, the prompt isn’t saved correctly in your Google Sheets. This can cause a wrong prompt message to be used since the last known prompt is the previous one.
Make sure you hit enter before you click “run.”
What is Softr
Join 700,000+ users worldwide, building client portals, internal tools, CRMs, dashboards, project management systems, inventory management apps, and more—all without code.