Google Sheets AI API: call an AI model from a cell
How to call an AI model from Google Sheets with Apps Script, as a formula or from a menu, what it costs and how to keep your API key safe.
To call an AI model from Google Sheets, add a short Apps Script that sends a cell's text to an AI API with UrlFetchApp and writes the answer back. Use it as a formula, such as =ASK_AI(A2), or from a menu that fills a whole column. Keep the API key in Script Properties, never in a cell.
How does it work?#
Apps Script is the code editor built into Google Sheets, under Extensions > Apps Script. Its UrlFetchApp.fetch sends web requests, so a script can send a prompt to an AI API and read the reply. The script below calls Chat Completions in the OpenAI format: our base URL https://api.5abeer.ai/v1 followed by /chat/completions, as explained in What is a base URL?. OpenAI-compatible: change the base URL and keep your code.
Each answer is one request like this one:
curl --request POST "https://api.5abeer.ai/v1/chat/completions" \
--header "Authorization: Bearer $KHABEER_API_KEY" \
--header "Content-Type: application/json" \
--data '{"model":"claude-sonnet-5.5","messages":[{"role":"user","content":"Write a product idea in one sentence."}]}'{
"id": "chatcmpl-9f2",
"object": "chat.completion",
"model": "claude-sonnet-5.5",
"choices": [
{
"index": 0,
"message": {
"role": "assistant",
"content": "Hello! How can I help you today?"
},
"finish_reason": "stop"
}
],
"usage": {
"prompt_tokens": 21,
"completion_tokens": 12,
"total_tokens": 33
}
}The key is read from KHABEER_API_KEY, so it never appears in your code.
The script gives you two ways to run it:
| Formula | Menu | |
|---|---|---|
| How you run it | Type =ASK_AI(A2) in a cell | Select the prompt cells, then 5abeer > Answer the selected cells |
| Time limit | 30 seconds per cell | 6 minutes per run |
| When it sends a request | Whenever the cell recalculates, such as when you edit the formula or change a cell it refers to | Only when you click |
| What stays in the sheet | A live formula | Plain values in the next column |
| Best for | A few cells | Many rows, over one run or more |
Before you start#
You need a 5abeer API key for the provider of the model the script calls. Each key works with one provider's models, and the script calls claude-sonnet-5.5, so create a key for Claude models as in Create a key.
Control every key: a spend limit, an expiry date and an IP allow-list. Give this spreadsheet its own key with a spend limit and an expiry date, as in Control every key, so a mistake in the sheet costs little. Do not restrict this key to your own IP address: Apps Script sends its requests from Google's servers, not from your computer, so such a key would refuse every request from the sheet.
Add the script#
Open Apps Script#
In your spreadsheet, choose Extensions > Apps Script. This opens a script project tied to the spreadsheet, with a file named
Code.gs.Save the key#
In the Apps Script editor, open Project Settings, then under Script Properties add a property named
KHABEER_API_KEYwith your 5abeer key as its value, and save. The key stays out of the code and out of the cells.Paste the code#
Replace everything in
Code.gswith this code, then save:Code.gs// The key lives in Project Settings > Script Properties as KHABEER_API_KEY, never in this code or in a cell. const BASE_URL = "https://api.5abeer.ai/v1"; // 5abeer's OpenAI-format base URL const MODEL = "claude-sonnet-5.5"; /** * Sends a prompt to an AI model and returns its answer. * @param {string} prompt The question or instruction. * @return The model's answer. * @customfunction */ function ASK_AI(prompt) { if (prompt === "" || prompt == null) return ""; return askModel_(prompt); } function onOpen() { SpreadsheetApp.getUi() .createMenu("5abeer") .addItem("Test the key", "testKey") .addItem("Answer the selected cells", "answerSelection") .addToUi(); } function testKey() { SpreadsheetApp.getUi().alert(askModel_("Reply with the word OK.")); } function answerSelection() { const range = SpreadsheetApp.getActiveRange(); const prompts = range.getValues(); const out = range.offset(0, 1, prompts.length, 1); // the next column holds the answers const answers = out.getValues(); for (let i = 0; i < prompts.length; i++) { const prompt = prompts[i][0]; if (prompt === "" || answers[i][0] !== "") continue; // skip empty and answered rows let answer = askModel_(prompt); if (/^[=+\-@]/.test(answer)) answer = "'" + answer; // keep the reply as text, never a formula out.getCell(i + 1, 1).setValue(answer); SpreadsheetApp.flush(); // keep each answer if the 6-minute limit stops the run } } function askModel_(prompt) { const key = PropertiesService.getScriptProperties().getProperty("KHABEER_API_KEY"); if (!key) throw new Error("Add KHABEER_API_KEY in Project Settings > Script Properties."); const response = UrlFetchApp.fetch(BASE_URL + "/chat/completions", { method: "post", contentType: "application/json", headers: { Authorization: "Bearer " + key }, payload: JSON.stringify({ model: MODEL, messages: [{ role: "user", content: String(prompt) }] }), muteHttpExceptions: true, }); const status = response.getResponseCode(); const text = response.getContentText(); if (status !== 200) throw new Error("5abeer API error " + status + ": " + text.slice(0, 200)); return JSON.parse(text).choices[0].message.content; }To use another model, change
MODELto its id from the models page and save a key for that model's provider. You can rename the menu labels inonOpen, for example into Arabic.Test the key#
Reload the spreadsheet. A 5abeer menu appears in the menu bar. Choose 5abeer > Test the key, and approve the permissions Google asks for on the first run. A box with the model's reply means the setup works. This test sends one small paid request.
Use it in a cell#
Type the formula in a cell, with your instruction and a cell reference:
=ASK_AI("Summarize in one sentence: " & A2)You can write the instruction in Arabic too. Do the Test the key step first: a formula never asks for permissions, so you approve them once from the menu. Fill the formula down to run it for each row. Each cell is its own paid request, and it sends a new one whenever it recalculates. To keep the answers and stop new requests, copy the cells and paste them back as values only. A cell must get its answer within 30 seconds, otherwise it shows #ERROR!. Sheets also makes a separate call for every cell that uses the formula, which gets slow over hundreds of rows. For long answers or many rows, use the menu.
Fill a column with the menu#
Select the cells that hold your prompts, in one column, then choose 5abeer > Answer the selected cells. The answers go into the next column as plain values, so they never send a request again.
The script skips empty prompts and rows that already have an answer, and it saves each answer as it arrives. Google stops a run after 6 minutes, so for a long column run the menu again and it continues from the first row without an answer. A reply that starts with =, +, - or @ is kept as text, so it never becomes a formula.
Keep the key safe#
A script tied to a spreadsheet uses the spreadsheet's access list, and Script Properties are the same for everyone who runs the script:
- Anyone who can edit the spreadsheet can open the script and its Script Properties, read the key and run the script on your balance.
- Anyone who can only view the spreadsheet can still view the script and run it, and a run uses your key.
- Anyone who copies the spreadsheet gets their own copy of the script, which they can edit and run.
So keep the script in a spreadsheet that only you can open, and do not give anyone access to that file, not even view access. To share results, copy the answers into another spreadsheet as values only, and share that one. If you think the key has leaked, follow If a key leaks.
What does it cost?#
Each answer is billed by the tokens in your prompt and in the model's reply. As an example, 1,000 rows with about 300 input tokens and 100 output tokens each come to 300,000 input tokens and 100,000 output tokens on the default model:
300K input tokens and 100K output tokens
Official price from the provider's page, checked October 19, 2026.
Your real numbers depend on your prompts and replies. Arabic text often uses more tokens than English for the same meaning, as in Arabic token cost, so asking for short answers keeps the cost down. Every per-token API price is below the model's official price, and the API page shows both side by side.
When it shows an error#
In a cell, an error shows as #ERROR!; point at the cell to read the message. From the menu, Google shows the message on screen. For an API error, the message holds the status code and the start of 5abeer's reply, which names the error code:
| You see | What it means | Fix |
|---|---|---|
Add KHABEER_API_KEY in Project Settings > Script Properties | The key property is missing | Add the property as in the Save the key step |
You do not have permission to call … | The script is missing a permission it needs | Run 5abeer > Test the key once and approve the permissions |
INVALID_API_KEY | The key is wrong or was copied with extra spaces | Copy the key again into Script Properties |
MODEL_PLATFORM_NOT_ALLOWED | The key is for another provider's models | Save a key for the provider of MODEL |
INSUFFICIENT_BALANCE | Your balance is too low | Top up your balance |
API_KEY_QUOTA_EXHAUSTED | The key reached its spend limit | Raise the limit in the key settings |
API_KEY_EXPIRED | The key passed its expiry date | Create a new key and save it |
RATE_LIMITED | Too many requests at once | Wait a little, then run the menu again |
Exceeded maximum execution time in a formula cell | The answer took longer than 30 seconds | Use the menu, or ask for a shorter answer |
Every code and its fix is in Errors and fixes.
Questions#
Which models can the sheet call?#
Claude, GPT and Gemini models, because 5abeer serves all three in the OpenAI format, so the request stays the same. Change MODEL to the model's id from the models page, and save a key for that model's provider in KHABEER_API_KEY. One key covers one provider, so one sheet runs one provider's models at a time.
When does the formula send a new request?#
Whenever the cell recalculates, such as when you edit the formula or change a cell it refers to. Each new request is paid. To stop it, paste the answers back as values only, or use the menu, which writes plain values.
How many rows can one menu run answer?#
As many as finish within Google's 6-minute limit per run, which depends on the model and the length of each answer. Run the menu again to continue. Google also limits URL Fetch calls to 20,000 a day on a personal Google account and 100,000 a day on Google Workspace, and says its quotas can change at any time without notice.
Do I pay for empty or skipped rows?#
No request is sent for them: the formula returns nothing for an empty cell, and the menu skips empty prompts and rows that already have an answer. Each request the script does send is paid from your balance by the tokens it uses, at the model's 5abeer price, as in Pricing and balance.
Is it safe to share the spreadsheet?#
Not the spreadsheet that holds the key. Its editors can read the key in Script Properties, and even its viewers can run the script on your key. Copy the answers into another spreadsheet as values only, and share that one.
Sources#
Checked on 2026-11-03, in the Google Apps Script docs:
- UrlFetchApp, URL Fetch Service and HTTPResponse
- Custom functions in Google Sheets and Custom menus
- Properties Service, Container-bound scripts and Authorization for Google services
- Quotas for Google services and the Range reference
Get started#
See every model's price on the API page, then create a key with a spend limit for your spreadsheet.
Related guides
- How to get an API key for Claude, GPT and GeminiWhat an AI API key does, where to create one at Anthropic, OpenAI and Google, what it costs to use, and how to keep it safe.
- What is a base URL? For the OpenAI, Anthropic, Gemini SDKsWhat a base URL is, the official one for the OpenAI, Anthropic and Gemini SDKs, how to set it in code or Claude Code, and how to fix 404 and 401 errors.
- Arabic token cost: why Arabic uses more tokens and the fixWhy the same text costs more tokens in Arabic than in English, measured on a real tokenizer, with a cost example and ways to cut Arabic token use.
Ready to start?
Pick a plan that runs the official apps, or create an API key to use from your own code.