Google Sheets automation: summarize and categorize order and inquiry lists with the AI function and Apps Script
In a Google Sheet full of inquiries, one menu click fills the next columns with a «Praise·Complaint·Question» category and a one-line summary. Use the Sheets AI function if you have a qualifying plan, Apps Script if you don't, and Python to combine it with other automation.
Where to goGoogle Sheets › Extensions › Apps ScriptApps Script › Project Settings › Script PropertiesGoogle Cloud Console
Steps
- Set up the sheet with inquiries in column A, category in column B, summary in column C, and a header in the first row. If you have a qualifying Google Workspace or Google AI plan, use the AI function directly in cell B2. On a free account you may see «AI function is not available», so go to Apps Script in the next step. If you used to use Excel, move the sheet to Google Sheets and it works the same way.
=AI("Answer with only one of these for this text: Praise, Complaint, Question", A2) - Apps Script is a small program that runs inside Google Sheets. You do not need a paid plan, and you use the Gemini key you got in part 2. You can get the code by putting this into Claude, ChatGPT or Gemini.
Please make an Apps Script for Google Sheets. 1. Column A is the customer inquiry, column B is the category, column C is a one-line summary. Row 1 is the header. 2. Pick only rows where column B is empty, get one of «Praise·Complaint·Question» and a one-line summary from the Gemini Interactions API (https://generativelanguage.googleapis.com/v1beta/interactions, model gemini-4-hydrogen), and put them in columns B·C. 3. Opening the sheet should add a «Sort inquiries» menu, and clicking «Fill category and summary» in it should run the script. Do not write the API key in the code; read it from the script property GEMINI_API_KEY. - In the inquiry sheet, click Extensions › Apps Script, delete all the text you first see, paste the code in and save. If the code the AI gave you looks very different, you can use this code as it is. Rows already filled are skipped, so clicking again does not charge you twice for the same row. For a row you want redone, clear its B cell and click.
// Opening the sheet adds a «Sort inquiries» menu at the top function onOpen() { SpreadsheetApp.getUi() .createMenu('Sort inquiries') .addItem('Fill category and summary', 'fillRows') .addToUi(); } function askGemini(key, text) { const res = UrlFetchApp.fetch('https://generativelanguage.googleapis.com/v1beta/interactions', { method: 'post', contentType: 'application/json', headers: { 'x-goog-api-key': key }, muteHttpExceptions: true, payload: JSON.stringify({ model: 'gemini-4-hydrogen', input: 'Read the customer message below. On the first line write only one of «Praise», «Complaint», «Question»; ' + 'on the second line write only a one-line summary. Add nothing else.\n\n' + text, }), }); let data = JSON.parse(res.getContentText()); if (Array.isArray(data)) data = data[0]; if (data.error) throw new Error(data.error.code + ' ' + data.error.message); // The answer text is in the text of the model_output step among steps return (data.steps || []) .filter(s => s.type === 'model_output') .flatMap(s => s.content || []) .filter(c => c.type === 'text') .map(c => c.text) .join(''); } function fillRows() { const key = PropertiesService.getScriptProperties().getProperty('GEMINI_API_KEY'); if (!key) throw new Error('GEMINI_API_KEY is missing from the script properties'); const sheet = SpreadsheetApp.getActiveSheet(); const last = sheet.getLastRow(); if (last < 2) return; // Nothing to do if there is only a header row const rows = sheet.getRange(2, 1, last - 1, 3).getValues(); rows.forEach((r, i) => { if (!r[0] || r[1]) return; // Skip empty rows and rows already filled const lines = askGemini(key, r[0]).trim().split('\n'); const kind = (lines[0] || '').trim(); const summary = lines.slice(1).join(' ').trim(); sheet.getRange(i + 2, 2, 1, 2).setValues([[kind, summary]]); }); } - Keep the key in script properties, not in the code. Even if you share the sheet with others, the key is not exposed in the code. In the Apps Script screen, click the gear icon Project Settings on the left, click Add script property under Script Properties below, enter
GEMINI_API_KEYas the property name and the key you got in part 2 as the value, then save. - Go back to the sheet tab and reload, and a Sort inquiries menu appears at the top. Click Sort inquiries › Fill category and summary. The first time, Google asks «whether this script may access the sheet and outside addresses». Pick your account and allow it. It is a script you made, so it is fine to allow. You are done when columns B·C are filled.
- To use a button on the sheet instead of the menu, add a button shape with Insert › Drawing (or Image), choose Assign script from that picture's three-dot menu, and enter
fillRowswithout parentheses. This button works only in the web version on a computer, not in the mobile app. - To combine this with other automation, like the part 3 news email or the part 4 Telegram bot, read and write the sheet from Python. For that you need a robot account called a «service account». In the Google Cloud Console, create or pick a project, then find Google Sheets API and Google Drive API and enable each one. Create a service account under «APIs & Services › Credentials», then create a new key as JSON under key management, and one file downloads. This JSON file is the key itself, so do not email it or hand someone your whole code folder.
- Create a working folder and a venv, then install the libraries (Mac). On Windows, use
python -m venv .venvand.venv\Scripts\activateinstead.mkdir sheet && cd sheet python3 -m venv .venv source .venv/bin/activate pip install -U gspread google-genai - Create
sheet_fill.pyin thesheetfolder and paste the code in.import os import gspread from google import genai # Read values from environment variables, not from the code SA_FILE = os.environ["GOOGLE_SA_FILE"] # Path to the downloaded service account JSON file SHEET_NAME = os.environ["SHEET_NAME"] # Google Sheets file name def ask(client, text): prompt = ( "Read the customer message below. On the first line write only one of «Praise», «Complaint», «Question»; " "on the second line write only a one-line summary. Add nothing else.\n\n" + text ) out = client.interactions.create(model="gemini-4-hydrogen", input=prompt).output_text lines = out.strip().split("\n") return lines[0].strip(), " ".join(lines[1:]).strip() if __name__ == "__main__": gc = gspread.service_account(filename=SA_FILE) ws = gc.open(SHEET_NAME).sheet1 client = genai.Client() # Reads the GEMINI_API_KEY environment variable rows = ws.get_all_values() done = 0 for n, row in enumerate(rows[1:], start=2): # Row 1 is the header row += [""] * (3 - len(row)) if not row[0] or row[1]: continue # Skip empty rows and rows already filled kind, summary = ask(client, row[0]) ws.update([[kind, summary]], f"B{n}:C{n}") done += 1 print(f"Filled {done} rows.") - Set the environment variables (Mac). Change the path and name to your own. On Windows, enter
setx GOOGLE_SA_FILE "C:\keys\sheet-bot.json"andsetx SHEET_NAME "Inquiry list", then open a new window, and runcd sheetand activate again.echo 'export GOOGLE_SA_FILE="$HOME/keys/sheet-bot.json"' >> ~/.zshrc echo 'export SHEET_NAME="Inquiry list"' >> ~/.zshrc source ~/.zshrc - This is where people get stuck most on the Python route. The service account is a different account from yours, so you must share the sheet with it before it can read and write. Open the downloaded JSON file in a text editor, find the
client_emailvalue (shaped like…@….iam.gserviceaccount.com), click Share at the top right of the Google Sheet, add that email as an editor, then run it. You are done when «Filled N rows.» appears and columns B·C of the sheet are filled.python sheet_fill.py
Limits of the Sheets AI function
- If you select many cells at once, only the first 350 cells are generated. Select the rest again to generate them.
- Do not put it inside another function such as
IF. - The answer comes out as text only. It cannot read the whole sheet or other files in Drive, so you must give the cells to read as a range.
- There is a short-term limit and a long-term limit; if you hit the long-term limit, it works again after about 24 hours. The docs do not say how many cells.
Docs the code follows
- The Apps Script call address and request body shape follow the Gemini Interactions guide. The model
gemini-4-hydrogenis the same as in part 3. - If you do not share it, Python raises
gspread.exceptions.SpreadsheetNotFound.
Troubleshooting
- «AI function is not available»: you may not have a qualifying plan, or it may be due to admin or language settings. Take the Apps Script route.
- AI function stops at 350 cells: that is the limit generated at one time. Select the remaining cells again and generate.
- Apps Script
400 API key not valid: the key in the script properties was pasted wrong. Enter it again with no spaces before or after. - Apps Script
403 Permission denied on the service.: the key was not attached to the request. Check that the script property name matchesGEMINI_API_KEYdown to the last character. - «GEMINI_API_KEY is missing from the script properties»: you skipped adding the key or did not click save.
- Menu does not show: after saving the code, reload the sheet tab so
onOpenruns. - Stops partway when there are many rows: Apps Script runs for up to 6 minutes per execution. Rows already filled are skipped, so clicking again picks up where it left off. Calls to outside addresses are limited to 20,000 a day for free accounts and 100,000 a day for Workspace accounts.
- A long sentence goes into the category cell instead of «Praise»: the AI did not follow the format. Clear the B cell in that row and click again. If it happens often, add «The first line is a single one-word label only» to the end of the prompt.
- Python
FileNotFoundError: theGOOGLE_SA_FILEpath does not match where the JSON file actually is. - Python
ValueError: No API key was provided.: the Gemini key environment variableGEMINI_API_KEYcould not be found. Check with the check command from part 2. - Python
KeyError: 'GOOGLE_SA_FILE': you did not set the environment variable, or did not open a new window on Windows. - Python
SpreadsheetNotFound: you did not share the sheet, orSHEET_NAMEdiffers from the sheet file name. - Python
APIError403 (message saying the Sheets API is turned off): you did not enable the Sheets API and Drive API. ModuleNotFoundError: No module named 'gspread': you ran it outside the venv box. Activate it so(.venv)shows at the start of the line, then run it.
Next part
In part 6, we make blog drafts with Claude. You put in a list of search terms and get several draft files back; a person does the publishing. How to run this sheet sorting automatically every day is covered in the stage 3 server parts.
Source
Related posts
- AI automationGetting started with AI automation: Claude vs ChatGPT vs Gemini — which one fits your workAll three have two routes: the chat window and the API. Work a person can paste in each time goes in the chat window; work that must run by itself at a set time or condition goes through the API.4 stepsclaude.ai › chatgpt.com › gemini.google.comRead
- AI automationHow to get a Claude, ChatGPT and Gemini API key, and check pricing and free limitsGet an API key from each company's console with «Create key», and put it in an environment variable instead of writing it in code. Only Gemini has a free tier; ChatGPT and Claude charge for what you use.6 stepsaistudio.google.com/apikey › platform.openai.com/api-keys › platform.claude.com/settings/keysRead
- AI automationGet a daily morning news summary email with the Gemini API: your first Python automationBuild one Python file that collects news headlines, has Gemini summarize them in five lines, and sends the summary to your Gmail. Ask an AI to write the code; this guide only covers how to put it in place and run it.8 stepspython.org › Terminal › myaccount.google.com/apppasswordsRead