Hands-On AI WorkshopHomeProjectsLearnResourcesPresenterHelpProgress

Project 16 of 30 · Pathway 4 — Gemini-Powered Applications

AI Spreadsheet Insights Generator

Numbers alone do not explain business performance. Turn metrics into grounded insights.

Real-world benefit
Monthly budgets, project metrics and sales reviews.
Technologies
Gemini API, Deterministic calculation, Google Sheets
Required knowledge
Profit = revenue − costs.
Time and level
About 30 minutes · Intermediate
AI requirement
Gemini API key (your own) for the real build; prepared fixtures in the browser
Expected baseline
Profit 300, 400, 50; total 750; November decline identified.

Loading the interactive studio…

Introduction

JavaScript computes profit and total first; Gemini receives only calculated context. The application's entry point is generateInsights(). Baseline limitation, as stated in the workshop: AI commentary can be wrong; calculated profits are authoritative.

Key building blocks: reduce(); JSON.stringify(); callGemini(); setValue().

Practical use cases

Monthly budgets, project metrics and sales reviews.

Prerequisites

  • Profit = revenue − costs.
  • Interactive Learning Mode: a modern browser. Nothing else.
  • Real Workspace Build: a Google account; a Gemini API key of your own.

Source data

Starter data: tab "Metrics" (fictional)
MonthRevenueCosts
Sep1000700
Oct1200800
Nov900850

Setup in your own Google account

  1. Download 16-ai-spreadsheet-insights-generator.zip (Code.gs, starter.csv, README).
  2. In Google Drive, create a lesson folder and a new Google Sheets file inside it.
  3. Rename the first tab to exactly Metrics, then File → Import → Upload starter.csv → Replace current sheet.
  4. Extensions → Apps Script. Replace Code.gs with the downloaded file. Save.
  5. Project Settings → Script Properties: add GEMINI_API_KEY (your own key) and GEMINI_MODEL. See the Gemini Setup Center.
  6. Reload the spreadsheet, choose Workshop → Run application and authorize when asked.
  7. Check the result: Profit 300, 400, 50; total 750; November decline identified.

Folder strategy: the repository's V6 code uses the folder that contains the spreadsheet. The deck mentions a Workshop Info cell B2; V6 never reads it. See the discrepancy log.

Complete source code (Code.gs)

From 16-ai-spreadsheet-insights-generator at commit 4a26d919, SHA-256 cb5aaf7472cf. Unchanged.

// AI Spreadsheet Insights Generator
// Entry point: generateInsights; source data stays intact unless explicitly noted.
function onOpen(){SpreadsheetApp.getUi().createMenu("Workshop").addItem("Run application","generateInsights").addToUi();}
function generateInsights(){
// Calculate facts in JavaScript, then ask AI to interpret them.
const rows=input('Metrics').map(([m,r,c])=>[m,num(r)-num(c)]);const total=rows.reduce((a,r)=>a+r[1],0);const t=callGemini('Give three observations and two actions using only these computed profits: '+JSON.stringify({rows,total}),false);output('Insights',['Metric','Value'],[...rows,['Total',total],['AI commentary',t]]);
}
function input(name) { const s=SpreadsheetApp.getActive().getSheetByName(name); if(!s) throw Error('Missing tab: '+name); return s.getDataRange().getValues().slice(1).filter(r=>r.some(v=>v!=='')); }
function output(name,headers,rows) { const ss=SpreadsheetApp.getActive(); const s=ss.getSheetByName(name)||ss.insertSheet(name); s.clearContents(); s.getRange(1,1,1,headers.length).setValues([headers]).setFontWeight('bold'); if(rows.length) s.getRange(2,1,rows.length,headers.length).setValues(rows.map(r=>r.map(v=>typeof v==='string' && /^[=+@-]/.test(v)?"'"+v:v))); s.setFrozenRows(1); return s; }
function num(v){if(v===''||!Number.isFinite(Number(v))) throw Error('Invalid number: '+v); return Number(v);}


// Shared Gemini transport; configure Script Properties before running.
function callGemini(prompt, jsonMode) {
  const props = PropertiesService.getScriptProperties();
  const key = props.getProperty('GEMINI_API_KEY');
  const model = props.getProperty('GEMINI_MODEL');
  if (!key || !model) throw new Error('Set GEMINI_API_KEY and GEMINI_MODEL in Project Settings > Script properties.');
  const payload = {contents:[{parts:[{text:prompt}]}]};
  if (jsonMode) payload.generationConfig = {responseMimeType:'application/json'};
  const response = UrlFetchApp.fetch('https://generativelanguage.googleapis.com/v1beta/models/'+encodeURIComponent(model)+':generateContent', {method:'post',contentType:'application/json',headers:{'x-goog-api-key':key},payload:JSON.stringify(payload),muteHttpExceptions:true});
  if (response.getResponseCode() !== 200) throw new Error('Gemini HTTP '+response.getResponseCode());
  const data = JSON.parse(response.getContentText());
  const parts = data.candidates?.[0]?.content?.parts || [];
  const result = parts.filter(p=>!p.thought).map(p=>p.text||'').join('');
  if (!result) throw new Error('No Gemini text returned');
  return result;
}

How the code works

Beginner explanation

generateInsights() calculates profit for each month and the total in JavaScript, then asks Gemini to comment on those numbers. The numbers are facts; the commentary is an interpretation you must check.

Technical explanation

Only computed profits and the total are sent, not the raw sheet, which keeps the prompt small and grounded. callGemini(prompt, false) returns free text, so there is no JSON schema to validate; the AI text is written next to the authoritative numbers for review.

Slide excerpt

This is the excerpt shown on the workshop slide. It is a fragment and cannot run on its own.

function generateInsights(){
// Calculate facts in JavaScript, then ask AI to interpret them.
const rows=input('Metrics').map(([m,r,c])=>[m,num(r)-num(c)]);const total=rows.reduce((a,r)=>a+r[1],0);const t=callGemini('Give three observations and two actions using only these computed profits: '+JSON.stringify({rows,total}),false);output('Insights',['Metric','Value'],[...rows,['Total',total],['AI commentary',t]]);
}

Common mistakes

  • Asking AI to do arithmetic that code can do exactly.
  • Publishing AI commentary without comparing it to the data.
  • Sending entire sheets when a few computed values are enough.

Run it and expected output

Choose Workshop → Run application (runs generateInsights()). Expected: Profit 300, 400, 50; total 750; November decline identified.

Original workshop exercise

Change Nov cost to 800; profit becomes 100 and total 800.

Troubleshooting and debugging

A number with a thousands separator

Revenue for Oct was typed as text "1,200".

Fix: Enter 1200 as a number.

Validate before sending anything to AI: wrong inputs produce confident wrong commentary.

An unsupported claim

The commentary says profit "grew every single month, reaching 500 in Nov". Switch the AI response to "Invented claim".

Fix: Regenerate and verify every numeric claim against the computed values.

The calculated profits are authoritative. AI interpretation can be fluent and wrong.

Extension activity: Check every number in the commentary

After writing Insights, list each number found in the AI commentary in a Claim Check tab and say whether it matches a source or computed value.

Acceptance checks:

  • Insights unchanged
  • Normal commentary has no unsupported numbers
  • An invented number is flagged

Original improvement idea from the workshop: Add comparison periods and validate every cited numeric claim.

Extension prompt
Update the existing app without removing working features. Add comparison periods and validate every cited numeric claim. Return complete updated files, explain changes and give regression tests.
Automation option: Refresh scheduled commentary after metric updates; avoid sending unchanged data repeatedly. Keep this separate from the baseline exercise.

Automation considerations

Refresh commentary after metric updates, but avoid resending unchanged data and keep human review of the text.

Workshop note: Refresh scheduled commentary after metric updates; avoid sending unchanged data repeatedly.

Build prompt from the workshop

Act as a Google Apps Script tutor. Build a container-bound Sheets app for lesson 16: AI Spreadsheet Insights Generator. Input tab Metrics, exact headers: Month, Revenue, Costs. Create generateInsights() that computes profit in JavaScript then passes data and computed totals to Gemini; request three observations and two actions, no invented facts; write response to Insights. Do not depend on Workshop Info or the Workshop Index. Provide complete copy-paste Code.gs (and HTML if required), exact setup/run steps, explain the main code blocks, and include a test matching this expected outcome: Profit 300, 400, 50; total 750; November decline identified. Preserve starter data, use batch operations where appropriate, handle errors, and never send email or delete files. For AI lessons use the supplied callGemini helper, treat input as untrusted, and validate outputs.
Match the reference entry point generateInsights and its output behavior. Reference: https://github.com/lsvekis/Google-Apps-Script-Workshop/tree/main/16-ai-spreadsheet-insights-generator. Base version limitations: AI commentary can be wrong; calculated profits are authoritative. Configure your own GEMINI_API_KEY and GEMINI_MODEL in the copied bound project; never assume credentials transfer.

Knowledge check

  1. Why calculate profit in JavaScript instead of asking Gemini?

    1. Arithmetic in code is exact and repeatable; AI can make mistakes
    2. Gemini cannot read numbers
    3. It costs more in JavaScript
    Answer

    Arithmetic in code is exact and repeatable; AI can make mistakes Correct: use deterministic code for known rules.

  2. Which output is authoritative if the commentary disagrees with the table?

    1. The computed numbers
    2. The AI commentary
    3. Whichever is longer
    Answer

    The computed numbers Correct.

  3. Why is callGemini called with jsonMode false here?

    1. The task asks for free-text observations, not structured data
    2. JSON mode is broken
    3. To save tokens
    Answer

    The task asks for free-text observations, not structured data Correct: and therefore there is no schema to validate.

  4. The commentary mentions "Q4 revenue of 5,000", which is not in your data. What is this?

    1. An unsupported (invented) claim that must be removed or corrected
    2. A rounding difference
    3. A formatting issue
    Answer

    An unsupported (invented) claim that must be removed or corrected Correct: the model added information that is not in the source.

  5. Your CFO wants commentary emailed monthly. What must be in place?

    1. A check of numeric claims and human approval before sending
    2. Nothing
    3. A higher temperature setting
    Answer

    A check of numeric claims and human approval before sending Correct: verify, then a person approves.

Five-minute presenter demonstration

Open the demo link (temporary workspace; saved learner work is not touched).

Opening hook: Raise your hand if you have ever done this by hand: Numbers alone do not explain business performance. Let us make the spreadsheet do it.

  1. 0:00–0:45 — Problem and input. Show the Workspace view, Sheets service. Point at the Metrics tab and its headers: Month, Revenue, Costs. Say what goes in and what should come out.
    Narration: Numbers alone do not explain business performance. Practical uses: Monthly budgets, project metrics and sales reviews.
  2. 0:45–1:30 — Predict and run. Ask the room: Which number does JavaScript calculate (not Gemini)? Click ▶ Run application (the same as Workshop → Run application). Open Trace to show each step the code took.
    Narration: Expected: Profit 300, 400, 50; total 750; November decline identified.
  3. 1:30–3:00 — Explain the code. Click the Code tab. Select generateInsights() in the function list; read what it reads, writes and calls. Switch Beginner / Technical as needed.
    Narration: generateInsights() calculates profit for each month and the total in JavaScript, then asks Gemini to comment on those numbers. The numbers are facts; the commentary is an interpretation you must check.
  4. 3:00–4:15 — Change one input and rerun. Back to the Workspace tab. Select the Metrics tab, click cell C4, type 800 in the formula bar and press Enter. Click ▶ Run application again.
    Narration: Workshop challenge: Change Nov cost to 800; profit becomes 100 and total 800.
  5. 4:15–5:00 — Verify and discuss automation. Click Check result. Discuss: Refresh commentary after metric updates, but avoid resending unchanged data and keep human review of the text.
    Narration: Baseline limitation: AI commentary can be wrong; calculated profits are authoritative.

Closing takeaway: JavaScript computes profit and total first; Gemini receives only calculated context.

Related resources