Drop-In Upgrade or Silent Production Trap? Gemini 4 Hydrogen GA Deep Dive, 57% Terminal-Bench & Zero-Downtime Migration Guide (With 3-OS Audit Scripts)
Let us start with the blunt reality: late on November 12, 2026, Google launched Gemini 4 Hydrogen (gemini-4-hydrogen) into general availability across every major developer and consumer surface. If your migration plan is simply swapping a model string in config and pushing to production, expect a 2:00 AM page complaining of empty HTTP 200 OK responses, unexpected reasoning token bills, or premature context amnesia. Yet when configured properly, Hydrogen delivers nearly 2x faster agentic throughput while cutting real-world per-task spend by 59% compared to Gemini 3.8 Flash.
Many engineering teams assume a new “Flash-speed” GA release is merely an optional speedup. In reality, Google coupled the launch of Gemini 4 Hydrogen with two non-negotiable calendar cliffs for older pipelines: on December 1, 2026, retired gemini-2.5-pro workloads will automatically redirect to gemini-3.8-flash while flagship gemini-4-carbon and gemini-4-argon standard prices double (jumping to $4.00 / $20.00 per million tokens); one month later on January 1, 2027, gemini-3.8-flash itself doubles in price to $1.50 / $7.50—the exact same rate as Hydrogen today.
This is not an optional benchmark curiosity. You have a narrow multi-week engineering window to transition legacy Gemini pipelines into the Gemini 4 Hydrogen architecture cleanly, or get forced into surprise routing changes and 2x token invoices right at year-end.

Figure 1: Original cover blueprint summarizing Gemini 4 Hydrogen GA launch benchmarks, the 1M unified pool, 8 migration checks, and approaching Dec 1 / Jan 1 pricing cliffs.
1. Problem Background: Why Hydrogen Replaces Your Default Workhorse Stack
According to the official announcement on November 12, 2026 by Google Chief AI Architect Koray Kavukcuoglu, Gemini 4 Hydrogen was distilled and adapted from Google’s frontier flagship Gemini 4 Carbon (with a March 2026 knowledge cutoff). Unlike Carbon and Argon—which shipped strictly behind paid billing tiers—Hydrogen launches Day-One across both free and paid ecosystems:
- Full API & Studio Rollout: Available immediately in Google AI Studio and Gemini API on both a rate-limited Free tier (note: inputs may be used to improve Google products) and a data-protected Paid tier spanning Standard, Flex, Batch, and Priority serving tiers;
- AI-Native Agentic Development: Live across Google Antigravity as
Gemini 4 Hydrogenand wired directly underneath upgradedOrchestrator (Carbon)andOrchestrator (Argon)multi-model coordinators; - Search & Productivity Ecosystem: Rolled out across Google Search (including AI Overviews and AI Mode at no charge), the Gemini App, Android Studio (end-to-end app creation), and Google Sheets.
Figure 2: Live browser capture of Google’s official November 12, 2026 launch announcement for Gemini 4 Hydrogen.
Google’s positioning is crystal clear: teams previously suffered a brutal tradeoff between “cheap, jittery small models that stumble in multi-step terminal loops” and “frontier flagships that are slow and expensive for routine repo churn.” Hydrogen executes parallel tool calls—reading multiple files, grepping symbols, editing schemas, and verifying tests simultaneously—delivering 2x to 2.8x faster completion on multi-file retrieval while using 12% to 23% fewer tokens on complex graph traversal and SQL synthesis.
Figure 3: Live capture of Google’s developer rollout brief detailing parallel tool calling and rapid coding workflows.
Here is the pricing and retirement schedule every engineering lead needs on the wall:
| Model ID | Current GA Status | Standard Input / Output (per 1M Tokens) | Mandatory Dec 1, 2026 & Jan 1, 2027 Shifts |
|---|---|---|---|
gemini-4-hydrogen |
GA (Free + Paid) | $1.50 / $7.50 (Implicit cache $0.075) | Long-term production default; Batch/Flex 50% off at $0.75 / $3.75 |
gemini-4-argon |
Frontier Flagship (Paid) | Current $2.00 / $10.00 | Doubles Dec 1, 2026 to $4.00 / $20.00 |
gemini-4-carbon |
Frontier Peak (Paid) | Current $2.00 / $10.00 | Doubles Dec 1, 2026 to $4.00 / $20.00 |
gemini-3.8-flash |
Legacy Transition | Current $0.75 / $3.75 | Doubles Jan 1, 2027 to $1.50 / $7.50 (zero price savings vs Hydrogen) |
gemini-2.5-pro |
Deprecated | Legacy Pipelines | Auto-routes to 3.8 Flash on Dec 1, 2026 |
2. Plain-English Mental Models: Kitchens, Swimming Pools & Four-Gear Bikes
Most production regressions during a Hydrogen migration do not stem from complex syntax—they happen because engineers carry legacy mental models from Gemini 3.8 Flash. Let us translate the three core architectural changes into everyday intuition any elementary schooler can follow cleanly without sacrificing engineering accuracy:

Figure 4: Original intuition map linking Antigravity orchestration, unified pool budgeting, and ignored sampling parameters to everyday scenarios.
1. The Master Chef & Lightning Sous-Chef (Orchestrator Economics)
Imagine running a packed restaurant. To save hourly wages, you hired an inexpensive prep cook (legacy Flash) who constantly drops plates and misreads orders. Your Michelin head chef (Carbon) ends up fixing half the dishes personally, driving total labor per order to $7.77.
Hydrogen acts like an ultra-fast, hyper-competent lightning sous-chef: its hourly rate is twice as high on paper, yet it juggles six pans at once (parallel tool calling) and gets multi-step prep right on the first pass. Carbon writes the recipe and inspects the final plate; Hydrogen handles ~80% of the searching, slicing, editing, and test runs. Total labor per finished dish plunges to $3.16—a 59% savings!
2. One Giant Swimming Pool vs. a Split Bento Box (Unified 1M Context Pool)
Legacy models operated like a two-compartment bento box: one dedicated chamber for what you feed in (up to 1M input tokens), and a separate output chamber reserved solely for writing answers.
Gemini 4 Hydrogen merges everything into one single 1,048,576-token swimming pool. Your prompt (Input) + the model’s scratchpad (Thinking tokens) + your final response (Output) all swim inside that exact same pool!
Two hard physical rules follow immediately:
- If you dump 900,000 tokens of raw logs into the pool, only 148,576 tokens remain for both scratchpad thinking and visible answers combined;
- Watch the shared lid:
max_output_tokenslimits Thinking + Visible Output together. Legacy pipelines often leave conservative defaults likemax_output_tokens=8192sitting in config. Because Hydrogen thinks deeply by default, its scratchpad alone burns all 8,192 tokens, hits the lid, and yields anincompleteresponse with zero characters of visible text.
Also remember the faucet rule: normal synchronous requests (streaming or non-streaming) cap at 65,536 tokens (64K) per hop. To pour past 64K all the way up to the remaining pool boundary, enable the background relay pump (background=True + store=True + max_output_tokens > 65536).
3. The Four-Gear Bike & Ignored Salt Shaker (Thinking Levels & Sampling)
On older Flash models, the gearbox started at minimal, idled by default in medium, and let callers twist knobs like temperature, top_p, and top_k.
Hydrogen changes both levers dramatically:
- Goodbye
minimal, welcomehighby default: Hydrogen offers strictly four gears—low,medium,high, andxhigh(calledExtrain Antigravity UI). Passingthinking_level="minimal"throws an immediate error, while omitting the parameter defaults tohigh, billing deep reasoning traces at the $7.50 / 1M output rate; - The politely ignored salt shaker: If you send
temperature=0.1ortop_p=0.9in your request payload, the server returnsHTTP 200 OKwithout complaining—and silently ignores your shaker to cook with DeepMind's calibrated defaults. Never rely ontemperature=0for valid JSON formatting again; enforce schema structure cleanly with Structured Outputs.
3. Symptoms in Production: 5 Failure Patterns After Naive Model Swaps
External evaluations from routing platform OrcaRouter alongside Google AI Studio’s official migration guide reveal five classic failure symptoms triggered when teams swap only the model name:
Figure 5: Live screenshot of OrcaRouter’s migration field report documenting silent parameter changes between 3.8 Flash and Hydrogen.
- Symptom A (Silent JSON Drift): Extraction workers guarded only by
temperature=0occasionally emit conversational wrappers or minor format drift while returning HTTP 200. - Symptom B (Empty Output + Unexpected Cost): Quick classification endpoints spike in latency and occasionally return zero visible text because default
thinking_level=“high”collides with legacymax_output_tokens=4096/8192caps. - Symptom C (Immediate 400 Failures): Fast micro-classifiers passing
thinking_level=“minimal”fail loudly upon cutover. - Symptom D (Premature Compaction & Zero Cache Discount): Legacy
cachedContents.createcalls fail outright, and multi-hop Long Decode loops computing context usage fromusage.total_input_tokensprematurely trigger conversation compaction after hop 2 because repeated input tokens are summed across every hop. - Symptom E (Modality & Refusal Edge Shifts): Pipelines attempting Live API audio/video streaming, native image generation, or native audio synthesis hit unsupported-feature errors; meanwhile, image-to-text prompts near safety boundaries experience stricter filtering (DeepMind’s Model Card notes a +5.57 percentage-point shift in unjustified refusals vs. 3.8 Flash, driven by a +7.00pp tightening on image-to-text safety while keeping HealthBench Pro false refusals below 0.4%).
4. Root Cause Breakdown: The Complete 6+2 Migration Matrix
To eliminate guesswork before production cutover, here is the complete behavioral split separating silent HTTP 200 changes from explicit breaking errors:

Figure 6: Original diagnostic matrix contrasting the four silent HTTP 200 behavioral shifts (Zone A) against explicit breaking constraints (Zone B).
Deep Dive 1: Locking Down temperature / top_p / top_k & Structured Tools
Because Gemini 4 Hydrogen is RL-tuned natively for joint reasoning-and-action exploration, forcing near-zero sampling temperatures in post-training causes brittle backtracking loops during multi-step debugging. Rather than rejecting older configs, Google preserves backward request compatibility by accepting custom sampling values with HTTP 200 and neutralizing them at inference time. Enforce schemas exclusively via native Structured Outputs and declared tool schemas (avoid raw markdown-fenced JSON instructions in system prompts, which risk MALFORMED_FUNCTION_CALL).
Deep Dive 2: Breaking the 64K Output Ceiling Safely (Long Decode)
Per Google AI Studio’s Long Decode documentation, both streaming and non-streaming synchronous hops max out at 65,536 tokens. Exceeding 64K requires choosing one of two explicit paths:
- Server-Side Interactions API: Pass BOTH
background=True,store=True, and an explicitmax_output_tokens > 65536(if you passbackground=Truewithout raisingmax_output_tokensabove 65,536, generation still stops at 64K!); - Client-Side SDK Continuation: Upgrade to minimum SDK versions supporting transparent client continuation—Python
google-genai >= 2.34.0, JS/TS>= 2.32.0, Go>= 1.77.0, Java>= 1.80.0, .NET>= 1.28.0—and track true window occupancy viainitial_input_tokens + total_output_tokens + total_thought_tokensinstead oftotal_input_tokens.
Deep Dive 3: Capturing the 95% Implicit Caching Discount Without Busting Prefix Trees
Explicit cache objects (cachedContents / caches.create) are unsupported on Hydrogen. In exchange, Google turned Implicit Caching into a zero-config engine that automatically slashes cached input rates by 95% ($0.075 / 1M tokens) whenever consecutive requests share an exact prefix of at least 4,096 tokens. Never inject timestamps, request UUIDs, or ephemeral session IDs near the start of system instructions; pin static system prompts, shared repo maps, and tool schemas up front, appending dynamic deltas strictly at the tail.
Figure 7: Live capture of Google Search’s global Gemini 4 Hydrogen upgrade post, demonstrating production-scale retrieval and grounding readiness.
5. Production Agentic Setup & Zero-Dependency 3-OS Automation Scripts
With every constraint accounted for, let us wire together a clean, repeatable production workflow spanning code, Google Antigravity, and cross-platform CI verification.

Figure 8: Original architecture blueprint uniting Carbon/Argon top-level orchestration, 4,096+ token prefix caching, and safe >64K Long Decode handoffs.
Step 1: Canonical Python SDK, Antigravity CLI & Skill Setup
- Recommended Python
google-genaiPattern (Safe Across All 8 Rules)
# pip install -U "google-genai>=2.34.0"
from google import genai
from google.genai import types
client = genai.Client()
# Pattern A: High-throughput routing / classification (override default=high -> low)
fast_resp = client.models.generate_content(
model="gemini-4-hydrogen",
contents=static_4096_prefix + "\n" + user_query,
config=types.GenerateContentConfig(
thinking_level="low",
max_output_tokens=16384, # covers thinking + JSON output cleanly
response_mime_type="application/json",
response_schema=MyStrictSchema, # replaces ignored temperature=0
),
)
# Pattern B: Multi-file >64K generation via Interactions API Long Decode
long_job = client.interactions.create(
model="gemini-4-hydrogen",
input=massive_spec,
background=True,
store=True,
generation_config={"max_output_tokens": 180000, "thinking_level": "high"},
)
- Enabling Google Antigravity
Orchestrator&Extra (xhigh)Mode On Antigravity’sTerminal-Bench 4.0coding suite, routing tasks throughOrchestrator (Carbon)/Orchestrator (Argon)backed byGemini 4 Hydrogenpreserves Carbon-grade pass rates while reducing Antigravity quota consumption by 24% and cutting wall-clock latency by 19%. From theagyCLI, invoke maximum reasoning depth when tackling gnarly cross-file bugs:
agy --model gemini-4-hydrogen --effort xhigh
# Or via official shorthand alias
agy --model gemini-4-hydrogen-xhigh
Figure 9: Live capture of antigravity.google/docs/models/ showing Orchestrator delegation and Hydrogen model tiers.
- Equip Coding Agents with the Official
gemini-api-devSkill Prevent coding assistants from hallucinating retiredgoogle-generativeaiimports or removedcachedContentsAPIs by installing Google’s live skill and MCP docs server:
npx skills add google-gemini/gemini-skills --skill gemini-api-dev --global
# Or attach the hosted Gemini API MCP endpoint: https://aistudio.google.com/mcp
Step 2: Zero-Dependency Cross-Platform Pre-Flight Audit Scripts (Win11 / Ubuntu 26.04 / macOS 27)
Before swapping model strings across dozens of repositories, run an automated static + environment pre-flight check. Below are three zero-third-party-dependency scripts engineered for Windows 11 (PowerShell), Ubuntu 26.04 (Bash), and macOS 27 (Zsh).
Each script scans for all eight migration risks (G4H-TRAP-01 through G4H-TRAP-08), inspects local Python google-genai SDK version compliance (>= 2.34.0), detects Antigravity agy CLI readiness, optionally probes model metadata if GEMINI_API_KEY is exported (without ever printing secrets or hostnames), and supports both human and autonomous agent workflows:
- Method 1 — Human Interactive Mode: Run with zero flags; confirm target folder and probe preferences via clean terminal prompts and inspect a human-aligned summary table.
- Method 2 — Autonomous AI Agent Mode: Pass
--auto --json --write-plan(or-Auto -Json -WritePlanon Windows) for zero-prompt CI execution emitting strict JSON plus exit code1whenever hard blockers (such asminimalthinking level or retired SDK imports) exist.
Here is a real live execution capture running our macOS 27 Zsh script directly against a synthetic migration test fixture in both modes:
Figure 10: Real execution capture of gemini4_hydrogen_audit_macos27.zsh scanning a test repository—detecting 12 traps cleanly in both aligned human table and –json agent output.
1. Windows 11 PowerShell Script (gemini4_hydrogen_audit_windows11.ps1)
Human Interactive: .\gemini4_hydrogen_audit_windows11.ps1
Agent Automated: powershell -ExecutionPolicy Bypass -File .\gemini4_hydrogen_audit_windows11.ps1 -Target .\your-repo -Auto -Json -WritePlan
<#
.SYNOPSIS
Gemini 4 Hydrogen (GA) Migration & Agentic Pre-Flight Audit — Windows 11 PowerShell 5.1 / 7+
Zero third-party dependencies (uses built-in Get-ChildItem, Select-String, Invoke-RestMethod).
.EXAMPLE
Human Interactive: .\gemini4_hydrogen_audit_windows11.ps1
Agent Automated: .\gemini4_hydrogen_audit_windows11.ps1 -Target .\repo -Auto -Json
#>
[CmdletBinding()]
param(
[string]$Target = ".",
[switch]$Auto,
[switch]$Json,
[switch]$Probe,
[switch]$WritePlan,
[switch]$Help
)
$ErrorActionPreference = "Stop"
if ($Help) {
Write-Output "Usage: .\gemini4_hydrogen_audit_windows11.ps1 [-Target <dir>] [-Auto] [-Json] [-Probe] [-WritePlan]"
exit 0
}
if ($Json) { $Auto = $true }
if (-not (Test-Path -Path $Target -PathType Container)) {
Write-Error "Target directory not found: $Target"
exit 2
}
$TargetAbs = (Resolve-Path -Path $Target).Path
if (-not $Auto) {
Write-Host "=====================================================================" -ForegroundColor Cyan
Write-Host " Gemini 4 Hydrogen (GA) Pre-Flight Audit - Windows 11 Interactive" -ForegroundColor Blue
Write-Host "=====================================================================" -ForegroundColor Cyan
$inputDir = Read-Host "Target project [$TargetAbs] (Press Enter to keep)"
if ($inputDir -and $inputDir.Trim() -ne "") {
if (-not (Test-Path -Path $inputDir -PathType Container)) {
Write-Error "Directory not found: $inputDir"
exit 2
}
$TargetAbs = (Resolve-Path -Path $inputDir).Path
}
$probeAns = Read-Host "Run optional live check if GEMINI_API_KEY / agy CLI present? [y/N]"
if ($probeAns -match "^[Yy]") { $Probe = $true }
$planAns = Read-Host "Write sanitized migration plan JSON into target folder? [y/N]"
if ($planAns -match "^[Yy]") { $WritePlan = $true }
}
$TargetBase = Split-Path -Path $TargetAbs -Leaf
$Extensions = @("*.py","*.ts","*.tsx","*.js","*.jsx","*.mjs","*.go","*.java","*.cs","*.rs","*.json","*.yaml","*.yml","*.toml",".env*","requirements*.txt","go.mod","pyproject.toml")
$SkipDirsRegex = '\\(\.git|node_modules|\.venv|venv|__pycache__|dist|build|\.next)(\\|$)'
$Files = Get-ChildItem -Path $TargetAbs -Recurse -File -Include $Extensions -ErrorAction SilentlyContinue |
Where-Object { $_.FullName -notmatch $SkipDirsRegex -and $_.Name -ne ".gemini4-migration-plan.json" }
function Invoke-RuleScan {
param([string]$Pattern)
$matchesList = @()
if ($Files) {
$matchesList = $Files | Select-String -Pattern $Pattern -AllMatches -ErrorAction SilentlyContinue
}
$count = 0
$sample = ""
if ($matchesList) {
$count = ($matchesList | ForEach-Object { $_.Matches.Count } | Measure-Object -Sum).Sum
$first = $matchesList | Select-Object -First 1
if ($first) {
$relPath = $first.Path.Substring($TargetAbs.Length).TrimStart('\','/') -replace '\\','/'
$lineSnippet = ($first.Line.Trim() -replace '[\r\n]+', ' ')
if ($lineSnippet.Length -gt 80) { $lineSnippet = $lineSnippet.Substring(0, 80) }
$sample = "${relPath}:$($first.LineNumber):$lineSnippet"
}
}
return [PSCustomObject]@{ Count = [int]$count; Sample = $sample }
}
$rSampling = Invoke-RuleScan '["'']?(temperature|top_p|topP|top_k|topK)["'']?\s*[:=]'
$rMinimal = Invoke-RuleScan 'thinking_?[lL]evel["''\s:=]+(MINIMAL|minimal)'
$rLowCap = Invoke-RuleScan '["'']?max_?[oO]utput_?[tT]okens["'']?\s*[:=]\s*([1-9][0-9]{0,3}|16384)([^0-9]|$)'
$rCache = Invoke-RuleScan 'cachedContents|caches\.create|cached_content'
$rLegacy = Invoke-RuleScan 'gemini-(2\.5-pro|3\.8-flash|4-carbon|4-argon)'
$rTokenTrap = Invoke-RuleScan 'total_input_tokens'
$rOldSdk = Invoke-RuleScan 'google-generativeai|import google\.generativeai|@google/generative-ai'
$rLiveMedia = Invoke-RuleScan 'bidiGenerateContent|aio\.live|IMAGE_GENERATION|response_modalities.*AUDIO|gemini-4-hydrogen.*(IMAGE|AUDIO)'
$TotalIssues = $rSampling.Count + $rMinimal.Count + $rLowCap.Count + $rCache.Count + $rLegacy.Count + $rTokenTrap.Count + $rOldSdk.Count + $rLiveMedia.Count
$PythonGenAiVer = "not_installed"
if (Get-Command python -ErrorAction SilentlyContinue) {
try {
$ver = & python -c "import importlib.metadata as m; print(m.version('google-genai'))" 2>$null
if ($ver) { $PythonGenAiVer = $ver.Trim() }
} catch {}
} elseif (Get-Command py -ErrorAction SilentlyContinue) {
try {
$ver = & py -3 -c "import importlib.metadata as m; print(m.version('google-genai'))" 2>$null
if ($ver) { $PythonGenAiVer = $ver.Trim() }
} catch {}
}
$AgyStatus = "not_found"
if (Get-Command agy -ErrorAction SilentlyContinue) {
try {
$AgyStatus = (& agy --version 2>$null | Select-Object -First 1).ToString().Trim()
if (-not $AgyStatus) { $AgyStatus = "installed" }
} catch { $AgyStatus = "installed" }
}
$ApiProbeStatus = "skipped"
if ($Probe) {
if ($env:GEMINI_API_KEY) {
try {
$resp = Invoke-WebRequest -Uri "https://generativelanguage.googleapis.com/v1beta/models/gemini-4-hydrogen" `
-Headers @{ "x-goog-api-key" = $env:GEMINI_API_KEY } -TimeoutSec 8 -UseBasicParsing
$ApiProbeStatus = "ok_http_$($resp.StatusCode)"
} catch {
$ApiProbeStatus = "probe_error"
}
} else {
$ApiProbeStatus = "no_GEMINI_API_KEY_in_env"
}
}
$Payload = [ordered]@{
tool = "gemini4-hydrogen-audit"
os = "Windows 11 (PowerShell)"
model_target = "gemini-4-hydrogen"
project_basename = $TargetBase
total_findings = $TotalIssues
environment = [ordered]@{
google_genai_python_sdk = $PythonGenAiVer
recommended_min_python_sdk = "2.34.0"
antigravity_cli = $AgyStatus
api_model_metadata_probe = $ApiProbeStatus
}
checks = @(
@{ id = "G4H-TRAP-01"; severity = "SILENT_HTTP_200"; title = "Ignored sampling overrides (temperature/top_p/top_k)"; count = $rSampling.Count; sample = $rSampling.Sample },
@{ id = "G4H-TRAP-02"; severity = "LOUD_ERROR"; title = "Unsupported minimal thinking_level (defaults to high on Hydrogen)"; count = $rMinimal.Count; sample = $rMinimal.Sample },
@{ id = "G4H-TRAP-03"; severity = "SILENT_TRUNCATION"; title = "Low max_output_tokens <=16384 starves thinking + output budget"; count = $rLowCap.Count; sample = $rLowCap.Sample },
@{ id = "G4H-TRAP-04"; severity = "UNSUPPORTED_FEATURE"; title = "Explicit caching calls (use implicit >=4096 token cache on Hydrogen)"; count = $rCache.Count; sample = $rCache.Sample },
@{ id = "G4H-TRAP-05"; severity = "COST_OR_DEPRECATION"; title = "Legacy Gemini model IDs facing Dec 1 / Jan 1 price or routing shifts"; count = $rLegacy.Count; sample = $rLegacy.Sample },
@{ id = "G4H-TRAP-06"; severity = "COMPACTION_BUG"; title = "total_input_tokens used in Long Decode multi-hop accounting"; count = $rTokenTrap.Count; sample = $rTokenTrap.Sample },
@{ id = "G4H-TRAP-07"; severity = "RETIRED_SDK"; title = "Retired google-generativeai / @google/generative-ai package"; count = $rOldSdk.Count; sample = $rOldSdk.Sample },
@{ id = "G4H-TRAP-08"; severity = "UNSUPPORTED_MODALITY"; title = "Live API / native image or audio generation markers"; count = $rLiveMedia.Count; sample = $rLiveMedia.Sample }
)
}
$JsonText = $Payload | ConvertTo-Json -Depth 5
if ($WritePlan) {
$PlanPath = Join-Path -Path $TargetAbs -ChildPath ".gemini4-migration-plan.json"
Set-Content -Path $PlanPath -Value $JsonText -Encoding UTF8
}
if ($Json) {
Write-Output $JsonText
} else {
Write-Host "`nTarget folder: $TargetBase Findings: $TotalIssues"
Write-Host "Python google-genai SDK: $PythonGenAiVer (min >= 2.34.0 for Long Decode client continuation)"
Write-Host "Antigravity CLI (agy): $AgyStatus API Metadata Probe: $ApiProbeStatus"
Write-Host "---------------------------------------------------------------------"
"{0,-13} | {1,-19} | {2,5} | {3}" -f "Check ID", "Behavior", "Hits", "First Relative Hit" | Write-Host
Write-Host "---------------------------------------------------------------------"
foreach ($chk in $Payload.checks) {
$samp = if ($chk.sample) { $chk.sample } else { "-" }
"{0,-13} | {1,-19} | {2,5} | {3}" -f $chk.id, $chk.severity, $chk.count, $samp | Write-Host
}
Write-Host "---------------------------------------------------------------------"
if ($WritePlan) {
Write-Host "Saved migration plan: $TargetBase/.gemini4-migration-plan.json" -ForegroundColor Green
}
}
if ($rMinimal.Count -gt 0 -or $rOldSdk.Count -gt 0) { exit 1 }
exit 0
2. Ubuntu 26.04 Bash Script (gemini4_hydrogen_audit_ubuntu2604.sh)
Human Interactive: bash gemini4_hydrogen_audit_ubuntu2604.sh
Agent Automated: bash gemini4_hydrogen_audit_ubuntu2604.sh –target ./your-repo –auto –json –write-plan
#!/usr/bin/env bash
# ==============================================================================
# Gemini 4 Hydrogen (GA) Migration & Agentic Pre-Flight Audit — Ubuntu 26.04
# Zero third-party dependencies (standard bash, grep, awk, sed, curl)
# Modes:
# Human Interactive: bash gemini4_hydrogen_audit_ubuntu2604.sh [--target ./repo]
# Agent Automated: bash gemini4_hydrogen_audit_ubuntu2604.sh --target ./repo --auto --json
# ==============================================================================
set -euo pipefail
TARGET_DIR="."
AUTO_MODE=0
JSON_MODE=0
PROBE_API=0
WRITE_PLAN=0
print_usage() {
cat <<'USAGE'
Usage: bash gemini4_hydrogen_audit_ubuntu2604.sh [options]
--target <dir> Directory to scan (default: current directory)
--auto Non-interactive mode (no prompts; ideal for CI / AI Agents)
--json Emit machine-readable JSON summary to stdout
--probe Run optional read-only API/Antigravity CLI check if configured
--write-plan Write sanitized migration checklist to .gemini4-migration-plan.json
-h, --help Show this help message
USAGE
}
while [[ $# -gt 0 ]]; do
case "$1" in
--target)
shift
[[ $# -gt 0 ]] || { echo "Error: --target requires a directory" >&2; exit 2; }
TARGET_DIR="$1"
;;
--auto) AUTO_MODE=1 ;;
--json) JSON_MODE=1; AUTO_MODE=1 ;;
--probe) PROBE_API=1 ;;
--write-plan) WRITE_PLAN=1 ;;
-h|--help) print_usage; exit 0 ;;
*) echo "Unknown option: $1" >&2; print_usage >&2; exit 2 ;;
esac
shift
done
[[ -d "$TARGET_DIR" ]] || { echo "Error: Target directory not found: $TARGET_DIR" >&2; exit 2; }
TARGET_ABS="$(cd "$TARGET_DIR" && pwd)"
TARGET_BASE="$(basename "$TARGET_ABS")"
if [[ "$AUTO_MODE" -eq 0 ]]; then
printf '\033[36m=====================================================================\033[0m\n'
printf '\033[1;34m Gemini 4 Hydrogen (GA) Pre-Flight Audit — Ubuntu 26.04 Interactive\033[0m\n'
printf '\033[36m=====================================================================\033[0m\n'
read -r -p "Target project [${TARGET_ABS}] (Press Enter to keep): " input_dir || true
if [[ -n "${input_dir:-}" ]]; then
[[ -d "$input_dir" ]] || { echo "Directory not found: $input_dir" >&2; exit 2; }
TARGET_ABS="$(cd "$input_dir" && pwd)"
TARGET_BASE="$(basename "$TARGET_ABS")"
fi
read -r -p "Run optional live check if GEMINI_API_KEY / agy CLI present? [y/N]: " probe_ans || true
[[ "${probe_ans:-n}" == [Yy]* ]] && PROBE_API=1
read -r -p "Write sanitized migration plan JSON into target folder? [y/N]: " plan_ans || true
[[ "${plan_ans:-n}" == [Yy]* ]] && WRITE_PLAN=1
fi
EXCLUDE_ARGS=(
--exclude-dir=.git --exclude-dir=node_modules --exclude-dir=.venv
--exclude-dir=venv --exclude-dir=__pycache__ --exclude-dir=dist
--exclude-dir=build --exclude-dir=.next --exclude=.gemini4-migration-plan.json
)
INCLUDE_ARGS=(
--include='*.py' --include='*.ts' --include='*.tsx' --include='*.js' --include='*.jsx'
--include='*.mjs' --include='*.go' --include='*.java' --include='*.cs' --include='*.rs'
--include='*.json' --include='*.yaml' --include='*.yml' --include='*.toml' --include='*.env*'
--include='requirements*.txt' --include='go.mod' --include='pyproject.toml'
)
scan_count_and_sample() {
local pattern="$1"
local matches total first_rel sq="'"
matches="$(grep -rnE "${EXCLUDE_ARGS[@]}" "${INCLUDE_ARGS[@]}" -- "$pattern" "$TARGET_ABS" 2>/dev/null | grep -vE '(^|/)\.gemini4-migration-plan\.json:' || true)"
if [[ -z "$matches" ]]; then
echo "0|"
return
fi
total="$(printf '%s\n' "$matches" | wc -l | tr -d ' ')"
first_rel="${matches%%$'\n'*}"
first_rel="${first_rel#"$TARGET_ABS"/}"
first_rel="${first_rel//\"/$sq}"
first_rel="$(printf '%s' "$first_rel" | sed -E 's/:([0-9]+):[[:space:]]*/:\1: /' | cut -c1-84)"
echo "${total}|${first_rel}"
}
r_sampling="$(scan_count_and_sample '["'\'']?(temperature|top_p|topP|top_k|topK)["'\'']?[[:space:]]*[:=]')"
r_minimal="$(scan_count_and_sample 'thinking_?[lL]evel["'\''[:space:]:=]+(MINIMAL|minimal)')"
r_lowcap="$(scan_count_and_sample '["'\'']?max_?[oO]utput_?[tT]okens["'\'']?[[:space:]]*[:=][[:space:]]*([1-9][0-9]{0,3}|16384)([^0-9]|$)')"
r_explicit_cache="$(scan_count_and_sample 'cachedContents|caches\.create|cached_content')"
r_legacy_models="$(scan_count_and_sample 'gemini-(2\.5-pro|3\.8-flash|4-carbon|4-argon)')"
r_token_trap="$(scan_count_and_sample 'total_input_tokens')"
r_old_sdk="$(scan_count_and_sample 'google-generativeai|import google\.generativeai|@google/generative-ai')"
r_live_media="$(scan_count_and_sample 'bidiGenerateContent|aio\.live|IMAGE_GENERATION|response_modalities.*AUDIO|gemini-4-hydrogen.*(IMAGE|AUDIO)')"
C_SAMPLING="${r_sampling%%|*}"; S_SAMPLING="${r_sampling#*|}"
C_MINIMAL="${r_minimal%%|*}"; S_MINIMAL="${r_minimal#*|}"
C_LOWCAP="${r_lowcap%%|*}"; S_LOWCAP="${r_lowcap#*|}"
C_CACHE="${r_explicit_cache%%|*}"; S_CACHE="${r_explicit_cache#*|}"
C_LEGACY="${r_legacy_models%%|*}"; S_LEGACY="${r_legacy_models#*|}"
C_TOKENTRAP="${r_token_trap%%|*}"; S_TOKENTRAP="${r_token_trap#*|}"
C_OLDSDK="${r_old_sdk%%|*}"; S_OLDSDK="${r_old_sdk#*|}"
C_LIVEMEDIA="${r_live_media%%|*}"; S_LIVEMEDIA="${r_live_media#*|}"
TOTAL_ISSUES=$(( C_SAMPLING + C_MINIMAL + C_LOWCAP + C_CACHE + C_LEGACY + C_TOKENTRAP + C_OLDSDK + C_LIVEMEDIA ))
PYTHON_GENAI_VER="not_installed"
if command -v python3 >/dev/null 2>&1; then
PYTHON_GENAI_VER="$(python3 -c 'import importlib.metadata as m; print(m.version("google-genai"))' 2>/dev/null || echo "not_installed")"
fi
AGY_CLI_STATUS="not_found"
if command -v agy >/dev/null 2>&1; then
AGY_CLI_STATUS="$(agy --version 2>/dev/null | head -n 1 || echo "installed")"
fi
API_PROBE_STATUS="skipped"
if [[ "$PROBE_API" -eq 1 ]]; then
if [[ -n "${GEMINI_API_KEY:-}" ]]; then
http_code="$(curl -sS -o /dev/null -w "%{http_code}" --max-time 8 \
-H "x-goog-api-key: ${GEMINI_API_KEY}" \
"https://generativelanguage.googleapis.com/v1beta/models/gemini-4-hydrogen" || echo "000")"
API_PROBE_STATUS="http_${http_code}"
[[ "$http_code" == "200" ]] && API_PROBE_STATUS="ok_http_200"
else
API_PROBE_STATUS="no_GEMINI_API_KEY_in_env"
fi
fi
json_escape() {
printf '%s' "$1" | sed 's/\\/\\\\/g; s/"/\\"/g' | tr -d '\r\n'
}
build_json_payload() {
cat <<JSON
{
"tool": "gemini4-hydrogen-audit",
"os": "Ubuntu 26.04 (Bash)",
"model_target": "gemini-4-hydrogen",
"project_basename": "$(json_escape "$TARGET_BASE")",
"total_findings": ${TOTAL_ISSUES},
"environment": {
"google_genai_python_sdk": "$(json_escape "$PYTHON_GENAI_VER")",
"recommended_min_python_sdk": "2.34.0",
"antigravity_cli": "$(json_escape "$AGY_CLI_STATUS")",
"api_model_metadata_probe": "$(json_escape "$API_PROBE_STATUS")"
},
"checks": [
{"id": "G4H-TRAP-01", "severity": "SILENT_HTTP_200", "title": "Ignored sampling overrides (temperature/top_p/top_k)", "count": ${C_SAMPLING}, "sample": "$(json_escape "$S_SAMPLING")"},
{"id": "G4H-TRAP-02", "severity": "LOUD_ERROR", "title": "Unsupported minimal thinking_level (defaults to high on Hydrogen)", "count": ${C_MINIMAL}, "sample": "$(json_escape "$S_MINIMAL")"},
{"id": "G4H-TRAP-03", "severity": "SILENT_TRUNCATION", "title": "Low max_output_tokens <=16384 starves thinking + output budget", "count": ${C_LOWCAP}, "sample": "$(json_escape "$S_LOWCAP")"},
{"id": "G4H-TRAP-04", "severity": "UNSUPPORTED_FEATURE", "title": "Explicit caching calls (use implicit >=4096 token cache on Hydrogen)", "count": ${C_CACHE}, "sample": "$(json_escape "$S_CACHE")"},
{"id": "G4H-TRAP-05", "severity": "COST_OR_DEPRECATION", "title": "Legacy Gemini model IDs facing Dec 1 / Jan 1 price or routing shifts", "count": ${C_LEGACY}, "sample": "$(json_escape "$S_LEGACY")"},
{"id": "G4H-TRAP-06", "severity": "COMPACTION_BUG", "title": "total_input_tokens used in Long Decode multi-hop accounting", "count": ${C_TOKENTRAP}, "sample": "$(json_escape "$S_TOKENTRAP")"},
{"id": "G4H-TRAP-07", "severity": "RETIRED_SDK", "title": "Retired google-generativeai / @google/generative-ai package", "count": ${C_OLDSDK}, "sample": "$(json_escape "$S_OLDSDK")"},
{"id": "G4H-TRAP-08", "severity": "UNSUPPORTED_MODALITY", "title": "Live API / native image or audio generation markers", "count": ${C_LIVEMEDIA}, "sample": "$(json_escape "$S_LIVEMEDIA")"}
]
}
JSON
}
if [[ "$WRITE_PLAN" -eq 1 ]]; then
build_json_payload > "${TARGET_ABS}/.gemini4-migration-plan.json"
fi
if [[ "$JSON_MODE" -eq 1 ]]; then
build_json_payload
else
printf '\nTarget folder: %s Findings: %d\n' "$TARGET_BASE" "$TOTAL_ISSUES"
printf 'Python google-genai SDK: %s (min >= 2.34.0 for Long Decode client continuation)\n' "$PYTHON_GENAI_VER"
printf 'Antigravity CLI (agy): %s API Metadata Probe: %s\n' "$AGY_CLI_STATUS" "$API_PROBE_STATUS"
echo "---------------------------------------------------------------------"
printf "%-13s | %-19s | %5s | %s\n" "Check ID" "Behavior" "Hits" "First Relative Hit"
echo "---------------------------------------------------------------------"
printf "%-13s | %-19s | %5d | %s\n" "G4H-TRAP-01" "SILENT_HTTP_200" "$C_SAMPLING" "${S_SAMPLING:--}"
printf "%-13s | %-19s | %5d | %s\n" "G4H-TRAP-02" "LOUD_ERROR" "$C_MINIMAL" "${S_MINIMAL:--}"
printf "%-13s | %-19s | %5d | %s\n" "G4H-TRAP-03" "SILENT_TRUNCATION" "$C_LOWCAP" "${S_LOWCAP:--}"
printf "%-13s | %-19s | %5d | %s\n" "G4H-TRAP-04" "UNSUPPORTED_FEATURE" "$C_CACHE" "${S_CACHE:--}"
printf "%-13s | %-19s | %5d | %s\n" "G4H-TRAP-05" "COST_DEPRECATION" "$C_LEGACY" "${S_LEGACY:--}"
printf "%-13s | %-19s | %5d | %s\n" "G4H-TRAP-06" "COMPACTION_BUG" "$C_TOKENTRAP" "${S_TOKENTRAP:--}"
printf "%-13s | %-19s | %5d | %s\n" "G4H-TRAP-07" "RETIRED_SDK" "$C_OLDSDK" "${S_OLDSDK:--}"
printf "%-13s | %-19s | %5d | %s\n" "G4H-TRAP-08" "UNSUPPORTED_MOD" "$C_LIVEMEDIA" "${S_LIVEMEDIA:--}"
echo "---------------------------------------------------------------------"
if [[ "$WRITE_PLAN" -eq 1 ]]; then
echo "Saved migration plan: ${TARGET_BASE}/.gemini4-migration-plan.json"
fi
fi
if [[ "$C_MINIMAL" -gt 0 || "$C_OLDSDK" -gt 0 ]]; then
exit 1
fi
exit 0
3. macOS 27 Zsh Script (gemini4_hydrogen_audit_macos27.zsh)
Human Interactive: zsh gemini4_hydrogen_audit_macos27.zsh
Agent Automated: zsh gemini4_hydrogen_audit_macos27.zsh –target ./your-repo –auto –json –write-plan
#!/usr/bin/env zsh
# ==============================================================================
# Gemini 4 Hydrogen (GA) Migration & Agentic Pre-Flight Audit — macOS 27 (Zsh)
# Zero third-party dependencies (macOS 27 built-in zsh, grep, awk, sed, curl)
# Modes:
# Human Interactive: zsh gemini4_hydrogen_audit_macos27.zsh [--target ./repo]
# Agent Automated: zsh gemini4_hydrogen_audit_macos27.zsh --target ./repo --auto --json
# ==============================================================================
emulate -L zsh
setopt PIPE_FAIL NO_UNSET
TARGET_DIR="."
AUTO_MODE=0
JSON_MODE=0
PROBE_API=0
WRITE_PLAN=0
print_usage() {
cat <<'USAGE'
Usage: zsh gemini4_hydrogen_audit_macos27.zsh [options]
--target <dir> Directory to scan (default: current directory)
--auto Non-interactive mode (no prompts; ideal for CI / AI Agents)
--json Emit machine-readable JSON summary to stdout
--probe Run optional read-only API/Antigravity CLI check if configured
--write-plan Write sanitized migration checklist to .gemini4-migration-plan.json
-h, --help Show this help message
USAGE
}
while (( $# > 0 )); do
case "$1" in
--target)
shift
[[ $# -gt 0 ]] || { echo "Error: --target requires a directory" >&2; exit 2; }
TARGET_DIR="$1"
;;
--auto) AUTO_MODE=1 ;;
--json) JSON_MODE=1; AUTO_MODE=1 ;;
--probe) PROBE_API=1 ;;
--write-plan) WRITE_PLAN=1 ;;
-h|--help) print_usage; exit 0 ;;
*) echo "Unknown option: $1" >&2; print_usage >&2; exit 2 ;;
esac
shift
done
if [[ ! -d "$TARGET_DIR" ]]; then
echo "Error: Target directory does not exist: $TARGET_DIR" >&2
exit 2
fi
TARGET_ABS="$(cd "$TARGET_DIR" && pwd)"
if (( AUTO_MODE == 0 )); then
print -P "%F{cyan}=====================================================================%f"
print -P "%B%F{blue} Gemini 4 Hydrogen (GA) Pre-Flight Audit — macOS 27 Interactive%f%b"
print -P "%F{cyan}=====================================================================%f"
printf "Target project [%s] (Press Enter to keep): " "$TARGET_ABS"
read -r input_dir || true
if [[ -n "${input_dir:-}" ]]; then
[[ -d "$input_dir" ]] || { echo "Directory not found: $input_dir" >&2; exit 2; }
TARGET_ABS="$(cd "$input_dir" && pwd)"
fi
printf "Run optional live check if GEMINI_API_KEY / agy CLI present? [y/N]: "
read -r probe_ans || true
[[ "${probe_ans:-n}" == [Yy]* ]] && PROBE_API=1
printf "Write sanitized migration plan JSON into target folder? [y/N]: "
read -r plan_ans || true
[[ "${plan_ans:-n}" == [Yy]* ]] && WRITE_PLAN=1
fi
typeset -a EXCLUDE_ARGS
EXCLUDE_ARGS=(
"--exclude-dir=.git"
"--exclude-dir=node_modules"
"--exclude-dir=.venv"
"--exclude-dir=venv"
"--exclude-dir=__pycache__"
"--exclude-dir=dist"
"--exclude-dir=build"
"--exclude-dir=.next"
"--exclude=.gemini4-migration-plan.json"
)
typeset -a INCLUDE_ARGS
INCLUDE_ARGS=(
"--include=*.py" "--include=*.ts" "--include=*.tsx" "--include=*.js" "--include=*.jsx"
"--include=*.mjs" "--include=*.go" "--include=*.java" "--include=*.cs" "--include=*.rs"
"--include=*.json" "--include=*.yaml" "--include=*.yml" "--include=*.toml" "--include=*.env*"
"--include=requirements*.txt" "--include=go.mod" "--include=pyproject.toml"
)
scan_count_and_sample() {
local pattern="$1"
local matches total first_rel sq="'"
matches="$(grep -rnE "${EXCLUDE_ARGS[@]}" "${INCLUDE_ARGS[@]}" -- "$pattern" "$TARGET_ABS" 2>/dev/null | grep -vE '(^|/)\.gemini4-migration-plan\.json:' || true)"
if [[ -z "$matches" ]]; then
echo "0|"
return
fi
total="$(printf '%s\n' "$matches" | wc -l | tr -d ' ')"
first_rel="${matches%%$'\n'*}"
# Strip prefix paths & usernames to keep output leak-free
first_rel="${first_rel#$TARGET_ABS/}"
first_rel="${first_rel//\"/$sq}"
first_rel="$(printf '%s' "$first_rel" | sed -E 's/:([0-9]+):[[:space:]]*/:\1: /' | cut -c1-84)"
echo "${total}|${first_rel}"
}
r_sampling="$(scan_count_and_sample '["'\'']?(temperature|top_p|topP|top_k|topK)["'\'']?[[:space:]]*[:=]')"
r_minimal="$(scan_count_and_sample 'thinking_?[lL]evel["'\''[:space:]:=]+(MINIMAL|minimal)')"
r_lowcap="$(scan_count_and_sample '["'\'']?max_?[oO]utput_?[tT]okens["'\'']?[[:space:]]*[:=][[:space:]]*([1-9][0-9]{0,3}|16384)([^0-9]|$)')"
r_explicit_cache="$(scan_count_and_sample 'cachedContents|caches\.create|cached_content')"
r_legacy_models="$(scan_count_and_sample 'gemini-(2\.5-pro|3\.8-flash|4-carbon|4-argon)')"
r_token_trap="$(scan_count_and_sample 'total_input_tokens')"
r_old_sdk="$(scan_count_and_sample 'google-generativeai|import google\.generativeai|@google/generative-ai')"
r_live_media="$(scan_count_and_sample 'bidiGenerateContent|aio\.live|IMAGE_GENERATION|response_modalities.*AUDIO|gemini-4-hydrogen.*(IMAGE|AUDIO)')"
split_metric() {
local val="$1"
echo "${val%%|*}"
}
split_sample() {
local val="$1"
echo "${val#*|}"
}
C_SAMPLING=$(split_metric "$r_sampling"); S_SAMPLING=$(split_sample "$r_sampling")
C_MINIMAL=$(split_metric "$r_minimal"); S_MINIMAL=$(split_sample "$r_minimal")
C_LOWCAP=$(split_metric "$r_lowcap"); S_LOWCAP=$(split_sample "$r_lowcap")
C_CACHE=$(split_metric "$r_explicit_cache"); S_CACHE=$(split_sample "$r_explicit_cache")
C_LEGACY=$(split_metric "$r_legacy_models"); S_LEGACY=$(split_sample "$r_legacy_models")
C_TOKENTRAP=$(split_metric "$r_token_trap"); S_TOKENTRAP=$(split_sample "$r_token_trap")
C_OLDSDK=$(split_metric "$r_old_sdk"); S_OLDSDK=$(split_sample "$r_old_sdk")
C_LIVEMEDIA=$(split_metric "$r_live_media"); S_LIVEMEDIA=$(split_sample "$r_live_media")
TOTAL_ISSUES=$(( C_SAMPLING + C_MINIMAL + C_LOWCAP + C_CACHE + C_LEGACY + C_TOKENTRAP + C_OLDSDK + C_LIVEMEDIA ))
# Environment checks (zero external dependencies)
PYTHON_GENAI_VER="not_installed"
if command -v python3 >/dev/null 2>&1; then
PYTHON_GENAI_VER="$(python3 -c 'import importlib.metadata as m; print(m.version("google-genai"))' 2>/dev/null || echo "not_installed")"
fi
AGY_CLI_STATUS="not_found"
if command -v agy >/dev/null 2>&1; then
AGY_CLI_STATUS="$(agy --version 2>/dev/null | head -n 1 || echo "installed")"
fi
API_PROBE_STATUS="skipped"
if (( PROBE_API == 1 )); then
if [[ -n "${GEMINI_API_KEY:-}" ]]; then
http_code="$(curl -sS -o /dev/null -w "%{http_code}" --max-time 8 \
-H "x-goog-api-key: ${GEMINI_API_KEY}" \
"https://generativelanguage.googleapis.com/v1beta/models/gemini-4-hydrogen" || echo "000")"
if [[ "$http_code" == "200" ]]; then
API_PROBE_STATUS="ok_http_200"
else
API_PROBE_STATUS="http_${http_code}"
fi
else
API_PROBE_STATUS="no_GEMINI_API_KEY_in_env"
fi
fi
json_escape() {
printf '%s' "$1" | sed 's/\\/\\\\/g; s/"/\\"/g' | tr -d '\r\n'
}
build_json_payload() {
cat <<JSON
{
"tool": "gemini4-hydrogen-audit",
"os": "macOS 27 (Zsh)",
"model_target": "gemini-4-hydrogen",
"project_basename": "$(json_escape "${TARGET_ABS:t}")",
"total_findings": ${TOTAL_ISSUES},
"environment": {
"google_genai_python_sdk": "$(json_escape "$PYTHON_GENAI_VER")",
"recommended_min_python_sdk": "2.34.0",
"antigravity_cli": "$(json_escape "$AGY_CLI_STATUS")",
"api_model_metadata_probe": "$(json_escape "$API_PROBE_STATUS")"
},
"checks": [
{"id": "G4H-TRAP-01", "severity": "SILENT_HTTP_200", "title": "Ignored sampling overrides (temperature/top_p/top_k)", "count": ${C_SAMPLING}, "sample": "$(json_escape "$S_SAMPLING")"},
{"id": "G4H-TRAP-02", "severity": "LOUD_ERROR", "title": "Unsupported minimal thinking_level (defaults to high on Hydrogen)", "count": ${C_MINIMAL}, "sample": "$(json_escape "$S_MINIMAL")"},
{"id": "G4H-TRAP-03", "severity": "SILENT_TRUNCATION", "title": "Low max_output_tokens <=16384 starves thinking + output budget", "count": ${C_LOWCAP}, "sample": "$(json_escape "$S_LOWCAP")"},
{"id": "G4H-TRAP-04", "severity": "UNSUPPORTED_FEATURE", "title": "Explicit caching calls (use implicit >=4096 token cache on Hydrogen)", "count": ${C_CACHE}, "sample": "$(json_escape "$S_CACHE")"},
{"id": "G4H-TRAP-05", "severity": "COST_OR_DEPRECATION", "title": "Legacy Gemini model IDs facing Dec 1 / Jan 1 price or routing shifts", "count": ${C_LEGACY}, "sample": "$(json_escape "$S_LEGACY")"},
{"id": "G4H-TRAP-06", "severity": "COMPACTION_BUG", "title": "total_input_tokens used in Long Decode multi-hop accounting", "count": ${C_TOKENTRAP}, "sample": "$(json_escape "$S_TOKENTRAP")"},
{"id": "G4H-TRAP-07", "severity": "RETIRED_SDK", "title": "Retired google-generativeai / @google/generative-ai package", "count": ${C_OLDSDK}, "sample": "$(json_escape "$S_OLDSDK")"},
{"id": "G4H-TRAP-08", "severity": "UNSUPPORTED_MODALITY", "title": "Live API / native image or audio generation markers", "count": ${C_LIVEMEDIA}, "sample": "$(json_escape "$S_LIVEMEDIA")"}
]
}
JSON
}
if (( WRITE_PLAN == 1 )); then
build_json_payload > "${TARGET_ABS}/.gemini4-migration-plan.json"
fi
if (( JSON_MODE == 1 )); then
build_json_payload
else
print ""
print -P "%BTarget folder:%b ${TARGET_ABS:t} %BFindings:%b ${TOTAL_ISSUES}"
print -P "%BPython google-genai SDK:%b ${PYTHON_GENAI_VER} (min >= 2.34.0 for Long Decode client continuation)"
print -P "%BAntigravity CLI (agy):%b ${AGY_CLI_STATUS} %BAPI Metadata Probe:%b ${API_PROBE_STATUS}"
printf "---------------------------------------------------------------------\n"
printf "%-13s | %-19s | %5s | %s\n" "Check ID" "Behavior" "Hits" "First Relative Hit"
printf "---------------------------------------------------------------------\n"
printf "%-13s | %-19s | %5d | %s\n" "G4H-TRAP-01" "SILENT_HTTP_200" "$C_SAMPLING" "${S_SAMPLING:--}"
printf "%-13s | %-19s | %5d | %s\n" "G4H-TRAP-02" "LOUD_ERROR" "$C_MINIMAL" "${S_MINIMAL:--}"
printf "%-13s | %-19s | %5d | %s\n" "G4H-TRAP-03" "SILENT_TRUNCATION" "$C_LOWCAP" "${S_LOWCAP:--}"
printf "%-13s | %-19s | %5d | %s\n" "G4H-TRAP-04" "UNSUPPORTED_FEATURE" "$C_CACHE" "${S_CACHE:--}"
printf "%-13s | %-19s | %5d | %s\n" "G4H-TRAP-05" "COST_DEPRECATION" "$C_LEGACY" "${S_LEGACY:--}"
printf "%-13s | %-19s | %5d | %s\n" "G4H-TRAP-06" "COMPACTION_BUG" "$C_TOKENTRAP" "${S_TOKENTRAP:--}"
printf "%-13s | %-19s | %5d | %s\n" "G4H-TRAP-07" "RETIRED_SDK" "$C_OLDSDK" "${S_OLDSDK:--}"
printf "%-13s | %-19s | %5d | %s\n" "G4H-TRAP-08" "UNSUPPORTED_MOD" "$C_LIVEMEDIA" "${S_LIVEMEDIA:--}"
printf "---------------------------------------------------------------------\n"
if (( WRITE_PLAN == 1 )); then
print -P "%F{green}Saved migration plan:%f ${TARGET_ABS:t}/.gemini4-migration-plan.json"
fi
fi
if (( C_MINIMAL > 0 || C_OLDSDK > 0 )); then
exit 1
fi
exit 0
6. Verified Benchmarks & The 59% Cost-Paradox Unpacked
At first glance, seeing Hydrogen priced at $1.50 / $7.50 next to 3.8 Flash’s $0.75 / $3.75 triggers understandable sticker shock. Why pay double per token?
Because total invoice spend = price per token × turns needed to succeed—and independent testing by Artificial Analysis (v5.0.1) alongside DeepMind’s official Model Card flips the math completely:

Figure 11: Original analysis visual detailing benchmark jumps (Terminal-Bench 4.1 from 18.2% to 57.0%) and why 2x token rates yield 59% lower real task spend.
Key verified numbers worth bookmarking:
- AA Intelligence Index v5.0.1: Hydrogen scores 51 at default
highand jumps to 54 atxhigh(comparable median 41)—meaning Google's Flash-speed model literally outscores frontier Gemini 4 Argon (50) and demolishes 3.8 Flash's 31! - The $7.77 vs. $3.16 Reality Check: Running Artificial Analysis's full end-to-end suite costs $7.77 on 3.8 Flash due to repeated wrong turns and retries, versus just $3.16 on Hydrogen (xhigh)—a 59% real cost drop—at a blazing 188 tok/s output speed (up from ~111 tok/s on 3.8 Flash).
Figure 12: Live capture from artificialanalysis.ai/models/gemini-4-hydrogen showing Intelligence Index 54, 188 tok/s throughput, and total evaluation spend.
DeepMind’s official Model Card confirms massive gains across real engineering harnesses as well:
Terminal-Bench 4.1: 57.0% (crushing 3.8 Flash's 18.2% by +38.8 points, nearing Claude Sonnet 5.5's 63.9%);SWE-sweep(Multi-file repo tasks): 13.5% vs. Sonnet 5.5 (3.1%) and GPT-6.1 Terra (5.8%);Agents' Last Exam v1.1/OSWorld-2.1/Vending-Bench 2: 71.6%, 77.6% GUI mastery, and $14,549 long-horizon planning score—plus #1 onVals Tax Agent Bench(52.3%), tied #1 onVals Legal Research Bench(55.8%), and #5 on Agent Arena.
Figure 13: Real web capture corroborating Gemini 4 Hydrogen’s jump across coding, agentic tool execution, and real-world workflows.
One UX nuance to budget for: while Hydrogen streams at ~188 tok/s once talking, enabling maximum xhigh reasoning introduces a measured 40.55s TTFT in AA tests (around 13.7 min per hard evaluation task). Reserve high/xhigh for hard coding and async pipelines; explicitly specify low or medium for sub-second user chat interfaces!
7. Frequently Asked Engineering Questions (Q&A)
Q1: Since Hydrogen offers a Free Tier, can I deploy staging or lightweight production bots onto free API keys?
Keep proprietary codebases and production SLAs off Free Tier keys. Free keys carry tight rate caps AND Google’s Free Tier terms permit submitted content to be used to improve Google products. Upgrade the billing project to Paid Tier whenever privacy or throughput guarantees matter.
Q2: Should existing Gemini 4 Argon or Carbon teams switch everything to Hydrogen?
Shift ~70%–80% of high-frequency agentic execution, file search, formatting, and test verification to Hydrogen—either directly or via Antigravity Orchestrator (Carbon/Argon). With Carbon and Argon doubling to $4.00 / $20.00 on December 1, reserving flagships strictly for top-level orchestration is essential for healthy unit economics.
Q3: How do stateless generateContent tool loops stay valid without server-side Conversations?
Return every thought_signature field emitted in model responses back verbatim inside your conversation history array. Note carefully: on parallel tool calls within a single turn, only the first functionCall carries the signature—never copy or fabricate signatures onto sibling parallel calls.
Q4: I enabled background=True yet my generation still stopped at 64K tokens—why?
Unless you explicitly override max_output_tokens above 65536 alongside store=True, the server applies the standard 64K ceiling even on asynchronous jobs. Pass all three flags together on interactions.create.
Q5: Does Gemini 4 Hydrogen support Live API voice streaming or native image/audio generation?
No. Live API (bidiGenerateContent), native image output, and native audio generation are currently unsupported on gemini-4-hydrogen. Keep those specialized endpoints routed to dedicated multimodal models in your gateway.
Q6: Do I need code changes to enable the 95% Implicit Caching discount?
No extra endpoints are required—and explicit cachedContents is unsupported. Simply keep at least 4,096 byte-identical tokens (system prompt, architectural docs, tool schemas) pinned at the top of consecutive requests on the same project to pay $0.075 / 1M automatically.
Q7: Is Antigravity’s Extra tier identical to thinking_level=“xhigh” in the API?
Yes—Extra maps directly to xhigh (or agy –model gemini-4-hydrogen-xhigh). Save it for tough architectural diagnostics and keep latency-sensitive UX loops on low or medium.
Conclusion
The November 2026 arrival of Gemini 4 Hydrogen marks the end of compromising between fragile bargain models and sluggish, pricey flagships. Before December 1 triggers forced 2.5-pro routing and 2x price jumps on Carbon and Argon—and January 1 eliminates 3.8 Flash’s pricing gap altogether—run the cross-platform audit script above, eliminate the six silent HTTP 200 pitfalls cleanly, and make Hydrogen the fast, accurate workhorse of your production agent stack.