Zero-Output-Token AI in Google Apps Script with Gemini Decisions API

Gists

Zero-Output-Token AI in Google Apps Script with Gemini Decisions API

Introduction

Over the past three years, I published a three-part series on automating semantic Gmail labeling with Google Apps Script (GAS) and the Gemini API:

Each generation improved structural reliability, yet all three shared one underlying constraint: they relied on autoregressive text generation (generateContent) to emit classification tokens one by one. In November 2026, Google DeepMind introduced the Gemini Decisions API (POST https://generativelanguage.googleapis.com/v1beta/decisions, powered by gemini-decision-1). It evaluates structured questions in a single forward pass with zero output tokens and returns calibrated probabilities (0.01 to 0.99) alongside confidence scores.

In this article, I explain why the Decisions API fits Google Apps Script’s execution model and walk through three self-contained V8 GAS applications. I start with Flexible Labeling for Gmail (Part 4) and a controlled 4-method benchmark, move to a Gmail Model Cascade Router, and close with a 1,000-Item Parallel Compliance Audit in Google Sheets. Every latency, token, and accuracy measurement below comes from live Google Apps Script V8 runs.


1. Why Gemini Decisions API Fits Google Apps Script

As described on the official Google Apps Script site:

“Apps Script is the only low-code platform that makes it quick and easy to build business solutions that integrate, automate, and extend Google Workspace. With Apps Script, business users can build custom solutions on top of Google Workspace — no professional development experience required. Apps Script is available to anyone with a Gmail account.”

Because Google Apps Script has native affinity with Google Workspace, it is an exceptional platform for exercising fine-grained control over Gmail, Google Sheets, Google Drive, Docs, and Forms—whether through time-driven triggers, event triggers like onEdit and onFormSubmit, or custom spreadsheet functions. At the same time, GAS enforces a strict 6-minute (360-second) hard execution limit. When a script loops through hundreds of compliance rules or dozens of emails using autoregressive generateContent calls, token decoding latency and per-item network overhead accumulate quickly.

Figure 1: Autoregressive LLM Loops vs. Gemini Decisions API in Google Apps Script Figure 1: Comparison between sequential autoregressive generateContent loops and single forward-pass parallel evaluation with gemini-decision-1 in Google Apps Script.

In practice, the Gemini Decisions API changes four design constraints inside GAS:


2. Three Practical Applications Across Orthogonal Axes

To show where zero-output-token decisions outperform autoregressive generation—and where reasoning models remain essential—I built three standalone GAS applications along three distinct axes:

Repository & File Layout: All scripts are published in https://github.com/tanaikech/gemini-decisions-api-gas. The source filenames (src/usecase3_gmail_flexible_labeling.js, src/usecase3_gmail_benchmark.js, src/usecase2_gmail_cascade_router.js, and src/usecase1_compliance_audit.js) keep their original file numbering; this article orders them from Gmail labeling evolution to horizontal Sheets scale.

All six .js files in src/ (including the production operations runner src/production_runners.js) are V8-compatible and designed to coexist inside a single GAS project without namespace collisions. Each application exposes both a single one-shot test function (with pre-flight checks, a 4.5-minute safety timeout, automatic Drive log export, and full cleanup) and a production-ready runner for day-to-day Workspace automation.


3. Shared Core Client (src/decisions_client.js)

The shared client centralizes UrlFetchApp.fetch calls and passes GEMINI_API_KEY strictly via the x-goog-api-key header, never in query URLs. It also handles bounded exponential backoff on HTTP 429/5xx, normalizes response field names, and enforces a 35 MB raw-byte inline limit so Base64 expansion stays safely below UrlFetchApp’s 50 MB body cap.

function callGeminiDecisionsApi_(sharedInput, questions, modelOverride) {
  const payload = {
    model: modelOverride || GEMINI_DECISIONS_CONFIG.MODEL_DECISION,
    input: sharedInput,
    questions: questions,
  };
  const res = postGeminiJsonWithRetry_(
    GEMINI_DECISIONS_CONFIG.DECISIONS_ENDPOINT,
    payload,
  );
  const rawAnswers = res.body.answers || res.body.decisions || {};
  const normalizedAnswers = {};
  Object.keys(questions).forEach(function (qId) {
    normalizedAnswers[qId] = normalizeDecisionAnswer_(rawAnswers[qId]);
  });
  return {
    answers: normalizedAnswers,
    usage: {
      inputTokens: res.body.usage ? res.body.usage.totalInputTokens : null,
      outputTokens: 0,
      thinkingTokens: 0,
    },
    apiLatencyMs: res.apiLatencyMs,
    retries: res.retries,
  };
}

The complete client—including multimodal input builders, MIME whitelisting, generateContent wrappers with explicit thinkingLevel control, and Gmail/Drive cleanup helpers—is available in src/decisions_client.js.


4. Use Case 1: Flexible Labeling for Gmail (Part 4) & 4-Method Benchmark

I start by picking up directly from my three prior Gmail labeling articles (Part 1, Part 2, and Part 3), which focused on multi-axis inbox classification in Google Apps Script (src/usecase3_gmail_flexible_labeling.js and src/usecase3_gmail_benchmark.js).

Figure 2: Evolution of Flexible Labeling for Gmail in GAS (Part 1 to Part 4) Figure 2: Architectural progression across Part 1 (Prompt Free-Text), Part 2 (Semantic Search / Function Calling), Part 3 (JSON Schema), and Part 4 (Gemini Decisions API).

Figure 2 and Table 1 summarize the structural shift across the four generations. Parts 1 through 3 progressively constrained how autoregressive text tokens were formatted; Part 4 removes text token generation altogether while adding native calibrated confidence gating (NeedsReview when confidence < 0.85).

Table 1: Architectural Comparison Across Gmail Labeling Approaches in GAS Table 1: Architectural comparison across Part 1 through Part 4 Gmail labeling implementations in Google Apps Script.

In src/usecase3_gmail_flexible_labeling.js, uc3ClassifyEmailWithDecisions_() evaluates primary category (choice), independent boolean flags (is_action_required, is_urgent via noul), and priority (score) in one pass. The production trigger entry point labelGmailWithDecisions() caches GmailLabel objects in a per-run Map to minimize Gmail API overhead.

Controlled 4-Method Benchmark Design (src/usecase3_gmail_benchmark.js)

What this benchmark tests: Given the exact same 6 incoming Gmail emails (including a PDF invoice attachment and an intentionally ambiguous message), all four GAS labeling approaches—Part 1 Free-Text, Part 2 Function Calling, and Part 3 JSON Schema on gemini-3.8-flash vs. Part 4 Decisions API on gemini-decision-1—are asked to predict the exact same three outputs for every email: a primary category (Academic, Finance, Advertisement, Support, or Other), two boolean flags (ActionRequired, Urgent), and a 1–5 priority score. The goal is to measure whether switching from autoregressive text/JSON generation to Decisions API reduces latency and token cost without sacrificing accuracy, and whether calibrated confidence catches ambiguous emails before applying a wrong label.

To keep the comparison fair inside GAS without deprecated models or execution-order bias, testUseCase3GmailBenchmark() applies six experimental controls illustrated in Figure 3:

Figure 3: Multi-Axis Gmail Labeling & 4-Method Benchmark Harness Figure 3: One-shot Latin-square benchmark harness in src/usecase3_gmail_benchmark.js measuring isolated API latency, accuracy, Macro-F1, and token cost across all four methods.

Figure 4: Live GAS 4-Method Gmail Labeling Benchmark Chart Figure 4: Empirical latency distribution (left), estimated cost per 1,000 emails with output/thinking token counts (top right), and gemini-decision-1 calibrated confidence gate across all 6 emails (bottom right), measured across 48 live GAS V8 trials.

Figure 4 reads across three complementary panels: the left panel plots median API latency bars overlaid with all 12 individual trial points and p95 diamond markers; the top-right panel compares estimated cost per 1,000 emails alongside average output and thinking token counts; and the bottom-right panel shows gemini-decision-1’s calibrated confidence for each test email against the dashed 0.85 auto-label threshold.

Table 2: Live GAS 4-Method Gmail Labeling Benchmark Results Table 2: Live GAS V8 benchmark results measured via testUseCase3GmailBenchmark() (N = 6, R = 2, measured on November 23, 2026).

Key Empirical Findings from Live GAS Execution

The live Latin-square benchmark across 48 API calls (measured on November 23, 2026; post-benchmark live Gmail label application total: 3,750 ms across 6 threads) revealed four concrete takeaways:


5. Use Case 2: Gmail Trigger-Driven Model Cascade Router

While Use Case 1 focuses on multi-axis inbox labeling, real support and operations pipelines must also decide when to invoke a heavyweight reasoning model to draft a substantive reply. Not every incoming email warrants frontier reasoning latency and cost, yet complex outages or legal disputes cannot be answered with static templates. Use Case 2 implements a two-stage model cascade in src/usecase2_gmail_cascade_router.js.

Figure 5: Gmail Trigger-Driven Model Cascade Router Figure 5: Vertical escalation workflow routing routine Gmail threads through gemini-decision-1 (Fast Path) and cascading complex or low-confidence threads to gemini-4-hydrogen.

Stage 1 evaluates each incoming Gmail thread—including whitelisted PDF or image attachments—with gemini-decision-1 across three questions: is_action_required (noul), intent_category (choice across routine_inquiry, billing, technical_escalation, and informational), and complexity_risk (score on a 0–4 rubric). A simple threshold rule (confidence < 0.85 or complexity >= 3) decides whether to escalate:

const shouldEscalate =
  confidence < UC2_CONFIDENCE_THRESHOLD ||
  complexityScore >= UC2_COMPLEXITY_CASCADE_THRESHOLD;

if (shouldEscalate) {
  const escRes = uc2CallReasoningEscalation_(emailText, attachments, {
    category: category,
    confidence: confidence,
    complexityScore: complexityScore,
  });
  thread.addLabel(escalatedLabel);
  createdDrafts.push(thread.createDraftReply(escRes.draftBody));
} else {
  thread.addLabel(fastLabel);
}

When shouldEscalate is true, Stage 2 invokes gemini-4-hydrogen with thinkingConfig: { thinkingLevel: "HIGH" } to draft a detailed reply (with an optional fallback to gemini-3.8-flash).

Live GAS Validation & Cascade Results (testUseCase2GmailCascadeRouter())

What this validation tests: Unlike Use Case 1’s head-to-head model comparison, Use Case 2 verifies whether a two-stage cascade router inside Gmail can reliably separate routine inquiries from ambiguous or high-risk threads—handling routine mail cheaply with gemini-decision-1 alone while escalating only the hard cases to gemini-4-hydrogen for full reply drafting. Specifically, it measures (1) routing accuracy (does every email take the intended path?) and (2) latency savings (how much time is saved on routine mail by skipping Stage 2 reasoning?).

To validate both branches without preparing sample emails manually, testUseCase2GmailCascadeRouter() generates a real PDF attachment (incident_409.pdf, reporting an EU-West HTTP 500 API outage with a $42,000 billing dispute and SLA penalty clause) and sends 3 fixed test emails to your own Gmail Inbox:

After polling Inbox until all 3 emails arrive (excluded from API timing), runGmailCascadeRouter() runs Stage 1 triage on each thread and escalates qualifying threads to Stage 2 gemini-4-hydrogen (thinkingLevel: "HIGH") to generate a Gmail reply draft. It then verifies all 3 routing outcomes, saves the log to Google Drive (GeminiDecisionsTestLogs/), and deletes all temporary drafts, threads, and nested labels in finally.

Figure 6: Live GAS Results: Gmail Model Cascade Router Figure 6: Empirical Stage 1 vs. Stage 2 API latency (left), 2D confidence-complexity decision plane with conf = 0.85 and score = 3.0 gates (top right), and live routing summary across all three GAS V8 test emails (bottom right).

In the live GAS V8 run, all 3/3 routing checks passed. The three panels in Figure 6 highlight the measured trade-offs:

Key Empirical Findings from Live GAS Execution


6. Use Case 3: 1,000-Item Parallel Compliance Audit on Google Sheets

Use Cases 1 and 2 operate on Gmail threads. Use Case 3 shifts to Google Sheets to demonstrate horizontal scale (1 shared multimodal input × up to 1,000 criteria) in src/usecase1_compliance_audit.js. When auditing a corporate security policy or vendor contract PDF against hundreds of checklist rules, calling a chat model once per row re-sends the entire document hundreds of times.

Figure 7: 1,000-Item Parallel Compliance Audit on Google Sheets Figure 7: Horizontal scale workflow in src/usecase1_compliance_audit.js evaluating up to 1,000 criteria against one shared Drive PDF input per batch.

How Google Sheets, Google Drive, and Gemini Decisions API Work Together

In this workflow, Google Sheets acts as both the checklist input table and the color-coded audit report, while Google Drive stores the target PDF (such as a security policy or vendor contract). Row 1 holds four headers (Audit Criterion, P(Compliant), Confidence, Verdict), you list one yes/no compliance question per row in Column A (A2:A), and runComplianceAudit(fileId, spreadsheetId, sheetName) executes four concrete steps inside GAS:

// 1. Map Column A criteria to noul questions (up to 1,000 per batch)
chunk.forEach(function (entry, idx) {
  const qKey = "q_" + String(sliceStart + idx + 1).padStart(4, "0");
  questions[qKey] = {
    type: "noul",
    instructions:
      "Does the document explicitly satisfy this compliance requirement? " +
      "Criterion: " +
      entry.text,
  };
});

// 2. Send 1 shared Drive PDF + all questions in one forward pass
const response = callGeminiDecisionsApi_(sharedInput, questions);

// 3. Batch-write Columns B–D (P(Compliant), Confidence, Verdict) & row colors
const outRange = sheet.getRange(2, 2, valuesMatrix.length, 3);
outRange.setValues(valuesMatrix);
outRange.setBackgrounds(bgMatrix);

How to Run This in Your Own Google Sheet

You can execute this audit in two practical ways using src/production_runners.js:

Live GAS Validation & Audit Results (testUseCase1ComplianceAudit())

What this test does: Suppose you have one security policy PDF in Google Drive and a Google Sheet listing 25 checklist items (such as “Does the policy require AES-256 encryption?” or “Does it offer HIPAA BAA compliance?”). With a normal chat LLM, checking each row separately means uploading the same PDF 25 times. Here, runComplianceAudit() sends the PDF once together with all 25 questions in a single Decisions API request, then writes every PASS, FAIL, or NEEDS_REVIEW result back to the Sheet. This test checks three practical things: how many input tokens are saved by sending the PDF once instead of 25 times, how fast the API call and Sheet update complete, and whether clear items are judged accurately while ambiguous items are flagged NEEDS_REVIEW for human review.

To verify this workflow without preparing external files beforehand, testUseCase1ComplianceAudit() generates a sample policy PDF and a checklist Sheet automatically:

runComplianceAudit() sends the PDF once with all 25 noul questions in a single gemini-decision-1 forward pass. Each returned probability P passes through the 0.85 confidence gate: P >= 0.85 maps to PASS, P <= 0.15 to FAIL, and 0.15 < P < 0.85 to NEEDS_REVIEW. The script then writes all 25 probabilities, confidences, verdicts, and row highlights back to the Sheet in one batch, saves the log to Google Drive (GeminiDecisionsTestLogs/), and trashes both temporary files inside finally.

Figure 8: Live GAS Results: 25-Criterion Batch Compliance Audit (Google Sheets) Figure 8: Empirical per-criterion compliance probabilities for all 25 criteria (left), shared-input token savings vs. sequential calls (top right), and sub-second core audit latency breakdown (bottom right) measured in live GAS V8.

Here is how to read the three graphs in Figure 8 (out of the 22 clear PASS/FAIL ground-truth items, 20/22 (90.9%) were auto-classified accurately, and the remaining 2 were safely routed to human review rather than misclassified):

Key Empirical Findings from Live GAS Execution


7. Setup, Production Operation & Future Extensions

Follow the step-by-step guide in README.md from tanaikech/gemini-decisions-api-gas to paste the six src/*.js files and src/appsscript.json into a new Google Apps Script project, set GEMINI_API_KEY in Script Properties, and authorize OAuth scopes once. You can verify each workflow immediately using testUseCase3GmailBenchmark(), testUseCase2GmailCascadeRouter(), or testUseCase1ComplianceAudit().

Running All Three Use Cases in Production (src/production_runners.js)

To move directly from testing to daily Workspace operation without writing glue code, src/production_runners.js adds LockService-guarded trigger runners, idempotent trigger installers, and a Google Sheets custom menu controlled by PRODUCTION_CONFIG:

Future Extensions

Beyond these three core applications, the same zero-output-token architecture extends naturally to broader Workspace agent systems:


Summary

The Gemini Decisions API (gemini-decision-1) removes the primary bottleneck of running AI inside Google Apps Script—sequential autoregressive token generation—by evaluating structured questions in a single sub-second forward pass with strictly zero output tokens and native calibrated probabilities:

All source scripts, one-shot test harnesses, and turnkey production runners are ready to copy and deploy from https://github.com/tanaikech/gemini-decisions-api-gas.


References

 Share!