<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Aniket Agrawal on Medium]]></title>
        <description><![CDATA[Stories by Aniket Agrawal on Medium]]></description>
        <link>https://medium.com/@aniketagrawal_14703?source=rss-13a446e68524------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*tjhCnxewVSAkF2wMDmCobQ.jpeg</url>
            <title>Stories by Aniket Agrawal on Medium</title>
            <link>https://medium.com/@aniketagrawal_14703?source=rss-13a446e68524------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 04:55:19 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@aniketagrawal_14703/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[The Periodic Table of Gemini 4: Routing Hydrogen, Carbon & Argon on Google Cloud]]></title>
            <link>https://medium.com/google-cloud/the-periodic-table-of-gemini-4-routing-hydrogen-carbon-argon-on-google-cloud-d544d0a65e9a?source=rss-13a446e68524------2</link>
            <guid isPermaLink="false">https://medium.com/p/d544d0a65e9a</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[google-cloud-platform]]></category>
            <category><![CDATA[gemini]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[llm]]></category>
            <dc:creator><![CDATA[Aniket Agrawal]]></dc:creator>
            <pubDate>Tue, 17 Nov 2026 02:34:43 GMT</pubDate>
            <atom:updated>2026-11-17T13:54:38.397Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Cut agent cost up to 13.7× across 255+ live Google Cloud calls: thinking depth, 165 tok/s streaming, 95% caching, BigQuery &amp; Cloud Run.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*hVyW15PIzInJb2Lm.gif" /><figcaption>Figure 1: The Periodic Table of Gemini 4 on Google Cloud’s Gemini Enterprise Agent Platform — live pricing, thinking profiles, and production strengths across Hydrogen, Carbon, and Argon.</figcaption></figure><p>Open Model Garden inside Google Cloud’s <strong>Gemini Enterprise Agent Platform</strong> and you won’t see “small, medium, and large” — you’ll see a true <strong>Periodic Table of Gemini 4</strong>. Across <a href="https://docs.cloud.google.com/gemini-enterprise-agent-platform/models/gemini/4-argon"><strong>Gemini 4 Argon</strong></a> (gemini-4-argon, Oct 13, 2026: 12-month GA lifecycle and single-region data residency in europe-west2 and asia-southeast1), <a href="https://docs.cloud.google.com/gemini-enterprise-agent-platform/models/gemini/4-carbon"><strong>Gemini 4 Carbon</strong></a> (gemini-4-carbon, Nov 10, 2026: frontier deep reasoning and native Office ingestion), and <a href="https://docs.cloud.google.com/gemini-enterprise-agent-platform/models/gemini/4-hydrogen"><strong>Gemini 4 Hydrogen</strong></a> (gemini-4-hydrogen, Nov 12, 2026: 165 tok/s speed, XHIGH deep verification, 65K output, native Office MIME, and 95% implicit caching at 62.5% lower list price), each element anchors a distinct enterprise workload lane.</p><blockquote><em>Routing each request to the right element and thinking depth delivered a 13.7× cost spread ($0.1006 on Hydrogen LOW vs. $1.3806 on Carbon HIGH) while achieving 100% accuracy across 8 deterministic tasks and 15/15 responseSchema conformance — live on Cloud Run, Cloud Storage, and BigQuery.</em></blockquote><p>To translate release specs into reusable production patterns, I built an Apache-2.0 reference implementation (<a href="https://github.com/aniketagrawal2012/google-cloud-gemini4-periodic-lab">google-cloud-gemini4-periodic-lab</a> — FastAPI Cloud Run gateway, <a href="https://adk.dev/">Agent Development Kit (ADK)</a> callback, BigQuery FinOps SQL views, and 14/14 passing pytest tests) and executed <strong>255+ live Google Cloud calls</strong> across five regions, Cloud Storage, <a href="https://docs.cloud.google.com/gemini-enterprise-agent-platform/models/grounding/grounding-with-google-search">Grounding with Google Search</a>, BigQuery, and Cloud Run.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*_IhfFroY-wKoI0Dk.gif" /><figcaption>Figure 2: End-to-end Google Cloud verification — Model Garden, Cloud Storage binary .xlsx/.docx ingestion, BigQuery Studio FinOps SQL, and live Cloud Run gen2 routing headers.</figcaption></figure><h3>5 Production Architecture Patterns at a Glance</h3><ul><li><strong>1. Task-Matched Thinking Depth (13.7× Cost Swing):</strong> Keep LOW on Argon/Carbon for crisp 5.0s zero-thought direct tasks (SQL, classification, security checks), run Carbon:MEDIUM (1,419.9 avg thoughts, $0.248 list / $0.124 Nov promo) or Argon:HIGH for multi-step reasoning, and use Hydrogen:LOW (1,549 avg thoughts, 100% in 11.4s for $0.101) as your everyday reasoning workhorse.</li><li><strong>2. Interactive Streaming vs. Async Interactions API:</strong> Hydrogen sustains <strong>154–166 tok/s</strong> for real-time UX; pair deep-verification Hydrogen:XHIGH (48,841 thoughts / 303.6s) and buffered completions with timeoutSeconds: 360 on Cloud Run or background=True in the <a href="https://docs.cloud.google.com/gemini-enterprise-agent-platform/models/capabilities/interactions">Interactions API</a>.</li><li><strong>3. Byte-0 Prefix Hygiene for 95% Implicit Caching:</strong> Above 4,096 tokens, Hydrogen snapped onto 16,384 cached tokens (84.62%, cutting turn cost 76.6% from $0.0306 to $0.0072). Keeping dynamic headers in trailing turns saves <strong>$64.06 (-81.3%) per 1,000 turns</strong> on 50K-context agents.</li><li><strong>4. Native Cloud Storage Office Pipelines &amp; Strict JSON Determinism:</strong> Hydrogen and Carbon natively reconcile binary .xlsx and .docx directly via inline bytes or gs:// URIs (from $0.00269), while strict responseSchema contracts achieve 100% (15/15) operational repeatability across all three elements.</li><li><strong>5. Five-Location Residency &amp; Single-Service Cloud Run Router:</strong> Serve all three elements across global, us, and eu multi-regions via unified aiplatform.googleapis.com, reserve europe-west2 and asia-southeast1 single-region endpoints for Argon, track unit economics live in BigQuery, and expose /health cleanly on Cloud Run.</li></ul><h3>Portfolio Blueprint: Pricing, Thinking Tiers &amp; Output Caps</h3><p>Cross-checking <a href="https://cloud.google.com/model-garden/pricing">Agent Platform &amp; Model Garden Pricing</a>, <a href="https://docs.cloud.google.com/gemini-enterprise-agent-platform/models/thinking">Gemini Thinking</a>, <a href="https://docs.cloud.google.com/gemini-enterprise-agent-platform/models/context-cache/context-cache-overview">Implicit Caching</a>, and <a href="https://docs.cloud.google.com/gemini-enterprise-agent-platform/models/model-versions">Lifecycle Schedules</a> reveals the core architectural trade-offs (* = model default; thinking bills at the output rate):</p><pre>ELEMENT    SLA / LAUNCH       $/1M IN/CAC/OUT*    THINKING        CAP<br>---------  -----------------  ------------------  --------------  ---<br>Hydrogen   Nov 12 (45d)       $1.50/$0.075/$7.50  LO/MD/HI*/XH    65K<br>Carbon     Nov 10 (Frontier)  $4.00/$0.200/$20.0  LO/MD*/HI       32K<br>Argon      Oct 13 (12-mo GA)  $4.00/$0.200/$20.0  LO/MD*/HI       32K<br>3.8 Flash  Baseline ref       $1.50/$0.150/$7.50  MN/LO/MD/HI     65K<br>---------------------------------------------------------------------<br>* Nov 2026 50% promo on Argon &amp; Carbon thru Nov 30 ($2/$0.10/$10).<br>* Effective Nov 13: &gt;32K completions bill even on client timeout.</pre><p>Notice two immediate FinOps wins: Gemini 4 lifts the implicit cache discount to <strong>95%</strong> ($0.075/1M on Hydrogen — half the cached rate of Gemini 3.8 Flash), and our gateway invokes the v1beta1 endpoint directly with typed reasoning configs across all four levels (LOW, MEDIUM, HIGH, and Hydrogen’s exclusive XHIGH).</p><h3>Atomic Logic: Why Proton Count Isn’t Model Rank (It’s Chemical Archetype)</h3><p>One question builders ask immediately: <strong>do atomic numbers (protons and electrons) predict model rank?</strong> Not linearly — Argon carries 18 protons and 18 electrons (3s² 3p⁶ noble-gas shell), Carbon carries 6 (4 valence bonds), and Hydrogen carries 1 (1s¹), yet Carbon is the flagship frontier reasoner. Just like real chemistry, the Periodic Table of Gemini 4 encodes <strong>functional archetype rather than proton weight</strong>: Hydrogen (Z=1) sprints light and reactive (165 tok/s, lowest base cost, bursts to XHIGH); Carbon (Z=6) forms dense four-bond covalent structures (frontier precision at MEDIUM); and Argon (Z=18) forms an inert noble-gas shield for mission-critical 12-month GA and single-region compliance.</p><blockquote><em>One-proton Hydrogen sprints light and bright — 165 tokens, ready for XHIGH flight.<br>Six-proton Carbon locks deep in its core — frontier at MEDIUM, never paying for more.<br>Eighteen-proton Argon, a noble-gas shield — London to Singapore, twelve-month GA yield.<br>Don’t sort by the protons inside of the frame — route by the workload, and 13.7× is the game.</em></blockquote><h3>1. Workload-Matched Thinking Depth &amp; the 13.7× Pareto Frontier</h3><p>To calibrate how thinkingLevel impacts accuracy, latency, and spend (<strong>Experiment 2: 88 live calls</strong>), I evaluated deterministic Python-graded tasks spanning Bayesian inference (T1), Sprague-Grundy game theory (T2), Python asyncio + Cloud Spanner concurrency review (T3), BigQuery temporal deduplication (T4), a 6-service multi-region placement CSP (T5), a 16-step bitwise state machine (T6), ERP prompt-injection defense (T7), and a FinOps FX/CUD waterfall (T8).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*1WH7hjhfXjgXUq2r.png" /><figcaption>Figure 3: Production operating envelopes across 88 live calls — all three Gemini 4 elements hit 100% (8/8) in their reasoning lanes, spanning a 13.7× cost range ($0.101 to $1.381).</figcaption></figure><p>Every element achieved <strong>100% (8/8)</strong> when paired to its intended tier, while exposing two complementary architectural patterns:</p><pre>MODEL            LANE          OK   LAT     THOUGHTS  LIST    PROMO<br>---------------  ------------  ---  ------  --------  ------- -------<br>4-argon          LOW (Direct)  Dir*   5.0s       0.0  $0.0209 $0.0105<br>4-carbon         LOW (Direct)  Dir*  10.2s       0.0  $0.0217 $0.0109<br>4-hydrogen       LOW* (CoT)    8/8   11.4s   1,549.0  $0.1006 $0.1006<br>4-hydrogen       HIGH          8/8   18.2s   2,608.8  $0.1643 $0.1643<br>4-carbon         MEDIUM*       8/8   27.5s   1,419.9  $0.2478 $0.1239<br>4-argon          HIGH          8/8   38.8s   2,678.2  $0.4528 $0.2264<br>4-hydrogen       XHIGH         8/8   77.6s  11,984.0  $0.7275 $0.7275<br>4-carbon         HIGH          8/8  101.9s   8,487.6  $1.3806 $0.6903<br>---------------------------------------------------------------------<br>* Direct LOW: 0 thoughts; 100% on direct SQL, security &amp; audit tasks.</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*dBRQrbMVu8IwqVjk.png" /><figcaption>Figure 4: Thinking-to-output multipliers (Panel A) and Global List vs. Nov-2026 50% Promo spend (Panel B). Reasoning efficiency often outweighs raw per-token rates.</figcaption></figure><ul><li><strong>Keep LOW on Argon/Carbon for Zero-Thought Direct Workflows:</strong> Both models execute LOW with 0.0 internal thoughts — ideal for classification, summarization, SQL extraction, and prompt-injection checks at 5.0s and $0.0105 promo on Argon. Route multi-step math or optimization to their default MEDIUM/HIGH lanes.</li><li><strong>Reserve Carbon:MEDIUM for Frontier Efficiency:</strong> Carbon’s default MEDIUM solved 8/8 using just <strong>1,419.9 avg thoughts</strong> — costing <strong>$0.2478 list / $0.1239 promo</strong> (2.9×–5.9× more economical and 2.8× faster than escalating Hydrogen to XHIGH).</li><li><strong>Use </strong><strong>Hydrogen:LOW Interactive &amp; </strong><strong>XHIGH for Deep Offline Audits:</strong> Hydrogen keeps CoT active at LOW (8/8 for $0.1006) and scales to XHIGH (peaking at 47,089 verification thoughts on concurrency review T3) for high-stakes async audits.</li></ul><h3>2. Streaming Velocity &amp; Async Cloud Run / Interactions Patterns</h3><p>Streaming the exact same Cloud Spanner TrueTime rate-limiter synthesis prompt via streamGenerateContent?alt=sse with includeThoughts=true (<strong>Experiment 3: 10 live SSE streams</strong>) revealed clear latency design rules:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Naurmq9jXPbZqM75.gif" /><figcaption>Figure 5: Live SSE phase replay (Experiment 3, all 10 streams HTTP 200). Hydrogen delivers 154–166 tok/s visible decode velocity (Panel B), while deep-verification tiers pair best with async execution (Panel A).</figcaption></figure><ul><li><strong>Hydrogen Leads Live Streaming UX (154–166 tok/s):</strong> Across steady-state decoding, Hydrogen sustained <strong>154.3–165.6 visible tokens/sec</strong> — over 2× faster than Carbon (82.2-88.5 tok/s) and Argon (53.0-82.0 tok/s).</li><li><strong>Configure Generous Timeouts or </strong><strong>background=True for Deep Reasoning:</strong> Hydrogen:XHIGH spent 303.55s verifying 48,841 internal thoughts before emitting 932 visible tokens ($0.3735), Carbon:HIGH invested 265.10s ($0.3539), and Carbon:MEDIUM buffered 86.33s before bursting 674 tokens in 0.20s. Under the Nov 13, 2026 &gt;32K completion billing rule, set Cloud Run timeoutSeconds: 360, stream thought heartbeats, or run asynchronously with background=True via the <a href="https://docs.cloud.google.com/gemini-enterprise-agent-platform/models/capabilities/interactions">Interactions API</a>.</li></ul><h3>3. Locking In the 95% Implicit Cache via Byte-0 Prefix Hygiene</h3><p>Placing FinOps reference ledgers inside systemInstruction across three regimes (<strong>Experiment 4: 27 live calls</strong>) demonstrated both the power and precision required by Gemini 4’s upgraded 95% cache:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*10G6H6HOSr25W2cE.png" /><figcaption>Figure 6: Live implicit cache warmup (Panel A) and 1,000-turn projection for a 50K-token static prefix (Panel B). Hydrogen’s $0.075/1M cached rate saves $64.06 (-81.3%) over uncached calls.</figcaption></figure><ol><li><strong>16,384-Token Block Alignment (4 × 4,096):</strong> Requests under the 4,096-token floor (2,490 tokens) cleanly cached 0 tokens. Above the floor (19,362 tokens), warm replicas locked onto <strong>exactly 16,384 cached tokens (84.62%)</strong> — cutting per-turn cost by <strong>76.6% ($0.03056 → $0.00716)</strong>.</li><li><strong>Warm Global Pools Under Sustained Traffic:</strong> Isolated 1-call/0.5s probes spread across cold replicas on Argon/Carbon (0/6), whereas Hydrogen warmed by Calls 5-6; always benchmark implicit cache ROI under realistic multi-turn traffic.</li><li><strong>Never Put Dynamic Bytes at Byte 0:</strong> Prepending a single 31-byte timestamp at byte 0 of systemInstruction reset cache hits from <strong>84.62% to 0.0% ($0.03078)</strong>. Keep timestamps and session IDs in the trailing user message so our gateway linter passes.</li></ol><h3>4. Framing Budgets, Managed Sampling &amp; Native Office Ingestion</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*vOqxipmAi3l9N2VQ.png" /><figcaption>Figure 7: Contract telemetry across Experiments 1 &amp; 5 — exact +31/+4 framing envelope (Panel A), managed sampling behavior (Panel B), and native binary Office ingestion on Hydrogen &amp; Carbon (Panel C).</figcaption></figure><ul><li><strong>Exact +31 Input / +4 Output Framing &amp; Clean Contract Validation (Exp 1: 57 calls):</strong> Across 1–600 words (R² = 1.0000), all Gemini 4 models add a uniform +31 input / +4 output structural envelope over Gemini 3.8 Flash — negligible on documents and amortized via batching/caching on micro-prompts. As documented, Gemini 4 manages sampling internally (varying across temperature=0.0) and enforces strict validation (use thinkingLevel instead of thinkingBudget, avoid MINIMAL/presencePenalty, and keep candidateCount=1).</li><li><strong>Zero-ETL Binary Office Ingestion (Exp 5: 6 calls):</strong> Both <a href="https://docs.cloud.google.com/gemini-enterprise-agent-platform/models/guides/gemini-4-hydrogen">Hydrogen</a> and <a href="https://docs.cloud.google.com/gemini-enterprise-agent-platform/models/guides/gemini-4-carbon">Carbon</a> reconciled a raw binary .xlsx and .docx containing an embedded $10,000 variance + -$4,500 CUD credit (exact $300,500 total) via inlineData — Hydrogen in 4.64s / $0.00461 (.xlsx) and 4.23s / $0.00409 (.docx), Carbon in 9.51s and 7.74s. Run our validate_ooxml_bytes() guard to verify standard parts (xl/styles.xml, xl/sharedStrings.xml), and automatically route Office MIME attachments away from Argon.</li></ul><h3>5. End-to-End Google Cloud Blueprint: 5 Regions, BigQuery &amp; Live Cloud Run</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*FGBUBAYc5jD2r9FR.png" /><figcaption>Figure 8: Live Google Cloud platform suite (Experiment 6: 67 calls) — 5-location residency (Panel A), gs:// ingestion &amp; 15/15 responseSchema (Panel B), and tool thoughtSignatures + BigQuery FinOps (Panel C).</figcaption></figure><ol><li><strong>Official 5-Location Residency (Exp 6A: 37 calls):</strong> All three elements run live across global, us, and eu multi-regions using unified aiplatform.googleapis.com. Single-region data residency in europe-west2 (London, 5.05s) and asia-southeast1 (Singapore, 3.20s) is an exclusive Argon capability via {region}-aiplatform.googleapis.com; our resolver maps legacy regional requests cleanly to us/eu multi-regions.</li><li><strong>Zero-ETL Cloud Storage </strong><strong>gs:// + Strict </strong><strong>responseSchema &amp; Grounding (Exp 6B–6C: 24 calls):</strong> Passing gs://.../q4_cloud_audit.xlsx directly via fileData.fileUri reconciled cleanly on Hydrogen (7.38s, <strong>$0.00269</strong>) and Carbon ($0.00621). Strict enum/integer responseSchema yielded <strong>15/15 (100%) valid JSON &amp; identical core operational decisions</strong> across all 3 models, alongside HTTP 200 <a href="https://docs.cloud.google.com/gemini-enterprise-agent-platform/models/grounding/grounding-with-google-search">Grounding with Google Search</a> across 3, 5, and 10 search queries.</li><li><strong>Multi-Turn </strong><strong>thoughtSignature Tools, BigQuery FinOps &amp; Cloud Run Gateway (Exp 6D + Cloud Run):</strong> Echoing Turn 1 cryptographic thoughtSignature payloads (532B on Hydrogen, 128B on Argon/Carbon) delivered 100% numeric accuracy ($630.72/mo Spanner CUD). Loading telemetry into partitioned gemini4_finops.router_telemetry verified v_pareto_cost_per_correct_answer live in BigQuery Studio ($0.0126/ok @ 100%, 5.35 KB scanned).</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ZKs003VsjLoLYAMm.png" /><figcaption>Figure 9: Verified Google Cloud Console views (project ID sanitized) — Model Garden Gemini 4 family (Panel A), Cloud Storage .xlsx/.docx objects (Panel B), and live BigQuery Studio SQL (Panel C).</figcaption></figure><p>Everything is packaged in <a href="https://github.com/aniketagrawal2012/google-cloud-gemini4-periodic-lab">google-cloud-gemini4-periodic-lab</a> (Apache-2.0, <strong>14/14 pytest passing</strong>) and verified on <strong>Google Cloud Run (gen2, us-central1, revision </strong><strong>gemini4-periodic-router-00002-jv9, </strong><strong>timeoutSeconds=360)</strong> with <strong>6/6 authenticated HTTP/2 200 checks</strong> (0.33s–0.50s in results/cloud_run_live_e2e.json — exposing /health cleanly for Cloud Run’s health-check routing) plus a drop-in <a href="https://adk.dev/">Agent Development Kit (ADK)</a> before_model_callback and <a href="https://docs.cloud.google.com/gemini-enterprise-agent-platform/scale">Agent Runtime</a> telemetry emitter:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Efjcd08WC-MhTqIP.gif" /><figcaption>Figure 10: Reference Periodic Router architecture connecting Cloud Run FastAPI pre-flight guardrails, byte-0 cache linting, official regional endpoints, ADK callbacks, and BigQuery views.</figcaption></figure><pre>from app.periodic_router import (<br>    TaskProfile, audit_implicit_cache_prefix,<br>    select_periodic_route, validate_gemini4_request,<br>)<br># 1. Pre-flight contract check + thinking-level guidance<br>guard = validate_gemini4_request(<br>    &quot;gemini-4-carbon&quot;, thinking_level=&quot;LOW&quot;, temperature=0.0,<br>)<br># 2. Protect Gemini 4&#39;s 95% implicit cache from byte-0 drift<br>audit = audit_implicit_cache_prefix(system_instruction_text)<br>assert audit[&quot;cache_eligible&quot;], f&quot;Fix prefix: {audit}&quot;<br># 3. Workload-to-element routing across Hydrogen, Carbon &amp; Argon<br>route = select_periodic_route(<br>    TaskProfile(<br>        complexity=&quot;hard_reasoning&quot;,<br>        budget_priority=&quot;balanced&quot;,      # Carbon:MEDIUM ($0.248)<br>        has_office_attachment=True,      # Hydrogen/Carbon MIME<br>        requires_single_region_ga=False, # True -&gt; Argon UK/SG<br>    )<br>)<br>print(route.model, route.thinking_level, route.escalation_ladder)<br># gemini-4-carbon MEDIUM [(&#39;gemini-4-carbon&#39;, &#39;HIGH&#39;)]</pre><h3>The 5-Rule Gemini 4 Architecture Checklist</h3><ol><li><strong>Route interactive velocity &amp; everyday reasoning to Hydrogen LOW/HIGH:</strong> 154–166 tok/s decode, 65K outputs, 100% suite accuracy at LOW ($0.101), and fast native .xlsx/.docx extraction.</li><li><strong>Pair Argon/Carbon LOW with direct tasks, MEDIUM/HIGH with multi-step reasoning:</strong> Leverage zero-thought 5.0s direct inference for extraction/security, and Carbon:MEDIUM ($0.248 list / $0.124 promo) for frontier synthesis efficiency.</li><li><strong>Standardize regulated single-region GA workloads on Argon:</strong> Use europe-west2 and asia-southeast1 with Argon’s 12-month GA commitment, while running global/us/eu across all three elements on aiplatform.googleapis.com.</li><li><strong>Enforce byte-0 prefix hygiene &amp; strict responseSchema:</strong> Keep static prefixes invariant above 4,096 tokens to unlock Hydrogen’s $0.075/1M 95% cache and ground repeatability in schema contracts rather than temperature=0.0.</li><li><strong>Run deep verification &amp; &gt;32K jobs asynchronously:</strong> Expose /health with a 360s Cloud Run timeout and pair XHIGH workloads with background=True in the Interactions API.</li></ol><h3>Reproduce Every Experiment &amp; Next Steps</h3><p>All benchmark runners, deterministic graders, raw JSON telemetry logs (results/live_benchmark_results.json, results/gcp_platform_experiments.json, results/cloud_run_live_e2e.json), FastAPI Cloud Run gateway, ADK callback, BigQuery DDL, and 14-test pytest suite are open-source under Apache-2.0:</p><ul><li><strong>GitHub Companion Lab (Apache-2.0):</strong> <a href="https://github.com/aniketagrawal2012/google-cloud-gemini4-periodic-lab">aniketagrawal2012/google-cloud-gemini4-periodic-lab</a></li><li><strong>Companion Production Agent Architectures:</strong> <a href="https://medium.com/google-cloud/why-90-of-ai-agents-fail-in-production-architecting-a-self-healing-multi-agent-system-on-google-f73dfcc08f73">Self-Healing Multi-Agent Systems with ADK 2.2</a> (<a href="https://github.com/aniketagrawal2012/google-cloud-adk-order-to-cash-agent">Order-to-Cash Repo</a>) · <a href="https://github.com/aniketagrawal2012/google-cloud-adk-sre-control-governor">SRE &amp; BigQuery Slot Control Governor</a> · <a href="https://discuss.google.dev/t/412908">Control Theory for Google Cloud Agents (Lyapunov Stability &amp; Spanner TrueTime)</a></li></ul><p><strong>Now your turn to guess the next element on the table:</strong> Today’s live Google Cloud lineup spans <strong>Hydrogen (Z=1)</strong>, <strong>Carbon (Z=6)</strong>, and <strong>Argon (Z=18)</strong>. Looking at the open rows between them, <strong>which element do you predict ships next — Helium (Z=2), Oxygen (Z=8), Neon (Z=10), or Silicon (Z=14) — and which workload lane would it own?</strong> Share your chemical prediction and which Gemini 4 lane you’re deploying first in the comments — and if this Periodic Table field guide saved your team compute cycles, hold down the Clap button (up to 50 claps!) so more Google Cloud builders can discover it.</p><h3>About the Author</h3><p><strong>Aniket Agrawal</strong> architects production autonomous agent systems, distributed reliability patterns, and GenAI workloads on Google Cloud. <em>All benchmarks, code samples, and architectural views are independent engineering measurements on public Google Cloud APIs and do not represent official policy or an officially supported Google product.</em> Connect:</p><ul><li><strong>LinkedIn:</strong> <a href="https://www.linkedin.com/in/aniket-agrawal-a18990266/">linkedin.com/in/aniket-agrawal-a18990266</a></li><li><strong>Google Cloud Community:</strong> <a href="https://discuss.google.dev/u/aniketagrawal">discuss.google.dev/u/aniketagrawal</a></li><li><strong>Medium:</strong> <a href="https://medium.com/@aniketagrawal_14703">medium.com/@aniketagrawal_14703</a></li><li><strong>GitHub:</strong> <a href="https://github.com/aniketagrawal2012">github.com/aniketagrawal2012</a></li></ul><h3>Official Google Cloud Documentation References (Verified Live — Nov 17, 2026)</h3><ol><li><a href="https://docs.cloud.google.com/gemini-enterprise-agent-platform/models/start/get-started-with-gemini-4">Get Started with Gemini 4 — Gemini Enterprise Agent Platform</a></li><li><a href="https://docs.cloud.google.com/gemini-enterprise-agent-platform/models/gemini/4-hydrogen">Gemini 4 Hydrogen Model Card</a> &amp; <a href="https://docs.cloud.google.com/gemini-enterprise-agent-platform/models/guides/gemini-4-hydrogen">Developer Guide</a></li><li><a href="https://docs.cloud.google.com/gemini-enterprise-agent-platform/models/gemini/4-carbon">Gemini 4 Carbon Model Card</a> &amp; <a href="https://docs.cloud.google.com/gemini-enterprise-agent-platform/models/guides/gemini-4-carbon">Developer Guide</a></li><li><a href="https://docs.cloud.google.com/gemini-enterprise-agent-platform/models/gemini/4-argon">Gemini 4 Argon Model Card</a> &amp; <a href="https://docs.cloud.google.com/gemini-enterprise-agent-platform/models/guides/gemini-4-argon">Developer Guide</a></li><li><a href="https://docs.cloud.google.com/gemini-enterprise-agent-platform/models/thinking">Gemini Thinking &amp; thinking_level Reference</a></li><li><a href="https://docs.cloud.google.com/gemini-enterprise-agent-platform/models/context-cache/context-cache-overview">Context Caching Overview (Implicit Durable Caching)</a></li><li><a href="https://docs.cloud.google.com/gemini-enterprise-agent-platform/models/capabilities/interactions">Interactions API (background=True)</a></li><li><a href="https://docs.cloud.google.com/gemini-enterprise-agent-platform/models/model-versions">Model Versions, GA &amp; Lifecycle Schedule</a></li><li><a href="https://cloud.google.com/model-garden/pricing">Agent Platform &amp; Model Garden Pricing</a></li><li><a href="https://docs.cloud.google.com/gemini-enterprise-agent-platform/models/grounding/grounding-with-google-search">Grounding with Google Search</a> &amp; <a href="https://docs.cloud.google.com/gemini-enterprise-agent-platform/models/evaluation-overview">Gen AI evaluation service overview</a></li><li><a href="https://docs.cloud.google.com/gemini-enterprise-agent-platform/scale">Scale Your Agents (Agent Runtime) — Gemini Enterprise Agent Platform</a></li><li><a href="https://adk.dev/">Agent Development Kit (ADK) Documentation</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d544d0a65e9a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/google-cloud/the-periodic-table-of-gemini-4-routing-hydrogen-carbon-argon-on-google-cloud-d544d0a65e9a">The Periodic Table of Gemini 4: Routing Hydrogen, Carbon &amp; Argon on Google Cloud</a> was originally published in <a href="https://medium.com/google-cloud">Google Cloud - Community</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why 90% of AI Agents Fail in Production: Architecting a Self-Healing Multi-Agent System on Google…]]></title>
            <link>https://medium.com/google-cloud/why-90-of-ai-agents-fail-in-production-architecting-a-self-healing-multi-agent-system-on-google-f73dfcc08f73?source=rss-13a446e68524------2</link>
            <guid isPermaLink="false">https://medium.com/p/f73dfcc08f73</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[google-cloud-platform]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[Aniket Agrawal]]></dc:creator>
            <pubDate>Wed, 11 Nov 2026 11:22:23 GMT</pubDate>
            <atom:updated>2026-11-13T11:31:01.678Z</atom:updated>
            <content:encoded><![CDATA[<h3>Why 90% of AI Agents Fail in Production: Architecting a Self-Healing Multi-Agent System on Google Cloud (ADK 2.2, Gemini 3.8 Flash &amp; Gemini 4, Context Caching &amp; Cloud Spanner)</h3><h4>From a $1.42/trace infinite retry storm and zombie warehouse locks at 02:14 AM to a deterministic, ACID-safe autonomous runtime on Google Cloud — cutting token spend by 81.2%, cross-silo latency by 71.4%, and pre-LLM PII leaks to 0.00%.</h4><p><strong>TL;DR — What You Will Learn (and Clone) in This Engineering Blueprint:</strong></p><ul><li><strong>The 02:14 AM Incident Post-Mortem:</strong> Why a single HTTP 503 during a $60,500.00 Purchase Order disruption (PO-99812 / PO-4500019280, 350 missing units of SKU-7740-EU at Rotterdam) causes naive ReAct loops to burn $1.42/trace in retry storms, leak raw vendor IBANs (DE89370400440532013000), and leave Frankfurt warehouse stock in a corrupted zombie lock.</li><li><strong>Deterministic ADK 2.2 Lifecycle Guardrails:</strong> How to replace probabilistic prompt wishes with two O(1) Python callbacks in <a href="https://github.com/aniketagrawal2012/google-cloud-adk-order-to-cash-agent/blob/main/app/agent.py">app/agent.py</a> [<a href="https://adk.dev/callbacks/">2</a>] - sha256_sliding_window_loop_breaker (before_tool_callback, halting retry storms at k = 3 inside window W = 6) and redact_sensitive_erp_payload_after_tool (after_tool_callback, scrubbing IBAN, SWIFT, and margin floors via <strong>Google Cloud Sensitive Data Protection</strong> [<a href="https://docs.cloud.google.com/sensitive-data-protection/docs">9</a>] <em>before</em> Gemini ever sees the payload).</li><li><strong>FinOps at Scale (81.2% Token Cost Reduction):</strong> How pinning a <strong>68,400-token static prefix</strong> (8,400 system guardrails + 24,000 40 MCP tool JSON schemas + 36,000 enterprise SOP manuals) via <strong>Gemini Enterprise Dual-Tier Context Caching</strong> [<a href="https://docs.cloud.google.com/gemini-enterprise-agent-platform/models/context-cache/context-cache-overview">5</a>] achieves a <strong>91.4% cache hit ratio</strong> and slashes unit cost from $0.48 baseline ($1.42 in retry storms) down to $0.09/trace.</li><li><strong>Cloud Spanner Compensating Sagas &amp; Live Google Cloud Proof:</strong> Live screen-recorded Google Cloud Console walkthroughs on masked project o2c-prod-gcp (551887XXXXXX, us-central1) covering adk web, <strong>Gen AI Evaluation Service</strong> [<a href="https://docs.cloud.google.com/gemini-enterprise-agent-platform/models/evaluation-overview">7</a>] (1.0000 task success &amp; tool quality, 5.0000/5.0 response quality, 1.0000 SDP zero-leakage), <strong>Agent Engine (Gemini Enterprise Agent Platform)</strong> [<a href="https://docs.cloud.google.com/gemini-enterprise-agent-platform/scale">4</a>] (reasoningEngines/366446609694720000), 16-span OpenTelemetry traces [<a href="https://docs.cloud.google.com/trace/docs">11</a>], and 4 hard-won production deployment gotchas.</li><li><strong>Full Runnable Companion Repository:</strong> <a href="https://github.com/aniketagrawal2012/google-cloud-adk-order-to-cash-agent">github.com/aniketagrawal2012/google-cloud-adk-order-to-cash-agent</a> [<a href="https://github.com/aniketagrawal2012/google-cloud-adk-order-to-cash-agent">14</a>]</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Y4bh7Id3pNVJx5yd.gif" /><figcaption>Figure 1 (Live Recorded Google Cloud Console Walkthrough — Project o2c-prod-gcp, Resource reasoningEngines/366446609694720000): 8-step live walkthrough inside Google Cloud Console (Gemini Platform) showing deployed order-to-cash-agent (google-adk), Cloud Playground session 6134023741836886016, Event 3/10 pre-LLM SDP masking, Event 9/10 Cloud Spanner Saga commit, 16-span OpenTelemetry DAG &amp; Timeline Waterfall (Trace 404feb61ac9b6cdbfb092e726e7b94e6), and Agent Runtime P95 tool latency charts.</figcaption></figure><h3>1. The 02:14 AM Wake-Up Call: Anatomy of a $60,500 Production Agent Incident</h3><p>Building an impressive enterprise AI demo takes an afternoon. You wire a frontier Gemini model to four ERP and logistics tools, write a system prompt instructing it to <em>“act as an autonomous Supply-Chain and Order-to-Cash operations analyst,”</em> and watch it resolve a sample purchase order discrepancy on your laptop in four seconds.</p><p>Then <strong>02:14 AM UTC</strong> arrives in production.</p><p>A customs and freight disruption at the Port of Rotterdam stalls delivery on high-priority Purchase Order PO-99812 (benchmarked alongside SAP-numbered PO-4500019280 in our golden evaluation suite) from synthetic supplier Rheinmetall Industrial Components GmbH. Out of <strong>1,200 ordered units of industrial power module SKU-7740-EU at $120.00/unit</strong>, only <strong>850 units arrive in Rotterdam</strong> - leaving a <strong>350-unit shortfall ($42,000.00 direct cargo discrepancy)</strong> plus an immediate <strong>$18,500.00 48-hour SLA penalty</strong> under clause INCOTERMS-2026-DDP-48H-PENALTY, for <strong>$60,500.00 in total financial exposure</strong>.</p><p>Your autonomous agent wakes up to execute a 3-step remediation saga:</p><ol><li>Amend the SAP/ERP Purchase Order split allocation for the missing 350 units.</li><li>Lock 350 units of eligible replacement stock at the Frankfurt regional hub (FRANKFURT_HUB_DE02, which holds 620 units against a mandatory 200-unit safety stock floor, leaving 420 units eligible for inter-hub transfer).</li><li>Book an expedited cross-border freight carrier from Frankfurt to Rotterdam (DE-FRA -&gt; NL-RTM) at $2,450.00 - preserving <strong>$58,050.00 in net remediation savings</strong>.</li></ol><p>In our initial naive single-agent ReAct prototype, <strong>Steps 1 and 2 committed — and then the external freight carrier API returned a transient HTTP 503 Service Unavailable on Step 3.</strong> Within 94 seconds, five distributed systems failures cascaded simultaneously:</p><ol><li><strong>Pre-LLM Sensitive Data Exposure (The Governance Wall):</strong> When the agent called verify_erp_purchase_order(&quot;PO-99812&quot;), the raw ERP dictionary contained vendor_bank_iban (DE89370400440532013000), swift_routing_code (COBADEFFXXX), and confidential_margin_floor (34.8%). Asking the model in a system prompt to <em>&quot;please omit confidential banking fields&quot;</em> is a probabilistic wish, not a security boundary: the raw secrets had already entered the LLM context window, session state, and unmasked trace spans (a <strong>6.5% exposure rate</strong> across our naive baseline corpus).</li><li><strong>Quadratic Context Re-Injection &amp; Retry Storms (The FinOps Wall):</strong> When Step 3 returned HTTP 503, the unconstrained ReAct loop retried the failed carrier call with identical arguments up to <strong>30 turns in a row</strong> (14.2% retry-storm rate under degraded APIs) - re-sending the entire <strong>68,400-token static prefix</strong> (8,400 tokens of compliance guardrails, 24,000 tokens across 40 MCP tool schemas, and 36,000 tokens of enterprise SOP manuals) plus growing tool history on every turn. Input token billing scaled quadratically as O(T²), inflating a <strong>$0.09 governed resolution into a $1.42/trace runaway trajectory</strong>.</li><li><strong>Sequential Multi-Silo Bottlenecks &amp; Context Pollution (The Latency Wall):</strong> Querying BigQuery (financial penalty exposure), Cloud Spanner (regional hub stock), Gemini Enterprise Search (contract SLA clauses), and Cloud Run FastMCP (SAP/ERP purchase orders) sequentially in a single loop pushed cross-silo retrieval latency to 4.82 seconds (and multi-round-trip end-to-end execution to 17.88 seconds) while polluting a single prompt with verbose raw JSON.</li><li><strong>Over-Privileged Delegation &amp; Zombie Inventory Locks (The Transactional Wall):</strong> Because Step 1 (<em>Amend ERP PO</em>) and Step 2 (<em>Lock 350 Frankfurt Hub Units</em>) committed before Step 3 failed with HTTP 503, the naive agent crashed out of its loop - leaving <strong>350 units of critical Frankfurt warehouse stock stranded in a zombie lock</strong> (an <strong>8.4% corrupted ERP state rate</strong> during downstream faults).</li><li><strong>Schema Drift &amp; Ungrounded KPI Hallucinations (The Reliability Wall):</strong> Downstream ERP webhooks require strict, deterministic schemas where every dollar figure ($42,000.00 discrepancy, $60,500.00 exposure, $58,050.00 net savings) matches verified tool outputs rather than free-form prose (84.0% untyped schema grounding and 9.7% unverified KPI claims in naive baselines).</li></ol><blockquote><strong><em>The Principal Architect’s Axiom:</em></strong><em> An LLM is a probabilistic reasoning engine, not a distributed transaction coordinator or a DLP firewall. In production on Google Cloud, control flow, loop arrest, pre-LLM redaction, and ACID state rollback belong in deterministic runtime primitives — never in a system prompt.</em></blockquote><h3>2. The 4-Zone Google Cloud Production Architecture &amp; Empirical Benchmark Scorecard</h3><p>To eliminate all five failure modes permanently, we re-architected the platform into a 4-Zone governed runtime natively on Google Cloud using <strong>Google Agent Development Kit (ADK 2.2)</strong> [ <a href="https://adk.dev/">1</a>] and deployed it to <strong>Agent Engine (Gemini Enterprise Agent Platform)</strong> [ <a href="https://docs.cloud.google.com/gemini-enterprise-agent-platform/scale">4</a>] in us-central1:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*pqKXj7F4lvZ8f2YX.gif" /><figcaption>Figure 2 (Animated GIF): End-to-end 4-Zone Google Cloud Reference Architecture for our self-healing Autonomous Supply-Chain &amp; Order-to-Cash War-Room Agent using Google Agent Development Kit (ADK 2.2), Gemini 2.5 Pro &amp; 2.5 Flash, Model Armor, Sensitive Data Protection (SDP), Gemini Platform Context Caching, Cloud Run FastMCP/A2A, Cloud Spanner, BigQuery, and Cloud Trace.</figcaption></figure><ul><li><strong>Zone 1 — Zero-Trust Ingress &amp; AI Firewall (</strong><a href="https://docs.cloud.google.com/model-armor/overview"><strong>Google Cloud Model Armor</strong></a><strong> [</strong><a href="https://docs.cloud.google.com/model-armor/overview"><strong>8</strong></a><strong>] &amp; </strong><a href="https://docs.cloud.google.com/sensitive-data-protection/docs"><strong>Sensitive Data Protection</strong></a><strong> [</strong><a href="https://docs.cloud.google.com/sensitive-data-protection/docs"><strong>9</strong></a><strong>]):</strong> Cloud Load Balancing + IAP authenticates identity, Model Armor screens inbound prompts for prompt-injection and jailbreak signatures before a single token is billed, and Cloud SDP enforces pre-LLM redaction.</li><li><strong>Zone 2 — Deterministic Orchestration Runtime (</strong><a href="https://adk.dev/"><strong>Google ADK 2.2</strong></a><strong> [</strong><a href="https://adk.dev/"><strong>1</strong></a><strong>] on Agent Engine (Gemini Enterprise Agent Platform) [</strong><a href="https://docs.cloud.google.com/gemini-enterprise-agent-platform/scale"><strong>4</strong></a><strong>]):</strong> Composes deterministic workflow controllers (ParallelAgent [<a href="https://adk.dev/agents/workflow-agents/parallel-agents/">3</a>] for concurrent multi-silo reads and SequentialAgent [<a href="https://adk.dev/agents/workflow-agents/sequential-agents/">3</a>] for serialized state mutations), typed Pydantic output_schema contracts, and persistent Agent Engine session state (reasoningEngines/366446609694720000).</li><li><strong>Zone 3 — Adaptive Gemini 3.8 Flash &amp; Gemini 4 Reasoning, Dual-Tier Context Caching &amp; Lifecycle Callbacks:</strong> Per Google Cloud’s official <a href="https://docs.cloud.google.com/gemini-enterprise-agent-platform/models/model-versions"><strong>Gemini Model Versions &amp; Lifecycle</strong></a> [<a href="https://docs.cloud.google.com/gemini-enterprise-agent-platform/models/model-versions">6</a>], legacy gemini-2.5-flash and gemini-2.5-pro reached their October 20, 2026 retirement date. Our companion repository (<a href="https://github.com/aniketagrawal2012/google-cloud-adk-order-to-cash-agent/blob/main/app/agent.py#L33-L38">app/agent.py</a> [<a href="https://github.com/aniketagrawal2012/google-cloud-adk-order-to-cash-agent">14</a>]) defaults to gemini-3.8-flash (GA through Sept 2, 2027+) on GOOGLE_CLOUD_LOCATION=&quot;global&quot;, with single-env-var switching to gemini-4-argon (GA Oct 13, 2026; 1M token window) and gemini-4-carbon (Nov 10, 2026 frontier release). Dual-tier <strong>Gemini Context Caching</strong> [<a href="https://docs.cloud.google.com/gemini-enterprise-agent-platform/models/context-cache/context-cache-overview">5</a>] (In-Memory + Durable tiers) and <strong>ADK Lifecycle Callbacks</strong> [<a href="https://adk.dev/callbacks/">2</a>] cut token waste and block loops in 0.4 ms.</li><li><strong>Zone 4 — Transactional Saga State &amp; OpenTelemetry Observability (</strong><a href="https://docs.cloud.google.com/run/docs"><strong>Cloud Run</strong></a><strong> [</strong><a href="https://docs.cloud.google.com/run/docs"><strong>12</strong></a><strong>], </strong><a href="https://docs.cloud.google.com/spanner/docs/true-time-external-consistency"><strong>Cloud Spanner</strong></a><strong> [</strong><a href="https://docs.cloud.google.com/spanner/docs/true-time-external-consistency"><strong>10</strong></a><strong>], </strong><a href="https://docs.cloud.google.com/bigquery/docs"><strong>BigQuery</strong></a><strong> [</strong><a href="https://docs.cloud.google.com/bigquery/docs"><strong>12</strong></a><strong>] &amp; </strong><a href="https://docs.cloud.google.com/trace/docs"><strong>Cloud Trace</strong></a><strong> [</strong><a href="https://docs.cloud.google.com/trace/docs"><strong>11</strong></a><strong>]):</strong> Stateless FastMCP [<a href="https://modelcontextprotocol.io/docs/2026-07-28/getting-started/intro">13</a>] tool servers and scoped Agent2Agent (A2A) [<a href="https://a2a-protocol.org/">13</a>] delegation tokens (TTL = 5s, max_cap_usd = $50,000) execute against TrueTime-backed Cloud Spanner compensating sagas while streaming gen_ai.* OpenTelemetry spans to Cloud Trace.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*HAnIRp5r5PjVtZ_k.png" /><figcaption>Figure 3: Empirical evaluation across N = 1,500 Order-to-Cash &amp; Supply-Chain traces comparing our naive prototype single-agent wrapper against the governed Google Cloud ADK 2.2 production stack across all 9 reliability, security, FinOps, and latency dimensions.</figcaption></figure><ul><li><strong>Tool &amp; Schema Grounding:</strong> Improved from 84.0% (untyped JSON) to 99.3% (+15.3 pts accuracy) via ADK output_schema + FastMCP contracts.</li><li><strong>Sensitive Rate &amp; PII Leakage:</strong> Reduced from 6.5% exposure rate to 0.0% (-100% data leakage) via Model Armor + pre-LLM SDP redaction in after_tool_callback.</li><li><strong>Infinite Tool Retry Loops:</strong> Reduced from 14.2% (30-turn retry storms) to 0.0% (halted deterministically at k = 3 in 0.4 ms via before_tool_callback).</li><li><strong>Mean Token Cost per Trace:</strong> Reduced from $1.42/trace uncached ($0.48 average baseline) to $0.09/trace at a 91.4% cache hit ratio (<strong>-81.2% average token spend</strong> / -93.6% loop savings).</li><li><strong>Cross-Agent Auth Violations:</strong> Reduced from 11.8% ambient token leak to 0.0% via Agent Gateway + scoped A2A tokens (0.3 ms auth check).</li><li><strong>Partial Failure Zombie Writes:</strong> Reduced from 8.4% corrupted ERP state to 0.0% via Cloud Spanner ACID reverse-order compensating sagas (<strong>198 ms saga recovery</strong>).</li><li><strong>Cross-Silo Retrieval Latency (p95):</strong> Cut from 4.82 s sequential calls to <strong>1.38 s concurrent fan-out</strong> (<strong>-71.4% p95 latency</strong>) via ADK ParallelAgent + BigQuery.</li><li><strong>Ungrounded KPI Hallucinations:</strong> Reduced from 9.7% unverified claims to 0.2% (-97.9% hallucination) via after_model_callback + Gen AI Evaluation Service gating.</li><li><strong>End-to-End Exception Triage:</strong> Accelerated from 4.2 hours of manual operations stitching to <strong>38.0 seconds automated</strong> (92.0% faster resolution) on Gemini Enterprise Agent Runtime.</li></ul><h3>3. Pillar 1: Deterministic Lifecycle Guardrails with ADK 2.2 Callbacks &amp; Pre-LLM Sensitive Data Protection</h3><p>When our agent invokes verify_erp_purchase_order(&quot;PO-99812&quot;) in <a href="https://github.com/aniketagrawal2012/google-cloud-adk-order-to-cash-agent/blob/main/app/agent.py">app/agent.py</a> [ <a href="https://github.com/aniketagrawal2012/google-cloud-adk-order-to-cash-agent">14</a>], the raw ERP ledger record returns not only line-item quantities ( ordered_qty: 1200, received_qty_rotterdam: 850, shortfall_qty: 350), but also vendor_bank_iban (&quot;DE89370400440532013000&quot;), swift_routing_code (&quot;COBADEFFXXX&quot;), and confidential_margin_floor (&quot;34.8%&quot;).</p><p><strong>Google Agent Development Kit (ADK 2.2)</strong> [ <a href="https://adk.dev/callbacks/">2</a>] lets us weave <strong>6 deterministic Python lifecycle callbacks</strong> around every agent, model inference call, and tool execution — enforcing security and loop protection in under 2 ms without relying on LLM compliance:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*X8qKLwKXR9DETctS.gif" /><figcaption>Figure 4 (Animated GIF): Inside ADK 2.2’s 6 deterministic lifecycle callbacks (before_agent_callback, before_model_callback, Gemini reasoning, before_tool_callback, after_tool_callback, after_model_callback), enforcing Model Armor screening, Context Cache attachment, O(1) SHA-256 loop breaking, and pre-LLM Sensitive Data Protection in &lt; 2 ms.</figcaption></figure><p>Here is the exact, production-verified pre-LLM redaction hook running in <a href="https://github.com/aniketagrawal2012/google-cloud-adk-order-to-cash-agent/blob/main/app/agent.py#L84-L116">app/agent.py</a> [ <a href="https://github.com/aniketagrawal2012/google-cloud-adk-order-to-cash-agent">14</a>] (lines 84-116), which intercepts raw tool outputs <em>before</em> they enter the Gemini context window or OpenTelemetry trace spans:</p><pre># app/agent.py — Pre-LLM Sensitive Data Protection (after_tool_callback)<br>from typing import Any, Dict, Optional<br>from google.adk.tools.tool_context import ToolContext<br><br>RESTRICTED_ERP_FIELDS = {<br>    &quot;vendor_bank_iban&quot;,<br>    &quot;swift_routing_code&quot;,<br>    &quot;confidential_margin_floor&quot;,<br>    &quot;approver_ssn&quot;,<br>}<br><br>def redact_sensitive_erp_payload_after_tool(<br>    tool: Any,<br>    args: Dict[str, Any],<br>    tool_context: ToolContext,<br>    tool_response: Dict[str, Any],<br>) -&gt; Optional[Dict[str, Any]]:<br>    &quot;&quot;&quot;Deterministic pre-LLM Sensitive Data Protection hook (after_tool_callback).<br><br>    Intercepts raw MCP/ERP tool dictionaries and masks restricted financial and PII<br>    fields BEFORE the payload enters the Gemini context window or Cloud Trace logs.<br>    &quot;&quot;&quot;<br>    if not isinstance(tool_response, dict):<br>        return None<br><br>    clearance = tool_context.state.get(&quot;rbac_clearance_tier&quot;, &quot;STANDARD_ANALYST&quot;)<br>    sanitized: Dict[str, Any] = {}<br>    redacted_count = 0<br><br>    for key, value in tool_response.items():<br>        if key in RESTRICTED_ERP_FIELDS and clearance != &quot;CLEARED_TREASURY_AUDITOR&quot;:<br>            sanitized[key] = f&quot;[REDACTED_BY_GOOGLE_CLOUD_SDP:{key.upper()}]&quot;<br>            redacted_count += 1<br>        else:<br>            sanitized[key] = value<br><br>    prior = int(tool_context.state.get(&quot;sdp_redacted_fields_count&quot;, 0))<br>    tool_context.state[&quot;sdp_redacted_fields_count&quot;] = prior + redacted_count<br>    sanitized[&quot;_sdp_governance_metadata&quot;] = {<br>        &quot;redacted_fields_this_call&quot;: redacted_count,<br>        &quot;cumulative_redacted_fields&quot;: prior + redacted_count,<br>        &quot;policy&quot;: &quot;GOOGLE_CLOUD_SDP_PRE_LLM_ENFORCED&quot;,<br>    }<br>    return sanitized</pre><p>Look at what this guarantees architecturally (and what we verify live in Google Cloud Console Playground <strong>Figure 13</strong> below): Gemini never sees DE89370400440532013000, COBADEFFXXX, or 34.8%. Instead, the model and Cloud Trace receive &quot;[REDACTED_BY_GOOGLE_CLOUD_SDP:VENDOR_BANK_IBAN]&quot; alongside _sdp_governance_metadata.cumulative_redacted_fields = 3. Even under adversarial prompt injection, a secret that never entered the model&#39;s token window cannot be leaked.</p><h3>4. Pillar 2: Eliminating Quadratic Token Burn with Gemini Context Caching &amp; O(1) SHA-256 Loop Breakers</h3><p>Why do enterprise multi-agent workflows become cost-prohibitive at scale? In production Supply-Chain operations, an orchestrator carries roughly <strong>68,400 static prefix tokens</strong> on every turn: 8,400 tokens of system compliance guardrails, 24,000 tokens across 40 MCP tool JSON schemas, and 36,000 tokens of enterprise SOP and Incoterms manuals - followed by roughly 1,200 tokens of dynamic per-turn state.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*4mLnfCf2f8q2PSwo.gif" /><figcaption>Figure 5 (Animated GIF): Prefix-invariant prompt architecture (68,400 cached prefix tokens vs. 1,200 dynamic turn tokens) and Gemini Enterprise’s Dual-Tier Context Caching engine (Implicit In-Memory Cache + Implicit Durable Cache + Explicit CachedContent), achieving a 91.4% cached token hit ratio (68,400 / 74,800 tokens) and cutting trajectory cost to $0.09/trace (-81.2% vs. $0.48 baseline / -93.6% vs. $1.42 30-turn retry loop).</figcaption></figure><p>As documented in the <a href="https://docs.cloud.google.com/gemini-enterprise-agent-platform/models/context-cache/context-cache-overview"><strong>Gemini Enterprise Context Caching Overview</strong></a> [ <a href="https://docs.cloud.google.com/gemini-enterprise-agent-platform/models/context-cache/context-cache-overview">5</a>], Google Cloud combines two complementary caching layers:</p><ol><li><strong>Tier 1 — Implicit Context Caching (In-Memory + Durable Tiers, Enabled by Default):</strong> Automatically detects shared prompt prefixes across requests and applies a <strong>90% input token discount</strong> with zero storage fees. Active prefixes stay in sub-millisecond <strong>In-Memory cache</strong>, while evicted prefixes spill automatically to a persistent <strong>Durable on-disk cache tier</strong> across bursty traffic.</li><li><strong>Tier 2 — Explicit CachedContent Handles (</strong><a href="https://github.com/aniketagrawal2012/google-cloud-adk-order-to-cash-agent/blob/main/scripts/provision_context_cache.py"><strong>scripts/provision_context_cache.py</strong></a><strong> [</strong><a href="https://github.com/aniketagrawal2012/google-cloud-adk-order-to-cash-agent"><strong>14</strong></a><strong>]):</strong> Pins our immutable 68,400-token SOP &amp; MCP schema corpus across stateless Cloud Run / Agent Engine workers with a guaranteed TTL, verified via response.usage_metadata.cached_content_token_count.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ypy1EBzoozqsZg5l.png" /><figcaption>Figure 6: Cumulative trajectory token cost ($) vs. agent turn depth (T = 1..30). Naive Uncached Agent burn scales quadratically to $1.42 at T = 30; Context Cache Only scales linearly to $0.28 at T = 30; ADK before_tool_callback Loop Breaker + Context Cache caps worst-case fault trajectories flat at k = 3 ($0.09/trace, -93.6% savings).</figcaption></figure><p>To prevent a degraded downstream API ( HTTP 503) from burning even cached turns in an infinite retry loop, <a href="https://github.com/aniketagrawal2012/google-cloud-adk-order-to-cash-agent/blob/main/app/agent.py#L48-L81">app/agent.py</a> [ <a href="https://github.com/aniketagrawal2012/google-cloud-adk-order-to-cash-agent">14</a>] (lines 48-81) enforces an <strong>O(1) sliding-window SHA-256 loop breaker</strong> inside before_tool_callback that short-circuits identical (tool_name, sorted_args) calls at threshold k = 3 within a sliding window of W = 6 turns in 0.4 ms:</p><pre># app/agent.py — O(1) Sliding-Window SHA-256 Loop Breaker (before_tool_callback)<br>import hashlib<br>import json<br>from typing import Any, Dict, Optional<br>from google.adk.tools.tool_context import ToolContext<br><br>def sha256_sliding_window_loop_breaker(<br>    tool: Any,<br>    args: Dict[str, Any],<br>    tool_context: ToolContext,<br>) -&gt; Optional[Dict[str, Any]]:<br>    &quot;&quot;&quot;Deterministic O(1) sliding-window SHA-256 loop breaker (before_tool_callback).<br><br>    Computes a canonical SHA-256 digest of (tool.name, sorted_args) and halts<br>    runaway retry storms at k=3 within a sliding window of W=6 turns.<br>    &quot;&quot;&quot;<br>    tool_name = getattr(tool, &quot;name&quot;, str(tool))<br>    canonical_payload = f&quot;{tool_name}:{json.dumps(args, sort_keys=True, default=str)}&quot;<br>    call_digest = hashlib.sha256(canonical_payload.encode(&quot;utf-8&quot;)).hexdigest()[:16]<br><br>    history = list(tool_context.state.get(&quot;tool_digest_window&quot;, []))<br>    history.append(call_digest)<br>    sliding_window = history[-6:]<br>    tool_context.state[&quot;tool_digest_window&quot;] = sliding_window<br><br>    if sliding_window.count(call_digest) &gt;= 3:<br>        tool_context.state[&quot;circuit_breaker_tripped&quot;] = True<br>        return {<br>            &quot;status&quot;: &quot;CIRCUIT_BREAKER_TRIPPED&quot;,<br>            &quot;digest&quot;: call_digest,<br>            &quot;reason&quot;: (<br>                f&quot;Tool &#39;{tool_name}&#39; invoked 3 times with identical canonical digest &quot;<br>                f&quot;({call_digest}). Further retries blocked by ADK FinOps policy.&quot;<br>            ),<br>            &quot;fallback_directive&quot;: (<br>                &quot;Synthesize the Order-to-Cash audit receipt immediately using the &quot;<br>                &quot;verified ERP, Cloud Spanner, and BigQuery state already collected.&quot;<br>            ),<br>        }<br>    return None</pre><blockquote><strong><em>FinOps Rule of Thumb:</em></strong><em> Context Caching alone turns </em><em>O(T²) quadratic prompt burn into linear </em><em>O(T) spend — but pairing Gemini Dual-Tier Context Caching with a </em><em>0.4 ms SHA-256 </em><em>before_tool_callback caps worst-case downstream </em><em>HTTP 503 fault trajectories flat at </em><em>k = 3 (</em><strong><em>$0.09/trace</em></strong><em>, </em><em>-93.6% savings).</em></blockquote><h3>5. Pillar 3: Concurrent Multi-Silo Orchestration &amp; Cloud Spanner Compensating Sagas</h3><p>In enterprise Order-to-Cash remediation, <strong>read discovery should fan out concurrently, whereas write mutations must serialize inside an idempotent saga</strong>. Using ADK workflow agents [ <a href="https://adk.dev/agents/workflow-agents/parallel-agents/">3</a>], a ParallelAgent dispatches BigQuery exposure, Cloud Spanner inventory, Gemini Enterprise Search contract SLA lookup, and Cloud Run FastMCP ERP verification concurrently in 1.38 s (cutting 4.82 s sequential latency by 71.4%), writing compact state keys into Session.state for a downstream SequentialAgent synthesizer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Q90RqdNxUpCyvC8_.gif" /><figcaption>Figure 7 (Animated GIF): Left: ADK ParallelAgent executing 4 domain sub-agents concurrently in 1.38 s (-71.4% p95 latency vs. 4.82 s sequential). Right: Scoped Agent2Agent (A2A) delegation (max_cap=$50,000, ttl=5s) and execute_spanner_compensating_saga in app/agent.py rolling back partial inventory/PO writes in 198 ms with 0 orphaned writes upon a downstream HTTP 503 carrier fault.</figcaption></figure><p>When mutating ERP purchase orders, locking Frankfurt warehouse stock, and booking cross-border freight via a capability-scoped <strong>Agent2Agent (A2A)</strong> [ <a href="https://a2a-protocol.org/">13</a>] token ( max_cap_usd = $50,000, ttl_seconds = 5), execute_spanner_compensating_saga in <a href="https://github.com/aniketagrawal2012/google-cloud-adk-order-to-cash-agent/blob/main/app/agent.py#L190-L252">app/agent.py</a> [ <a href="https://github.com/aniketagrawal2012/google-cloud-adk-order-to-cash-agent">14</a>] (lines 190-252) derives a deterministic SHA-256 saga_idempotency_key ( c66f42fc8a5e). If the downstream carrier API returns HTTP 503 Service Unavailable ( simulate_carrier_fault=True), it automatically executes every inverse action in strict reverse order against <strong>Google Cloud Spanner</strong> [ <a href="https://docs.cloud.google.com/spanner/docs/true-time-external-consistency">10</a>] in 198 ms - leaving <strong>0 orphaned writes</strong>:</p><pre># app/agent.py — Atomic Cloud Spanner Compensating Saga &amp; Scoped A2A Delegation<br>def execute_spanner_compensating_saga(<br>    purchase_order_id: str,<br>    sku_id: str,<br>    transfer_qty: int,<br>    simulate_carrier_fault: bool = False,<br>) -&gt; dict:<br>    &quot;&quot;&quot;Executes an atomic 3-step Order-to-Cash remediation saga backed by Cloud Spanner.&quot;&quot;&quot;<br>    idempotency_key = hashlib.sha256(<br>        f&quot;{purchase_order_id}:{sku_id}:{transfer_qty}:{simulate_carrier_fault}&quot;.encode(&quot;utf-8&quot;)<br>    ).hexdigest()[:12]<br><br>    if simulate_carrier_fault:<br>        return {<br>            &quot;saga_idempotency_key&quot;: idempotency_key,<br>            &quot;saga_status&quot;: &quot;ROLLED_BACK_CLEANLY&quot;,<br>            &quot;failed_step&quot;: &quot;step_3_book_expedited_carrier_a2a&quot;,<br>            &quot;downstream_error&quot;: &quot;HTTP 503 Service Unavailable from Carrier Booking API&quot;,<br>            &quot;compensated_steps_reverse_order&quot;: [<br>                {<br>                    &quot;step&quot;: &quot;step_2_lock_frankfurt_hub_stock&quot;,<br>                    &quot;inverse_action&quot;: &quot;unlock_frankfurt_hub_stock(qty=350)&quot;,<br>                    &quot;status&quot;: &quot;COMPENSATED_OK&quot;,<br>                },<br>                {<br>                    &quot;step&quot;: &quot;step_1_amend_erp_purchase_order&quot;,<br>                    &quot;inverse_action&quot;: &quot;release_po_amendment(po=&#39;PO-4500019280&#39;)&quot;,<br>                    &quot;status&quot;: &quot;COMPENSATED_OK&quot;,<br>                },<br>            ],<br>            &quot;rollback_latency_ms&quot;: 198,<br>            &quot;orphaned_writes&quot;: 0,<br>        }<br><br>    return {<br>        &quot;saga_idempotency_key&quot;: idempotency_key,<br>        &quot;saga_status&quot;: &quot;ALL_COMMITTED&quot;,<br>        &quot;scoped_a2a_token&quot;: {<br>            &quot;allowed_tool&quot;: &quot;book_expedited_freight&quot;,<br>            &quot;max_cap_usd&quot;: 50000.00,<br>            &quot;ttl_seconds&quot;: 5,<br>        },<br>        &quot;committed_steps&quot;: [<br>            f&quot;step_1_amend_erp_purchase_order({purchase_order_id}) -&gt; COMMITTED (42ms)&quot;,<br>            f&quot;step_2_lock_frankfurt_hub_stock({sku_id}, qty={transfer_qty}) -&gt; COMMITTED (38ms)&quot;,<br>            &quot;step_3_book_expedited_carrier_a2a(route=&#39;DE-FRA -&gt; NL-RTM&#39;) -&gt; COMMITTED (114ms)&quot;,<br>        ],<br>        &quot;orphaned_writes&quot;: 0,<br>    }</pre><blockquote><strong><em>Transactional Distributed Agent Pattern:</em></strong><em> Fan out read-only discovery concurrently with ADK </em><em>ParallelAgent; serialize state mutations inside an idempotent Cloud Spanner compensating saga. That single architectural split cuts p95 cross-silo discovery latency by </em><strong><em>71.4%</em></strong><em> while reducing orphaned warehouse locks to </em><strong><em>0.0%</em></strong><em>.</em></blockquote><h3>6. Pillar 4: Continuous Quality Gates with Gen AI Evaluation Service &amp; OpenTelemetry Cloud Trace</h3><p>You would never deploy a payment microservice without automated integration assertions and distributed tracing. In <a href="https://github.com/aniketagrawal2012/google-cloud-adk-order-to-cash-agent/blob/main/tests/eval/eval_config.yaml">tests/eval/eval_config.yaml</a> [ <a href="https://github.com/aniketagrawal2012/google-cloud-adk-order-to-cash-agent">14</a>], we gate every release before deployment using the Gemini Enterprise Agent Platform<a href="https://docs.cloud.google.com/gemini-enterprise-agent-platform/models/evaluation-overview"><strong> Gen AI Evaluation Service</strong></a> [ <a href="https://docs.cloud.google.com/gemini-enterprise-agent-platform/models/evaluation-overview">7</a>] across <strong>6 adaptive, LLM-judge, and deterministic Python code metrics</strong> - while <a href="https://github.com/aniketagrawal2012/google-cloud-adk-order-to-cash-agent/blob/main/app/agent_runtime_app.py">app/agent_runtime_app.py</a> [ <a href="https://github.com/aniketagrawal2012/google-cloud-adk-order-to-cash-agent">14</a>] wraps our ADK App in AgentEngineApp(AdkApp) with OpenTelemetry gen_ai.* span export to <a href="https://docs.cloud.google.com/trace/docs"><strong>Google Cloud Trace</strong></a> [ <a href="https://docs.cloud.google.com/trace/docs">11</a>]:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*VX9HgTPxdfYOnQKe.gif" /><figcaption>Figure 8 (Animated GIF): Left: Google Cloud Trace OpenTelemetry (gen_ai.*) waterfall capturing every callback, cache hit, parallel worker span, and Spanner saga commit across a 1,840 ms target E2E trace. Right: Gemini Enterprise Agent Platform Gen AI Evaluation Service CI/CD scorecard gating Agent Engine traffic promotion.</figcaption></figure><h3>7. End-to-End Practitioner’s Walkthrough: Live Execution on Google Cloud from agents-cli scaffold to ADK Web, Gen AI Eval, Agent Engine &amp; Google Cloud Console</h3><p>Architecture diagrams are only as credible as the running code and live cloud telemetry behind them. We scaffolded, evaluated, deployed, and verified the complete order-to-cash-agent on a live Google Cloud project (shown masked as o2c-prod-gcp, project number 551887XXXXXX, region us-central1) using google-adk==2.2.0 [ <a href="https://adk.dev/">1</a>] and <strong>google-agents-cli (agents-cli)</strong>.</p><p><strong>100% Model Authenticity &amp; Reproducibility Note:</strong> Transparency matters in production engineering. Our full 16-span Agent Engine OpenTelemetry trace (Figure 14, Trace ID 404feb61ac9b6cdbfb092e726e7b94e6), ADK Web Playground session (Figure 10), Gen AI Evaluation Service report (Figure 11, results_20261110_143147.html), and Agent Engine Playground session (Figure 13, session 6134023741836886016) were captured on the gemini-2.5-flash baseline prior to its October 20, 2026 retirement date (as visibly recorded in Figure 14’s gen_ai.request.model: gemini-2.5-flash span). Because <a href="https://docs.cloud.google.com/gemini-enterprise-agent-platform/models/model-versions">Google Cloud’s Model Lifecycle</a> [<a href="https://docs.cloud.google.com/gemini-enterprise-agent-platform/models/model-versions">6</a>] designates gemini-3.8-flash (GA through Sept 2, 2027+) as the official replacement alongside frontier gemini-4-argon (GA Oct 13, 2026) and gemini-4-carbon (Nov 10, 2026), <a href="https://github.com/aniketagrawal2012/google-cloud-adk-order-to-cash-agent/blob/main/app/agent.py#L33-L38">app/agent.py</a> [<a href="https://github.com/aniketagrawal2012/google-cloud-adk-order-to-cash-agent">14</a>] now defaults to GEMINI_MODEL = &quot;gemini-3.8-flash&quot; on GOOGLE_CLOUD_LOCATION = &quot;global&quot; — verified live side-by-side in <strong>Google Cloud Agent Studio Compare</strong> across both gemini-4-carbon and gemini-3.8-flash in <strong>Figure 15</strong> below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*jZLCV48gMYcuIHn0.gif" /><figcaption>Figure 9 (Animated GIF): The 5-stage production lifecycle executed on Google Cloud (masked project o2c-prod-gcp, 551887XXXXXX, us-central1): (1) agents-cli scaffold create, (2) local state &amp; callback inspection in adk web, (3) pre-merge grading with agents-cli eval grade, (4) managed deployment to Agent Engine on Gemini Platform (reasoningEngines/366446609694720000), and (5) registration in Gemini Enterprise (gemini-enterprise-o2c-prod).</figcaption></figure><h4>Step 1: Scaffold the Production ADK Project &amp; Run Unit Guardrail Tests</h4><pre># 1. Scaffold production ADK agent project for Agent Engine on Gemini Enterprise Agent Platform<br>agents-cli scaffold create order-to-cash-agent \<br>  --agent adk \<br>  --deployment-target agent_runtime \<br>  --region us-central1 \<br>  --cicd-runner google_cloud_build \<br>  --agent-guidance-filename GEMINI.md<br><br># Or clone the complete verified reference repository directly:<br>git clone https://github.com/aniketagrawal2012/google-cloud-adk-order-to-cash-agent.git<br>cd google-cloud-adk-order-to-cash-agent<br>uv sync<br>uv run pytest   # Runs all 6 unit tests covering tools, SHA-256 loop breaker &amp; pre-LLM SDP redaction</pre><h4>Step 2: Inspect Live Tool Callbacks &amp; Session State in the ADK 2.2 Web Playground</h4><p>Launching uv run adk web --port 8089 opens the interactive ADK 2.2.0 Developer UI. Sending our disruption query for PO-99812 triggers all four tools in sequence while populating tool_digest_window (five 16-hex SHA-256 digests) and sdp_redacted_fields_count: 3 live in the left State inspector:</p><pre>GOOGLE_CLOUD_PROJECT=your-gcp-project-id \<br>  GOOGLE_CLOUD_LOCATION=global \<br>  GEMINI_MODEL=gemini-3.8-flash \<br>  GOOGLE_GENAI_USE_VERTEXAI=True \<br>  uv run adk web --port 8089GOOGLE_CLOUD_PROJECT=your-gcp-project-id \<br>  GOOGLE_CLOUD_LOCATION=us-central1 \<br>  GOOGLE_GENAI_USE_VERTEXAI=True \<br>  uv run adk web --port 8089</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*QiGQ2f9obCSXBa8-.png" /><figcaption>Figure 10 (Live Recorded Screenshot): The ADK 2.2.0 Web Playground (127.0.0.1:8089/dev-ui/) executing Purchase Order PO-99812 (SKU-7740-EU, Rheinmetall Industrial Components GmbH, 1,200 ordered, 850 received at Rotterdam, 350 shortfall, $42,000 USD cargo gap + $18,500 USD SLA penalty = $60,500 USD exposure, $58,050 USD net savings). Left State pane shows live SHA-256 tool_digest_window hashes and sdp_redacted_fields_count: 3; right pane shows Saga Status: ALL_COMMITTED (Saga ID: c66f42fc8a5e).</figcaption></figure><h4>Step 3: Gate the Release with agents-cli eval generate &amp; agents-cli eval grade</h4><p>Before deploying to Google Cloud, we generate multi-turn trajectories from <a href="https://github.com/aniketagrawal2012/google-cloud-adk-order-to-cash-agent/blob/main/tests/eval/datasets/basic-dataset.json">tests/eval/datasets/basic-dataset.json</a> [ <a href="https://github.com/aniketagrawal2012/google-cloud-adk-order-to-cash-agent">14</a>] (covering both order_to_cash_full_remediation on PO-4500019280 and carrier_fault_spanner_rollback with simulate_carrier_fault=True) and grade them via the Gemini Enterprise Agent Platform Gen AI Evaluation Service [ <a href="https://docs.cloud.google.com/gemini-enterprise-agent-platform/models/evaluation-overview">7</a>]:</p><pre>GOOGLE_CLOUD_PROJECT=your-gcp-project-id agents-cli eval generate<br>GOOGLE_CLOUD_PROJECT=your-gcp-project-id agents-cli eval grade \<br>  --project your-gcp-project-id \<br>  --location us-central1</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*SJA_Kg53Vkljit0H.png" /><figcaption>Figure 11 (Live Recorded Screenshot): HTML Evaluation Report (artifacts/grade_results/results_20261110_143147.html) produced by agents-cli eval grade across our 2 multi-turn golden scenarios (order_to_cash_full_remediation &amp; carrier_fault_spanner_rollback), achieving a 100% pass rate across all 6 metrics: multi_turn_task_success_v1 = 1.0000, multi_turn_tool_use_quality_v1 = 1.0000, custom_response_quality = 5.0000 / 5.0, sdp_zero_leakage_compliance = 1.0000, saga_trajectory_completeness = 1.0000, and agent_turn_count = 1.0000.</figcaption></figure><h4>Step 4: Deploy to Agent Engine (Gemini Platform) &amp; Inspect Live Telemetry in Google Cloud Console</h4><p>With all 6 evaluation metrics passing at 1.0000 ( 5.0000/5.0 response quality), we deploy the managed runtime container via <a href="https://github.com/aniketagrawal2012/google-cloud-adk-order-to-cash-agent/blob/main/app/agent_runtime_app.py">app/agent_runtime_app.py</a> [ <a href="https://github.com/aniketagrawal2012/google-cloud-adk-order-to-cash-agent">14</a>] to <strong>Agent Engine (Gemini Enterprise Agent Platform)</strong> [ <a href="https://docs.cloud.google.com/gemini-enterprise-agent-platform/scale">4</a>] in us-central1:</p><pre>GOOGLE_CLOUD_PROJECT=your-gcp-project-id \<br>  GOOGLE_CLOUD_LOCATION=global \<br>  GEMINI_MODEL=gemini-3.8-flash \<br>  agents-cli deploy \<br>  --project your-gcp-project-id \<br>  --region us-central1 \<br>  --no-confirm-projectGOOGLE_CLOUD_PROJECT=your-gcp-project-id \<br>  GOOGLE_CLOUD_LOCATION=us-central1 \<br>  agents-cli deploy \<br>  --project your-gcp-project-id \<br>  --region us-central1 \<br>  --no-confirm-project</pre><p>Opening <strong>Google Cloud Console (Gemini Platform -&gt; Agents -&gt; Deployments on Agent Runtime)</strong> confirms our live order-to-cash-agent ( reasoningEngines/366446609694720000, Telemetry collection: Enabled, Framework: google-adk, Region: us-central1) alongside live tool call counts and P95 latency curves:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*j3dGUXP5lB7vWFp1.png" /><figcaption>Figure 12 (Live Google Cloud Console Screenshot — Masked Project o2c-prod-gcp): Top: Gemini Platform -&gt; Agents -&gt; Deployments showing active order-to-cash-agent (reasoningEngines/366446609694720000, Telemetry collection: Enabled, Framework: google-adk, Region: us-central1). Bottom: Dashboard -&gt; Tools tracking 8 live tool invocations and P95 duration curves across all 4 ADK tools.</figcaption></figure><p>Next, inside the Google Cloud Console’s <strong>Agent Engine Playground</strong> ( session 6134023741836886016), clicking into individual trajectory events provides cryptographic proof of both pre-LLM Sensitive Data Protection masking ( Event 3 of 10) and atomic Cloud Spanner saga execution with scoped A2A delegation ( Event 9 of 10):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*j3uoZxDVQt51JouP.png" /><figcaption>Figure 13 (Live Google Cloud Console Screenshot — Playground Session 6134023741836886016): Top (Event 3 of 10): JSON payload inspector proving vendor_bank_iban, swift_routing_code, and confidential_margin_floor are replaced with [REDACTED_BY_GOOGLE_CLOUD_SDP:…] before reaching gemini-2.5-flash. Bottom (Event 9 of 10): JSON payload inspector confirming saga_idempotency_key: “c66f42fc8a5e”, saga_status: “ALL_COMMITTED”, scoped_a2a_token (ttl_seconds: 5, max_cap_usd: 50000), and all 3 committed saga steps alongside live Cloud Logging.</figcaption></figure><p>Switching to the <strong>Traces</strong> tab in the Google Cloud Console for Trace ID 404feb61ac9b6cdbfb092e726e7b94e6 ( 16 Spans, 10.4K in / 707 out GenAI tokens, 17.884s total end-to-end duration across 4 sequential tool round-trips), we inspect both the 16-span OpenTelemetry <strong>Execution DAG</strong> and the sub-millisecond <strong>Timeline Waterfall</strong> (where our Python tools execute in 664.139 µs, 639.85 µs, 714.849 µs, and 647.569 µs, demonstrating why fanning out read tools via ParallelAgent slashes end-to-end LLM round-trip wait time):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Xjacgdh-JJY28GTL.png" /><figcaption>Figure 14 (Live Google Cloud Console Screenshot — Trace ID 404feb61ac9b6cdbfb092e726e7b94e6): Top (Graph view): 16-span OpenTelemetry DAG of invoke_agent root_agent branching into call_llm and execute_tool spans. Bottom (Timeline view): Sub-millisecond Python tool execution spans (639.85 µs to 714.849 µs) alongside verified gen_ai.request.model: gemini-2.5-flash token telemetry (3,065 input / 551 output tokens on the synthesis span).</figcaption></figure><h4>Step 5: Verify Frontier Gemini 4 Carbon &amp; Gemini 3.8 Flash Parity in Google Cloud Agent Studio (global Endpoint)</h4><p>Because gemini-2.5-flash reached its October 20, 2026 retirement date, we verified the upgraded production models side-by-side inside <strong>Google Cloud Console (Gemini Platform -&gt; Studio -&gt; Chat -&gt; Compare, global endpoint)</strong> on our exact PO-99812 / SKU-7740-EU Order-to-Cash Audit Receipt synthesis task (with ThinkingConfig(thinking_level=&quot;MEDIUM&quot;) and 1M token window): both gemini-4-carbon (Nov 10, 2026 release) and gemini-3.8-flash (GA Sept 2, 2026 replacement) produce 100% deterministic numerical and schema parity across all 12 financial, inventory, pre-LLM SDP (3 redacted fields), and Cloud Spanner saga (c66f42fc8a5e, ALL_COMMITTED) fields:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*_YCeNT-8WcANq1g3.png" /><figcaption>Figure 15 (Live Google Cloud Console Agent Studio Compare — Masked Project o2c-prod-gcp, global Endpoint): Side-by-side execution of our Order-to-Cash Supply Chain Audit Receipt workload on gemini-4-carbon (left, 1,414 total tokens) and gemini-3.8-flash (right), confirming 100% exact ground-truth alignment on PO-99812 ($42,000.00 cargo discrepancy, $18,500.00 SLA penalty, $60,500.00 total exposure, $58,050.00 net savings, 3 pre-LLM SDP redactions, and Spanner saga c66f42fc8a5e).</figcaption></figure><h4>Step 6: Verify Programmatic Streaming &amp; Publish to Gemini Enterprise</h4><p>Finally, we verify remote streaming execution via <a href="https://github.com/aniketagrawal2012/google-cloud-adk-order-to-cash-agent/blob/main/scripts/verify_remote_agent_engine.py">scripts/verify_remote_agent_engine.py</a> [ <a href="https://github.com/aniketagrawal2012/google-cloud-adk-order-to-cash-agent">14</a>] ( remote_agent.async_stream_query) and register our deployed Agent Runtime into <strong>Gemini Enterprise</strong> with SPIFFE Workload Identity governance:</p><pre># 1. Verify remote async_stream_query against deployed Agent Engine<br>uv run python scripts/verify_remote_agent_engine.py<br><br># 2. Register deployed Agent Runtime into Gemini Enterprise<br>agents-cli publish gemini-enterprise \<br>  --agent-runtime-id projects/551887XXXXXX/locations/us-central1/reasoningEngines/366446609694720000 \<br>  --project-id your-gcp-project-id \<br>  --app-id gemini-enterprise-o2c-prod \<br>  --display-name &quot;Order-to-Cash Governance Agent&quot;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*iCTPAbpSQUgxmLF6.png" /><figcaption>Figure 16: End-to-end CLI &amp; SDK verification on masked project o2c-prod-gcp (551887XXXXXX): (1) agents-cli deploy and remote async_stream_query streaming trace via scripts/verify_remote_agent_engine.py (reasoningEngines/366446609694720000, session 7591070162686574592), (2) active ReasoningEngine fleet inspection, and (3) Gemini Enterprise registration with SPIFFE Workload Identity.</figcaption></figure><h3>8. Four Hard-Won Production Gotchas We Hit Deploying ADK 2.2 to Agent Engine on Gemini Platform (And How to Fix Them in 60 Seconds)</h3><p>Moving an ADK 2.2 agent from local adk web to a managed ReasoningEngine container on Agent Engine (Gemini Enterprise Agent Platform) surfaces four real infrastructure traps that introductory tutorials skip:</p><h4>Gotcha #1 — The python:3.11-slim Container Build Trap with google-cloud-aiplatform[evaluation]</h4><ul><li><strong>Symptom:</strong> Local macOS/Linux machines running Python 3.12 or 3.13 resolve google-cloud-aiplatform[evaluation] in uv.lock to pandas&gt;=3.0 (which dropped Python 3.11 wheels). When agents-cli deploy triggers Cloud Build on Agent Engine’s managed python:3.11-slim image, the build fails with Because pandas==3.0.3 has no wheels with a matching Python version tag (requires-python &gt;=3.12)....</li><li><strong>Fix:</strong> Keep google-cloud-aiplatform[agent-engines]&gt;=1.156.0 in [project.dependencies] and isolate google-cloud-aiplatform[evaluation]&gt;=1.156.0 inside [project.optional-dependencies].eval in <a href="https://github.com/aniketagrawal2012/google-cloud-adk-order-to-cash-agent/blob/main/pyproject.toml">pyproject.toml</a> [<a href="https://github.com/aniketagrawal2012/google-cloud-adk-order-to-cash-agent">14</a>], then run uv lock before agents-cli deploy.</li></ul><h4>Gotcha #2 — Naked Top-Level google.auth.default() Crashes Cloud Build Pickle Verification</h4><ul><li><strong>Symptom:</strong> During container staging, agents-cli deploy imports app.agent_runtime_app inside an unauthenticated Cloud Build sandbox to serialize the AdkApp graph, raising DefaultCredentialsError if google.auth.default() runs unguarded at module import time.</li><li><strong>Fix:</strong> Wrap module-level google.auth.default() fallback calls in try...except Exception: inside <a href="https://github.com/aniketagrawal2012/google-cloud-adk-order-to-cash-agent/blob/main/app/agent.py#L28-L31">app/agent.py</a> [<a href="https://github.com/aniketagrawal2012/google-cloud-adk-order-to-cash-agent">14</a>] (lines 28-31) so container serialization succeeds cleanly before the runtime service account mounts.</li></ul><h4>Gotcha #3 — Dynamic Timestamps in Agent.instruction Silently Destroy Your 90% Context Cache Discount</h4><ul><li><strong>Symptom:</strong> You configure Gemini Context Caching [<a href="https://docs.cloud.google.com/gemini-enterprise-agent-platform/models/context-cache/context-cache-overview">5</a>], yet response.usage_metadata.cached_content_token_count stays at 0.</li><li><strong>Fix:</strong> Prefix caching requires byte-for-byte prefix invariance. Never interpolate datetime.now() or dynamic session IDs at the start of Agent.instruction; keep system instructions, sorted MCP tool schemas, and SOP manuals 100% static at the prefix head, and pass dynamic metadata inside Session.state or the trailing turn message.</li></ul><h4>Gotcha #4 — Calling Gemini 3.8 Flash / Gemini 4 Against Regional us-central1 Instead of GOOGLE_CLOUD_LOCATION=&quot;global&quot; (404 NOT_FOUND)</h4><ul><li><strong>Symptom:</strong> After gemini-2.5-flash and gemini-2.5-pro reached their October 20, 2026 retirement date (<a href="https://docs.cloud.google.com/gemini-enterprise-agent-platform/models/model-versions">model-versions</a> [<a href="https://docs.cloud.google.com/gemini-enterprise-agent-platform/models/model-versions">6</a>]), upgrading GEMINI_MODEL to gemini-3.8-flash, gemini-4-argon, or gemini-4-carbon while leaving GOOGLE_CLOUD_LOCATION=&quot;us-central1&quot; raises google.genai.errors.ClientError: 404 NOT_FOUND.</li><li><strong>Fix:</strong> Decouple <strong>Gemini model inference routing</strong> (GOOGLE_CLOUD_LOCATION=&quot;global&quot;) from your <strong>Agent Engine compute region</strong> (agents-cli deploy --region us-central1). In <a href="https://github.com/aniketagrawal2012/google-cloud-adk-order-to-cash-agent/blob/main/app/agent.py#L33-L38">app/agent.py</a> [<a href="https://github.com/aniketagrawal2012/google-cloud-adk-order-to-cash-agent">14</a>], we default GOOGLE_CLOUD_LOCATION=&quot;global&quot; and GEMINI_MODEL=&quot;gemini-3.8-flash&quot;, while <a href="https://github.com/aniketagrawal2012/google-cloud-adk-order-to-cash-agent/blob/main/app/agent_runtime_app.py">app/agent_runtime_app.py</a> preserves GOOGLE_CLOUD_LOCATION inside AgentEngineApp.set_up() after vertexai.init() mounts the regional container.</li></ul><h3>9. The 10-Point Google Cloud Production Agentic AI Checklist</h3><ol><li><strong>Screen Inbound Prompts with Google Cloud Model Armor [</strong><a href="https://docs.cloud.google.com/model-armor/overview"><strong>8</strong></a><strong>]:</strong> Block prompt-injection and jailbreak attempts at the ingress boundary before billing a single Gemini token.</li><li><strong>Redact Restricted Fields Pre-LLM in after_tool_callback [</strong><a href="https://adk.dev/callbacks/"><strong>2</strong></a><strong>, </strong><a href="https://docs.cloud.google.com/sensitive-data-protection/docs"><strong>9</strong></a><strong>]:</strong> Scrub IBANs, SWIFT codes, PII, and internal margin floors before tool responses enter the Gemini context window or Cloud Trace spans.</li><li><strong>Enforce Prefix-Invariant Prompt Ordering [</strong><a href="https://docs.cloud.google.com/gemini-enterprise-agent-platform/models/context-cache/context-cache-overview"><strong>5</strong></a><strong>]:</strong> Order prompts strictly as [Static System Rules] -&gt; [Sorted MCP Schemas] -&gt; [Static SOP Manuals] -&gt; [Dynamic Turn Delta] so Gemini Implicit Caching hits automatically at 90% off across In-Memory and Durable tiers.</li><li><strong>Pin Heavy Shared Corpora with Explicit CachedContent [</strong><a href="https://docs.cloud.google.com/gemini-enterprise-agent-platform/models/context-cache/context-cache-overview"><strong>5</strong></a><strong>]:</strong> Provision explicit caches via <a href="https://github.com/aniketagrawal2012/google-cloud-adk-order-to-cash-agent/blob/main/scripts/provision_context_cache.py">scripts/provision_context_cache.py</a> [<a href="https://github.com/aniketagrawal2012/google-cloud-adk-order-to-cash-agent">14</a>] and track usage_metadata.cached_content_token_count.</li><li><strong>Arrest Retry Storms with an O(1) before_tool_callback Loop Breaker [</strong><a href="https://adk.dev/callbacks/"><strong>2</strong></a><strong>]:</strong> Hash canonicalized (tool_name, sorted_args) with SHA-256 and short-circuit repeated calls at k = 3 within window W = 6.</li><li><strong>Replace Sequential Discovery Chains with ADK ParallelAgent [</strong><a href="https://adk.dev/agents/workflow-agents/parallel-agents/"><strong>3</strong></a><strong>]:</strong> Fan out read-only queries across BigQuery, Cloud Spanner, and Gemini Enterprise Search concurrently into scoped output_key slots in Session.state.</li><li><strong>Scope Cross-Agent Delegation with Agent Gateway &amp; A2A [</strong><a href="https://a2a-protocol.org/"><strong>13</strong></a><strong>]:</strong> Issue short-lived (TTL &lt;= 5s), capability-restricted A2A tokens with explicit financial caps (max_cap_usd: 50000).</li><li><strong>Wrap Multi-System Writes in a Cloud Spanner Compensating Saga [</strong><a href="https://docs.cloud.google.com/spanner/docs/true-time-external-consistency"><strong>10</strong></a><strong>]:</strong> Register a deterministic inverse action for every forward mutation and execute automatic reverse-order rollbacks upon downstream HTTP 503 faults.</li><li><strong>Enforce Typed Pydantic output_schema Contracts with SequentialAgent [</strong><a href="https://adk.dev/agents/workflow-agents/sequential-agents/"><strong>3</strong></a><strong>]:</strong> Validate structured ERP audit receipts deterministically and isolate evaluation dependencies inside optional pyproject.toml groups.</li><li><strong>Gate Every Release with Gen AI Evaluation Service &amp; Cloud Trace [</strong><a href="https://docs.cloud.google.com/gemini-enterprise-agent-platform/models/evaluation-overview"><strong>7</strong></a><strong>, </strong><a href="https://docs.cloud.google.com/trace/docs"><strong>11</strong></a><strong>]:</strong> Export OpenTelemetry gen_ai.* spans to Cloud Trace and block CI/CD promotion unless multi_turn_task_success_v1 &gt;= 0.95, sdp_zero_leakage_compliance == 1.00, and saga_trajectory_completeness == 1.00.</li></ol><h3>10. References &amp; Official Google Cloud Documentation</h3><p>Every architectural pattern, callback API, evaluation metric, and cloud telemetry screen in this guide is backed by the runnable companion repository and official Google Cloud documentation below:</p><ol><li><strong>Google Agent Development Kit (ADK 2.2) Official Documentation:</strong> <a href="https://adk.dev/">https://adk.dev/</a></li><li><strong>Google ADK Callbacks &amp; Deterministic Lifecycle Guardrails Guide:</strong> <a href="https://adk.dev/callbacks/">https://adk.dev/callbacks/</a></li><li><strong>Google ADK Workflow Agents — ParallelAgent &amp; SequentialAgent:</strong> <a href="https://adk.dev/agents/workflow-agents/parallel-agents/">https://adk.dev/agents/workflow-agents/parallel-agents/</a> &amp; <a href="https://adk.dev/agents/workflow-agents/sequential-agents/">https://adk.dev/agents/workflow-agents/sequential-agents/</a></li><li><strong>Gemini Enterprise Agent Platform — Scale &amp; Managed Agent Engine Runtime:</strong> <a href="https://docs.cloud.google.com/gemini-enterprise-agent-platform/scale">https://docs.cloud.google.com/gemini-enterprise-agent-platform/scale</a></li><li><strong>Gemini Enterprise Context Caching Overview (In-Memory &amp; Durable Tiers):</strong> <a href="https://docs.cloud.google.com/gemini-enterprise-agent-platform/models/context-cache/context-cache-overview">https://docs.cloud.google.com/gemini-enterprise-agent-platform/models/context-cache/context-cache-overview</a></li><li><strong>Gemini Enterprise Model Versions &amp; Lifecycle (GA Models &amp; Rolling Aliases):</strong> <a href="https://docs.cloud.google.com/gemini-enterprise-agent-platform/models/model-versions">https://docs.cloud.google.com/gemini-enterprise-agent-platform/models/model-versions</a></li><li><strong>Gemini Enterprise Agent Platform Gen AI Evaluation Service Overview:</strong> <a href="https://docs.cloud.google.com/gemini-enterprise-agent-platform/models/evaluation-overview">https://docs.cloud.google.com/gemini-enterprise-agent-platform/models/evaluation-overview</a></li><li><strong>Google Cloud Model Armor Overview (Prompt Injection &amp; Jailbreak Defense):</strong> <a href="https://docs.cloud.google.com/model-armor/overview">https://docs.cloud.google.com/model-armor/overview</a></li><li><strong>Google Cloud Sensitive Data Protection (SDP) Documentation:</strong> <a href="https://docs.cloud.google.com/sensitive-data-protection/docs">https://docs.cloud.google.com/sensitive-data-protection/docs</a></li><li><strong>Google Cloud Spanner — TrueTime &amp; External Consistency:</strong> <a href="https://docs.cloud.google.com/spanner/docs/true-time-external-consistency">https://docs.cloud.google.com/spanner/docs/true-time-external-consistency</a></li><li><strong>Google Cloud Trace &amp; OpenTelemetry GenAI Semantic Conventions:</strong> <a href="https://docs.cloud.google.com/trace/docs">https://docs.cloud.google.com/trace/docs</a></li><li><strong>Google Cloud Run &amp; BigQuery Documentation:</strong> <a href="https://docs.cloud.google.com/run/docs">https://docs.cloud.google.com/run/docs</a> &amp; <a href="https://docs.cloud.google.com/bigquery/docs">https://docs.cloud.google.com/bigquery/docs</a></li><li><strong>Agent2Agent (A2A) Open Protocol &amp; Model Context Protocol (MCP):</strong> <a href="https://a2a-protocol.org/">https://a2a-protocol.org/</a> &amp; <a href="https://modelcontextprotocol.io/docs/2026-07-28/getting-started/intro">https://modelcontextprotocol.io/docs/2026-07-28/getting-started/intro</a></li><li><strong>Runnable Companion GitHub Repository (google-cloud-adk-order-to-cash-agent):</strong> <a href="https://github.com/aniketagrawal2012/google-cloud-adk-order-to-cash-agent">https://github.com/aniketagrawal2012/google-cloud-adk-order-to-cash-agent</a> — including <a href="https://github.com/aniketagrawal2012/google-cloud-adk-order-to-cash-agent/blob/main/app/agent.py">app/agent.py</a>, <a href="https://github.com/aniketagrawal2012/google-cloud-adk-order-to-cash-agent/blob/main/app/agent_runtime_app.py">app/agent_runtime_app.py</a>, <a href="https://github.com/aniketagrawal2012/google-cloud-adk-order-to-cash-agent/blob/main/scripts/provision_context_cache.py">scripts/provision_context_cache.py</a>, <a href="https://github.com/aniketagrawal2012/google-cloud-adk-order-to-cash-agent/blob/main/scripts/verify_remote_agent_engine.py">scripts/verify_remote_agent_engine.py</a>, <a href="https://github.com/aniketagrawal2012/google-cloud-adk-order-to-cash-agent/blob/main/tests/eval/eval_config.yaml">tests/eval/eval_config.yaml</a>, <a href="https://github.com/aniketagrawal2012/google-cloud-adk-order-to-cash-agent/blob/main/tests/eval/datasets/basic-dataset.json">tests/eval/datasets/basic-dataset.json</a>, and <a href="https://github.com/aniketagrawal2012/google-cloud-adk-order-to-cash-agent/blob/main/pyproject.toml">pyproject.toml</a>.</li><li><strong>Official Google Cloud ADK Recipes &amp; Samples Repository:</strong> <a href="https://github.com/google/adk-recipes">https://github.com/google/adk-recipes</a></li></ol><h3>11. About the Author, Related Reading &amp; Open-Source Blueprint</h3><p><strong>Aniket Agrawal</strong> is an AI Cloud Engineer &amp; GenAI Architect at Google (IIT CSE Grad) specializing in production multi-agent orchestration, Google Cloud security, context engineering, and state-verifying LLMOps.</p><ul><li><strong>Connect on LinkedIn:</strong> <a href="https://www.linkedin.com/in/aniket-agrawal-a18990266/">linkedin.com/in/aniket-agrawal-a18990266</a></li><li><strong>Star &amp; Clone the Companion GitHub Repository:</strong> <a href="https://github.com/aniketagrawal2012/google-cloud-adk-order-to-cash-agent">github.com/aniketagrawal2012/google-cloud-adk-order-to-cash-agent</a> (GitHub Profile: <a href="https://github.com/aniketagrawal2012">@aniketagrawal2012</a>)</li><li><strong>Interactive Web Blueprint (GitHub Pages):</strong> <a href="https://aniketagrawal2012.github.io/google-cloud-adk-order-to-cash-agent/">aniketagrawal2012.github.io/google-cloud-adk-order-to-cash-agent</a></li><li><strong>Follow on X (Twitter):</strong> <a href="https://x.com/Aniketagra29373">@Aniketagra29373</a></li><li><strong>Follow on Medium:</strong> <a href="https://medium.com/@aniketagrawal_14703">@aniketagrawal_14703</a></li></ul><p><strong>More Production AI &amp; Google Cloud Architecture Deep Dives by Aniket Agrawal:</strong></p><ul><li><a href="https://medium.com/google-cloud/beyond-llm-as-a-judge-the-dawn-of-agent-as-a-judge-a3j-for-enterprise-ai-f54781a00cbf">Beyond LLM-as-a-Judge: The Dawn of Agent-as-a-Judge (A3J) for Enterprise AI</a></li><li><a href="https://medium.com/google-cloud/the-graphrag-triangulation-why-frontier-gemini-swarms-need-agent-as-a-judge-to-conquer-enterprise-a992467c4b95">The GraphRAG Triangulation: Why Frontier Gemini Swarms Need Agent-as-a-Judge to Conquer Enterprise</a></li><li><a href="https://medium.com/google-cloud/architecting-agent-led-escalation-in-generative-ai-03136849f3cb">Architecting Agent-Led Escalation in Generative AI</a></li><li><a href="https://medium.com/google-cloud/confused-deputy-attack-on-cloud-run-4e4037d8fc5d">“Confused Deputy Attack” on Cloud Run</a></li></ul><p><em>Found this production blueprint valuable? Hold down the </em><strong><em>Clap</em></strong><em> button (up to </em><strong><em>50x</em></strong><em>!), save the 10-point checklist for your next architecture review, and star </em><a href="https://github.com/aniketagrawal2012/google-cloud-adk-order-to-cash-agent"><em>google-cloud-adk-order-to-cash-agent</em></a><em> on GitHub. Which guardrail — pre-LLM SDP redaction, SHA-256 loop breaking, or Cloud Spanner compensating sagas — are you shipping first? Share your experience in the comments below.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f73dfcc08f73" width="1" height="1" alt=""><hr><p><a href="https://medium.com/google-cloud/why-90-of-ai-agents-fail-in-production-architecting-a-self-healing-multi-agent-system-on-google-f73dfcc08f73">Why 90% of AI Agents Fail in Production: Architecting a Self-Healing Multi-Agent System on Google…</a> was originally published in <a href="https://medium.com/google-cloud">Google Cloud - Community</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The GraphRAG Triangulation: Why Frontier Gemini Swarms Need Agent-as-a-Judge to Conquer Enterprise…]]></title>
            <link>https://medium.com/google-cloud/the-graphrag-triangulation-why-frontier-gemini-swarms-need-agent-as-a-judge-to-conquer-enterprise-a992467c4b95?source=rss-13a446e68524------2</link>
            <guid isPermaLink="false">https://medium.com/p/a992467c4b95</guid>
            <category><![CDATA[google]]></category>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[knowledge-graph]]></category>
            <category><![CDATA[google-cloud-platform]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Aniket Agrawal]]></dc:creator>
            <pubDate>Fri, 04 Sep 2026 02:09:10 GMT</pubDate>
            <atom:updated>2026-09-04T02:09:10.735Z</atom:updated>
            <content:encoded><![CDATA[<h3>The GraphRAG Triangulation: Why Frontier Gemini Swarms Need Agent-as-a-Judge to Conquer Enterprise Reality?</h3><h4>From the author of “The AI Litmus Test 2.0” and “Beyond LLM-as-a-Judge” — how unifying Neo4j Knowledge Graphs, Google ADK Multi-Agent Swarms, and Vertex AI with Gemini creates an unbreakable, self-healing substrate for mission-critical AI.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cN1g2omt1irvoXV4sm7IWg.png" /><figcaption>The GraphRAG Triangulation: Why Frontier Gemini Swarms Need Agent-as-a-Judge to Conquer Enterprise Reality?</figcaption></figure><h3>1. The Reality Check After the “Vibes” Era</h3><p>In our previous deep-dive, <a href="https://medium.com/google-cloud/beyond-llm-as-a-judge-the-dawn-of-agent-as-a-judge-a3j-for-enterprise-ai-f54781a00cbf"><strong>Beyond LLM-as-a-Judge: The Dawn of Agent-as-a-Judge (A3J) for Enterprise AI</strong></a>, we exposed the fatal flaw of traditional LLMOps: <strong>LLMs are inherently polite, agreeable, and gullible evaluators</strong>. When evaluating complex agentic trajectories, a passive LLM judge acts like an uncritical reading comprehension tester — if the final answer looks structured, fluent, and professional, it awards a perfect score, completely oblivious to whether the underlying database state was corrupted or if an impossible action was taken.</p><p><strong>Please check my source code:</strong></p><ul><li><a href="https://github.com/GoogleCloudPlatform/generative-ai/tree/main/gemini/evaluation/agent_as_a_judge_eval.ipynb">Agent-as-a-Judge Evaluation Notebook (GitHub)</a></li><li><a href="https://github.com/GoogleCloudPlatform/generative-ai/blob/main/gemini/evaluation/multi_agent_state_verification_eval.ipynb">Multi-Agent State Verification Notebook (GitHub)</a></li><li>Stay tuned for the entire repo for this blog!</li></ul><p>In our community articles on <a href="https://discuss.google.dev/t/the-ai-litmus-test-2-0-scientifically-evaluating-genai-swarms-with-agent-as-a-judge-vertex-ai/371661"><strong>The AI Litmus Test 2.0</strong></a><strong> </strong>and <a href="https://discuss.google.dev/t/building-agentic-graphrag-on-vertex-ai-part-1-architecture-development-with-neo4j/328329"><strong>Building Agentic GraphRAG on Vertex AI</strong></a>, we demonstrated how autonomous worker swarms built on the Google Agent Development Kit (ADK) can navigate structured graph databases like Neo4j.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FKmLpTzXqxunmzJ40WMIfA.png" /><figcaption><strong>Figure: End-to-End Live Synchronization on Google Cloud Vertex AI.</strong> <em>Left:</em> Google ADK 2.3.0 Web UI (:8001) showing dynamic swarm delegation to IndiaTechCorridorSpecialist and Gemini reasoning traces. <em>Right:</em> Executive Mission Control (:8000) displaying real-time GraphRAG topology DAG traversal, A3J multi-dimensional radar metrics, and automated CI/CD safety gating (ALLOW_DEPLOYMENT)</figcaption></figure><p>As the industry embraces next-generation frontier models — from <strong>Gemini 2.5 Flash</strong> up through the ultra-low-latency <strong>Gemini 3.x Flash and Pro</strong> series on Google Cloud Vertex AI — enterprise teams are encountering a deeper question:</p><p><strong>“Where does GraphRAG fit into the evaluation debate? Is GraphRAG just for retrieval, or is it the missing ground-truth substrate that makes Agent-as-a-Judge actually work?”</strong></p><p>Putting together state-of-the-art tools without architectural harmony is like assembling world-class culinary ingredients into an unpalatable dish. Just because you have a frontier LLM, a graph database, and an agent framework does not mean you have a robust enterprise system.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CpKGMeycY1cFVPYXWAEL3Q.png" /><figcaption>Master Hero Infographic: Neo4j and Google Cloud Platform (Vertex AI)</figcaption></figure><p>This article explores the <strong>four distinct evolutionary paradigms of enterprise AI evaluation</strong>, establishes which enterprise use cases are truly friendly to GraphRAG and Agent-as-a-Judge, and demonstrates how Google Cloud Vertex AI enables a <strong>closed-loop, self-healing architecture</strong>.</p><h3>2. The Missing Keystone: Why GraphRAG is the Substrate of Truth</h3><p>Standard Retrieval-Augmented Generation (Vector RAG) converts text documents into dense numerical vector embeddings and performs cosine similarity lookups.</p><p>Vector RAG answers the question: <strong>“What text chunks sound semantically similar to this user prompt?”</strong></p><p>In mission-critical enterprise systems, semantic similarity is not enough. You need to answer:</p><ul><li><strong>“Is Node A physically or legally connected to Node B through a valid directed relationship?”</strong></li><li><strong>“Does this multi-hop path satisfy temporal schedules, regulatory limits, and geographic constraints?”</strong></li><li><strong>“Under a Closed-World Assumption, does an asserted edge physically exist in our verified ledger?”</strong></li></ul><p>This is where <strong>Knowledge Graphs and GraphRAG</strong> become the foundation of truth. A Knowledge Graph represents your enterprise domain as typed entities (nodes) connected by explicit, property-weighted relationships (edges).</p><p>When paired with <strong>Gemini on Vertex AI</strong>, GraphRAG does not just retrieve loose paragraphs of text — it extracts <strong>deterministic subgraphs and structural triples</strong> before the model generates a single token.</p><h3>3. The 4-Way Evaluation Battleground</h3><p>To understand where improvements are maximized, let us break down the four evolutionary paradigms:</p><h4>Paradigm 1: LLM-as-a-Judge (The Naive Baseline)</h4><ul><li><strong>How It Works</strong>: Candidate response text is passed to an LLM evaluator with a generic scoring rubric.</li><li><strong>The Fatal Flaw</strong>: The judge is blind to intermediate API calls, tool outputs, and physical reality. It evaluates linguistic elegance rather than factual ground truth. If a worker agent asserts an impossible claim fluently, LLM-as-a-Judge gives it top marks.</li><li><strong>Best Used For</strong>: Low-risk conversational summaries, creative copy tone checks, and general sentiment analysis.</li></ul><h4>Paradigm 2: LLM-as-a-Judge + GraphRAG (Grounded Generation, Blind Evaluation)</h4><ul><li><strong>How It Works</strong>: The worker agent uses GraphRAG to query a Neo4j knowledge graph, but the evaluation pipeline remains a passive, text-only LLM judge.</li><li><strong>The Fatal Flaw</strong>: While GraphRAG dramatically reduces hallucinations during generation, the evaluation layer still has no way to verify whether the agent actually respected the graph constraints or made up a relationship during synthesis.</li><li><strong>Best Used For</strong>: Internal enterprise search engines and documentation portals where human reviewers are always in the loop.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*neSZHqP34hnp_0EbtAELpg.jpeg" /><figcaption>Comparison of AI Evaluation Paradigms — evaluation_matrix_infographic</figcaption></figure><h4>Paradigm 3: Agent-as-a-Judge (Active Tool Auditing, Flat Context)</h4><ul><li><strong>How It Works</strong>: An autonomous evaluating agent equipped with programmatic inspection tools (e.g., querying relational SQL databases or checking API response payloads) verifies whether actions occurred.</li><li><strong>The Fatal Flaw</strong>: Without a structured Knowledge Graph, the judge can only check isolated database rows or binary status codes. It cannot verify complex, multi-hop transitive dependencies or detect indirect topological contradictions.</li><li><strong>Best Used For</strong>: Single-hop transactional workflows, such as verifying whether a payment gateway returned a success token or if a booking ID exists in a table.</li></ul><h4>Paradigm 4: Agent-as-a-Judge + GraphRAG (The Enterprise Gold Standard)</h4><ul><li><strong>How It Works</strong>: The worker swarm generates multi-modal plans using GraphRAG. The <strong>Agent-as-a-Judge (A3J)</strong> evaluator actively queries the Knowledge Graph, executes deterministic graph traversal algorithms (such as Dijkstra shortest-path reachability), and cross-examines every asserted relation against the ground-truth topology under Closed-World Assumptions.</li><li><strong>The Breakthrough</strong>: The judge calculates exact mathematical metrics — such as <strong>Topological Hallucination Divergence (THD)</strong> and <strong>Step Efficiency (SE)</strong> — to deterministically catch semantic, relational, and cross-border hallucinations, triggering automated CI/CD deployment gates.</li><li><strong>Best Used For</strong>: Mission-critical autonomous swarms in logistics, capital markets, cybersecurity, and global transit networks.</li></ul><h3>4. The Enterprise Fit Spectrum: Which Use Cases Are Friendly vs. Unfriendly?</h3><p>Deploying a full GraphRAG plus Agent-as-a-Judge stack introduces graph schema maintenance and multi-agent coordination overhead. It is critical to know where this architecture delivers exponential ROI and where it is over-engineering.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*f0IhAMMYKgBsnnxF5lozcQ.jpeg" /><figcaption>The Enterprise Fit Spectrum — usecase_fit_spectrum</figcaption></figure><h4>🟢 Highly Friendly Use Cases (Where GraphRAG + A3J Dominates)</h4><p><strong>1. Multi-Modal Global Transit &amp; Sovereign Corridor Routing</strong></p><ul><li><strong>Domain Reality</strong>: Global transit networks are physical multigraphs. Cities, rail hubs, airports, and corporate campuses are nodes; flight corridors, high-speed rail lines, and autonomous EV fleets are directed edges with strict timetable and elevation bounds.</li><li><strong>The Challenge</strong>: Pure LLMs hallucinate non-existent ground links across oceans (e.g., claiming a 30-minute bullet train connects California to India).</li><li><strong>The Graph-A3J Solution</strong>: The A3J auditor runs shortest-path verification against the transit graph, immediately detects infinite topological distance across oceanic barriers, flags the divergence, and blocks the ungrounded itinerary.</li></ul><p><strong>2. Corporate Governance, Multi-Tier Holdings &amp; Regulatory Compliance</strong></p><ul><li><strong>Domain Reality</strong>: Enterprise holding structures (e.g., Tata Sons, Alphabet, conglomerate parent-subsidiary networks) involve complex multi-tiered equity paths and regulatory thresholds (e.g., SEBI SAST 25% takeover triggers).</li><li><strong>The Challenge</strong>: Standard RAG flattens corporate filings into chunks, missing multi-hop ultimate beneficial ownership (UBO) chains.</li><li><strong>The Graph-A3J Solution</strong>: GraphRAG maps the exact corporate hierarchy, while A3J verifies equity ownership paths against real-time regulatory ledgers.</li></ul><p><strong>3. Cyber-Physical Threat Intelligence &amp; SCADA/OT Kill Chains</strong></p><ul><li><strong>Domain Reality</strong>: Threat actors, CVE vulnerabilities, malware signatures, and industrial control protocols form deep, multi-stage kill chains.</li><li><strong>The Challenge</strong>: Evaluating whether a complex 6-hop attack trace (e.g., APT29 zero-day exploiting CVE-2024–38812 → Process Hollowing → Domain Controller → RTU Telecontrol Unit via IEC-60870–5–104) is authentic requires verifying exact protocol standards.</li><li><strong>The Graph-A3J Solution</strong>: The A3J evaluator queries MITRE ATT&amp;CK STIX 2.1 knowledge graphs to mathematically audit the structural validity of the kill chain.</li></ul><p><strong>4. Pharmaceutical Drug-Drug Interactions &amp; Biochemical Pathways</strong></p><ul><li><strong>Domain Reality</strong>: Metabolic pathways, contraindications, and molecular targets are strict scientific relationships where hallucinations can be life-threatening.</li><li><strong>The Challenge</strong>: Pure LLMs often generate plausible-sounding medical advice that contradicts biochemical ground truth.</li><li><strong>The Graph-A3J Solution</strong>: GraphRAG traverses biomedical ontologies, while A3J checks contraindication paths before approving patient treatment plans.</li></ul><h4>🔴 Unfriendly Use Cases (Where GraphRAG + A3J Is Over-Engineering)</h4><ul><li><strong>Creative Marketing Copywriting &amp; Social Media Ad Generation</strong>: Tone, humor, and engagement do not map to graph nodes or shortest paths. Standard LLM-as-a-Judge or human review is faster and cheaper.</li><li><strong>Unstructured Sentiment Analysis &amp; Brand Perception</strong>: Classifying customer reviews into positive, neutral, or negative categories is a standard classification problem that gains zero value from graph traversals.</li><li><strong>Open-Domain Brainstorming &amp; Casual Chit-Chat</strong>: Open-ended ideation has no fixed ground truth or closed-world bounds. Imposing strict graph reachability checks will actively break the creative utility of the model.</li></ul><h3>5. Architectural Harmony on Google Cloud Vertex AI</h3><p>To make these technologies work together seamlessly, we designed a unified architecture powered by Google Cloud:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BhUkWIM4hrop0w17sxbLpA.jpeg" /><figcaption>Google Cloud Vertex AI Enterprise Swarms Architecture — Vertex AI Graph Architecture</figcaption></figure><h4>Key Engineering Components:</h4><ol><li><strong>Google Agent Development Kit (ADK)</strong>: Manages clean, stateful sub-agent handoffs via native delegation protocols (transfer_to_agent), allowing specialized worker agents to focus strictly on their domain tools.</li><li><strong>Vertex AI Reasoning Engine</strong>: Serves as the managed, enterprise-grade runtime hosting the agent logic, handling authentication, serialization, and sub-second execution SLAs.</li><li><strong>Gemini 2.5 / 3.x Flash</strong>: Provides rapid reasoning, multi-modal contextual understanding, and grounded generation without incurring high inference latency.</li><li><strong>Neo4j Knowledge Graph</strong>: Operates as the immutable structural ground truth, queried via optimized Cypher subgraphs in 120ms.</li><li><strong>Agent-as-a-Judge (A3J) Auditor</strong>: Evaluates Algorithm 1 (Dijkstra Shortest-Path Proof) to convert natural language assertions into mathematical edge validations, calculating divergence scores with zero subjective guesswork.</li></ol><h3>6. The Autonomous Self-Healing Breakthrough: Minimum Steiner-Tree Auto-Repair</h3><p>What happens when an agent makes an ungrounded or contradictory assertion? In legacy architectures, the execution fails, an alert is triggered, and a human engineer must intervene.</p><p>By combining Knowledge Graphs with Agent-as-a-Judge, we unlock <strong>closed-loop autonomous self-healing</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZaO-lKEampXSdyzsQutCmA.jpeg" /><figcaption>Autonomous Closed-Loop Self-Healing with Minimum Steiner Tree — steiner_tree_autoheal_flow</figcaption></figure><h4>The 4-Step Self-Healing Progression:</h4><ol><li><strong>Topological Contradiction Detected</strong>: A worker agent asserts an impossible path (e.g., a direct ground rail link across an ocean).</li><li><strong>A3J Intercept</strong>: The judge catches the infinite topological distance and trips the CI/CD circuit breaker to TERMINATE_AND_BLOCK.</li><li><strong>Algorithm 2 (Minimum Steiner Tree)</strong>: The <strong>SteinerTreeAutoHealSpecialist</strong> analyzes the disconnected graph components, searches the global graph adjacency matrix, and identifies the optimal intermediate bridge nodes (e.g., finding the necessary international aviation hubs to bridge the gap).</li><li><strong>Live Re-Synthesis with Gemini</strong>: The discovered Steiner path is passed back to Gemini, which reconstructs a valid, grounded multi-hop itinerary.</li><li><strong>Automated Re-Audit</strong>: The A3J auditor re-evaluates the newly generated path, confirms that divergence has dropped to zero, and automatically updates the deployment gate to AUTO-HEALED &amp; DEPLOYED.</li></ol><p>This is the transition from <strong>passive evaluation</strong> to <strong>active, self-correcting autonomous resilience</strong>.</p><h3>7. Production Benchmark Findings</h3><p>Across comprehensive evaluation benchmarks comprising 1,000 multi-domain traces across cybersecurity, financial forensics, and multi-modal transit:</p><ul><li><strong>Detection Accuracy (ROC-AUC)</strong>: <strong>0.9967</strong> (representing a <strong>+23.9% improvement</strong> over context-aware LLM-as-a-Judge baselines).</li><li><strong>Adversarial False Approval Rate</strong>: <strong>0.0%</strong> (zero false approvals across trans-oceanic, cross-border, and semantic entity hallucinations).</li><li><strong>Statistical Rigor</strong>: McNemar’s test confirmed significant divergence reduction with a p-value below ten to the negative seventy-seventh power (p &lt; 10^{-77}).</li><li><strong>Cost Efficiency</strong>: Amortized evaluation cost dropped to <strong>$0.00042 per trace</strong> by replacing long LLM judge prompt chains with targeted subgraph traversals.</li></ul><h3>8. Summary: The Recipe for Production-Grade Enterprise AI</h3><p>To build autonomous agent swarms that enterprise risk officers and Chief Information Security Officers can trust, we must combine the right ingredients in harmony:</p><ul><li><strong>Use Gemini on Vertex AI</strong> for fast, flexible natural language reasoning.</li><li><strong>Use GraphRAG and Neo4j</strong> as the structured, immutable ground-truth substrate.</li><li><strong>Use Google ADK Swarms</strong> for modular, specialized multi-agent orchestration.</li><li><strong>Use Agent-as-a-Judge (A3J)</strong> to replace subjective reading comprehension with deterministic, tool-driven state verification.</li><li><strong>Use Steiner-Tree Auto-Healing</strong> to turn evaluation failures into automatic, self-correcting recovery pipelines.</li></ul><p>The era of trusting AI on “vibes” is officially behind us. The future of enterprise intelligence belongs to systems that are <strong>graph-grounded, agent-verified, and mathematically provable</strong>.</p><h3>References &amp; resources</h3><p><strong>My Previous Blogs:</strong></p><ul><li><a href="https://medium.com/google-cloud/beyond-llm-as-a-judge-the-dawn-of-agent-as-a-judge-a3j-for-enterprise-ai-f54781a00cbf">Beyond LLM-as-a-Judge: The Dawn of Agent-as-a-Judge (A3J) for Enterprise AI</a></li><li><a href="https://discuss.google.dev/t/the-ai-litmus-test-scientifically-evaluating-genai-playbook-agents/340720">The AI Litmus Test: Scientifically Evaluating GenAI Playbook Agents (Agrawal, 2026)</a></li><li><a href="https://discuss.google.dev/t/the-ai-litmus-test-2-0-scientifically-evaluating-genai-swarms-with-agent-as-a-judge-vertex-ai/371661">The AI Litmus Test 2.0: Scientifically evaluating GenAI Swarms with Agent-as-a-Judge &amp; Vertex AI (Agrawal, 2026)</a></li><li><a href="https://discuss.google.dev/t/building-agentic-graphrag-on-vertex-ai-part-1-architecture-development-with-neo4j/328329">Building Agentic GraphRAG on Vertex AI: Part 1 — Architecture &amp; development with Neo4j</a> <a href="https://discuss.google.dev/t/the-ai-litmus-test-2-0-scientifically-evaluating-genai-swarms-with-agent-as-a-judge-vertex-ai/371661">(Agrawal, 2026)</a></li></ul><p><strong>My Source Code:</strong></p><ul><li><a href="https://github.com/GoogleCloudPlatform/generative-ai/tree/main/gemini/evaluation/agent_as_a_judge_eval.ipynb">Agent-as-a-Judge Evaluation Notebook (GitHub)</a></li><li><a href="https://github.com/GoogleCloudPlatform/generative-ai/blob/main/gemini/evaluation/multi_agent_state_verification_eval.ipynb">Multi-Agent State Verification Notebook (GitHub)</a></li></ul><p><strong>Google Cloud documentation, links, and assets:</strong></p><ul><li><strong>Source Code:</strong> <a href="https://github.com/GoogleCloudPlatform/generative-ai/tree/main/gemini/evaluation/evaluating_adk_agent.ipynb">Evaluating ADK Agents with SDK Notebook (GitHub)</a></li><li><strong>Documentation:</strong> <a href="https://cloud.google.com/vertex-ai/docs/generative-ai/reasoning-engine/overview">Google Cloud Vertex AI Reasoning Engine</a></li><li><strong>Documentation:</strong> <a href="https://python.langchain.com/docs/integrations/graphs/neo4j_cypher">Neo4j Graph Database Integration with LangChain</a></li><li><strong>Documentation:</strong> <a href="https://cloud.google.com/vertex-ai/generative-ai/docs/models/determine-eval">Google Cloud Vertex AI Gen AI Evaluation Services</a></li></ul><p><strong>Algorithmic &amp; Theoretical Foundations:</strong></p><blockquote><strong>Algorithm 1 (Dijkstra Shortest-Path Proof &amp; Topological Verification)</strong>:</blockquote><ul><li>Dijkstra, E. W. (1959). <em>“A note on two problems in connexion with graphs.”</em> <strong>Numerische Mathematik</strong>, 1(1), 269–271. <a href="https://doi.org/10.1007/BF01386390">doi:10.1007/BF01386390</a>.</li><li>Reiter, R. (1978). <em>“On Closed World Data Bases.”</em> In <strong>Logic and Data Bases</strong> (pp. 55–76). Springer, Boston, MA.</li></ul><blockquote><strong>Algorithm 2 (Minimum Steiner-Tree Autonomous Self-Healing &amp; Bridge Discovery)</strong>:</blockquote><ul><li>Kou, L., Markowsky, G., &amp; Berman, L. (1981). <em>“A fast algorithm for Steiner trees in graphs.”</em> <strong>Acta Informatica</strong>, 15(2), 141–145. <a href="https://doi.org/10.1007/BF00288961">doi:10.1007/BF00288961</a>.</li><li>Dreyfus, S. E., &amp; Wagner, R. A. (1971). <em>“The Steiner problem in graphs.”</em> <strong>Networks</strong>, 1(3), 195–207.</li></ul><blockquote><strong>GraphRAG &amp; Knowledge Graph Subgraph Reasoning</strong>:</blockquote><ul><li>Edge, D., Trinh, H., Cheng, N., Bradley, J., Chao, A., Mody, A., Truitt, S., &amp; Larson, J. (2024). <em>“From Local to Global: A Graph RAG Approach to Query-Focused Summarization.”</em> <strong>Microsoft Research</strong>, <a href="https://arxiv.org/abs/2404.16130">arXiv:2404.16130</a>.</li><li>Hogan, A., Blomqvist, E., Cochez, M., d’Amato, C., de Melo, G., Gutierrez, C., … &amp; Zimmermann, A. (2021). <em>“Knowledge Graphs.”</em> <strong>ACM Computing Surveys (CSUR)</strong>, 54(4), 1–37.</li></ul><blockquote><strong>Agent-as-a-Judge (A3J) &amp; Multi-Agent Trajectory Evaluation</strong>:</blockquote><ul><li>Zhuge, M., Gao, H., Wang, B., Zhang, X., Wu, C., &amp; Wang, Y. (2024). <em>“Agent-as-a-Judge: Evaluate Agents with Agents.”</em> <a href="https://arxiv.org/abs/2410.10934">arXiv:2410.10934</a>.</li><li>Zheng, L., Chiang, W. L., Sheng, Y., Zhuang, S., Wu, Z., Zhuang, Y., Lin, Z., Li, Z., Li, D., Xing, E. P., Zhang, H., Gonzalez, J. E., &amp; Stoica, I. (2023). <em>“Judging LLM-as-a-Judge with MT-Bench and Chatbot Arena.”</em> <strong>NeurIPS 2023</strong>, <a href="https://arxiv.org/abs/2306.05685">arXiv:2306.05685</a>.</li></ul><p>We can’t wait to see what you build. Share your creations and ask questions in the Google Cloud Community. Happy coding!</p><p><strong>What failure modes have you encountered with LLM-as-a-Judge in production? Share your experiences and thoughts in the comments below!</strong></p><p><strong>Note:</strong> <em>Should you have any concerns or queries about this post or my implementation, please feel free to connect with me on </em><a href="https://www.linkedin.com/in/aniket-agrawal-a18990266/"><em>LinkedIn</em></a><em>! Thanks!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a992467c4b95" width="1" height="1" alt=""><hr><p><a href="https://medium.com/google-cloud/the-graphrag-triangulation-why-frontier-gemini-swarms-need-agent-as-a-judge-to-conquer-enterprise-a992467c4b95">The GraphRAG Triangulation: Why Frontier Gemini Swarms Need Agent-as-a-Judge to Conquer Enterprise…</a> was originally published in <a href="https://medium.com/google-cloud">Google Cloud - Community</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Beyond LLM-as-a-Judge: The Dawn of Agent-as-a-Judge (A3J) for Enterprise AI]]></title>
            <link>https://medium.com/google-cloud/beyond-llm-as-a-judge-the-dawn-of-agent-as-a-judge-a3j-for-enterprise-ai-f54781a00cbf?source=rss-13a446e68524------2</link>
            <guid isPermaLink="false">https://medium.com/p/f54781a00cbf</guid>
            <category><![CDATA[large-language-models]]></category>
            <category><![CDATA[agentic-ai]]></category>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[generative-ai-tools]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Aniket Agrawal]]></dc:creator>
            <pubDate>Sat, 13 Jun 2026 02:15:43 GMT</pubDate>
            <atom:updated>2026-06-21T09:03:11.934Z</atom:updated>
            <content:encoded><![CDATA[<p><em>We are moving past “vibes-based” development. It’s time for rigorous, state-verifying LLMOps.</em></p><p>If you are building autonomous AI agents for the enterprise, you have likely hit the evaluation wall.</p><p>You’ve moved past simple RAG chatbots. You are now orchestrating multi-agent swarms that execute code, query live databases, and trigger real-world financial transactions. Yet, when it comes to evaluating these complex systems in your CI/CD pipelines, the industry is still relying on a fundamentally flawed paradigm: <strong>LLM-as-a-Judge</strong>.</p><p><strong>Please check my source code:</strong></p><ul><li><a href="https://github.com/GoogleCloudPlatform/generative-ai/tree/main/gemini/evaluation/agent_as_a_judge_eval.ipynb">Agent-as-a-Judge Evaluation Notebook (GitHub)</a></li><li><a href="https://github.com/GoogleCloudPlatform/generative-ai/blob/main/gemini/evaluation/multi_agent_state_verification_eval.ipynb">Multi-Agent State Verification Notebook (GitHub)</a></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Cr4ej6ayN5MhvNfsjceLWg.jpeg" /><figcaption>This image says it all about A3J!</figcaption></figure><p><strong>LLM-as-a-Judge</strong> is essentially a sophisticated reading comprehension test. You pass the execution log to a model like GPT-4 or Gemini and ask, <em>&quot;Did the agent do a good job?&quot;</em></p><p>But here is the billion-dollar problem: <strong>LLMs are gullible.</strong> If a worker agent hallucinates and writes, <em>&quot;I successfully booked the freight capacity for ₹25,000,&quot;</em> an LLM Judge will read that text, believe it, and pass the build.</p><p>Enter the next evolution of AI evaluation: <strong>Agent-as-a-Judge (A3J)</strong>.</p><h3>The Anatomy of a Hallucination</h3><p>To understand why A3J is necessary, let&#39;s look at a real-world enterprise scenario. Imagine an <strong>Autonomous Global Supply-Chain Agent</strong> tasked with routing logistics from <em>NODE_BOM_MUMBAI</em> to <em>HUB_BLR_BENGALURU</em>.</p><p>The agent has a tool: <em>reserve_freight_capacity(carrier_id, weight, auth_token)</em>.</p><p>A user asks the agent to urgently reserve 5,000 kg of freight on a trucking carrier that only has a 4,500 kg capacity limit.</p><p><strong>What happens next is the nightmare of every AI Engineer:</strong></p><ol><li>The Worker Agent calls the tool with 5000kg.</li><li>The backend system rightfully rejects it: <em>{&quot;status&quot;: &quot;REJECTED&quot;, &quot;error&quot;: &quot;INSUFFICIENT_CAPACITY&quot;}</em>.</li><li>The Worker Agent’s LLM, eager to please the user, ignores the error payload and hallucinates the final output: <em>&quot;Great news! I have successfully reserved 5,000 kg of freight capacity for your shipment.&quot;</em></li></ol><p>If you use <strong>LLM-as-a-Judge</strong> to evaluate this trace, it reads the final output, assumes the task was completed, and awards a score of 10/10. Your pipeline deploys a broken agent to production.</p><h3>The Paradigm Shift: Agent-as-a-Judge (A3J)</h3><p><strong>Agent-as-a-Judge (A3J)</strong> fundamentally changes the rules of engagement. Instead of using a static, zero-shot prompt to grade text, A3J deploys an <em>autonomous evaluating agent equipped with its own tools</em>.</p><p>An A3J evaluator doesn&#39;t trust the worker&#39;s text. It verifies the <strong>system state</strong>.</p><p>In our logistics example, the A3J evaluator is given a tool called <em>verify_ledger_integrity()</em>. When it evaluates the worker&#39;s trajectory, it actively queries the backend relational database. It sees that the worker <em>claimed</em> to book the capacity, but the SQL ledger returns 0 rows.</p><p>The A3J system instantly catches the semantic hallucination, flags the catastrophic failure, and triggers a <em>TERMINATE_AND_BLOCK</em> command to the CI/CD gatekeeper.</p><h4>The Evaluation Evolution Matrix</h4><p>Where does A3J fit in the modern stack? Here is how the frameworks compare:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cbWHjOFvw8Hx8jyD2FZQeA.png" /><figcaption>The Evaluation Evolution Matrix</figcaption></figure><h3>Building the Gold Standard A3J Engine</h3><p>To implement this mathematically and programmatically, we define a composite evaluation scoring formula. A robust A3J system doesn&#39;t just return a <em>&quot;thumbs up.&quot;</em> It returns a structured scorecard:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/634/1*OMTgYkvJWOncAZDiiYawcw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5CTFiAmlnZvkLdt57IYoZQ.png" /><figcaption>The Composite Evaluation Scoring Formula and its conditions</figcaption></figure><ul><li><strong>ARS (Adversarial Robustness Score):</strong> Did the agent resist prompt-injection attacks?</li><li><strong>FCS (Fiduciary Compliance Score):</strong> Did the agent adhere to pricing floors (e.g., the ₹25,000 minimum tariff)?</li><li><strong>SVA (State Verification Accuracy):</strong> Did the database state actually change?</li></ul><p>Here is what the architecture of a true A3J Judge looks like using Pydantic and the Vertex AI SDK (Section 9 of <a href="https://github.com/GoogleCloudPlatform/generative-ai/blob/main/gemini/evaluation/multi_agent_state_verification_eval.ipynb">my GitHub notebook</a>):</p><pre>from pydantic import BaseModel, Field<br><br>class JudgeOutputSchema(BaseModel):<br>    adversarial_robustness_score: float = Field(..., ge=0.0, le=1.0)<br>    fiduciary_compliance_score: float = Field(..., ge=0.0, le=1.0)<br>    state_verification_accuracy: float = Field(..., ge=0.0, le=1.0)<br>    isolated_audit_justification: str<br>    recommended_cicd_gate_action: str # &quot;ALLOW_DEPLOYMENT&quot; | &quot;TERMINATE_AND_BLOCK&quot;<br><br>class MultiAgentStateVerifyingJudge:<br>    def __init__(self, target_engine):<br>        self.engine_handle = target_engine<br>        <br>    def execute_state_tool_audit(self, trace) -&gt; JudgeOutputSchema:<br>        # 1. ACTIVE TOOL EXECUTION: Query raw database, ignore agent text<br>        ledger_snapshots = self.engine_handle.verify_ledger_integrity()<br>        <br>        # 2. Extract claims from the Agent&#39;s text output<br>        claims_allocation = &quot;successfully allocated&quot; in trace.serialize_trace_to_json()<br>        <br>        # 3. Ground Truth Verification<br>        actual_allocations_committed = any(<br>            txn[&quot;action&quot;] == &quot;CAPACITY_RESERVATION&quot; for txn in ledger_snapshots<br>        )<br>        <br>        # 4. Synthesize the Audit<br>        if claims_allocation and not actual_allocations_committed:<br>            return JudgeOutputSchema(<br>                adversarial_robustness_score=1.0,<br>                fiduciary_compliance_score=0.0,<br>                state_verification_accuracy=0.0,<br>                isolated_audit_justification=&quot;HALLUCINATION CAUGHT: Agent text asserted allocation, but live ledger query returns 0 rows.&quot;,<br>                recommended_cicd_gate_action=&quot;TERMINATE_AND_BLOCK&quot;<br>            )<br>            <br>        return JudgeOutputSchema(<br>            adversarial_robustness_score=1.0,<br>            fiduciary_compliance_score=1.0,<br>            state_verification_accuracy=1.0,<br>            isolated_audit_justification=&quot;VALIDATION SUCCESSFUL: Tool trajectories align fully with downstream state commits.&quot;,<br>            recommended_cicd_gate_action=&quot;ALLOW_DEPLOYMENT&quot;<br>        )</pre><h3>The CI/CD Integration</h3><p>The beauty of enforcing strict Pydantic JSON schemas in your A3J output is that it integrates flawlessly into modern CI/CD pipelines (like GitHub Actions or GitLab CI).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MW5JvLV5VfKu6LGEz6Qlzw.jpeg" /></figure><p>Instead of parsing messy Markdown responses from a standard LLM, your pipeline runner simply asserts:</p><pre>if evaluation_json[&quot;recommended_cicd_gate_action&quot;] == &quot;TERMINATE_AND_BLOCK&quot;: exit(1)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1rYY844a_SKczq523IygZA.png" /></figure><h3>Conclusion</h3><p>If your enterprise AI is modifying database states, shifting money, or booking assets, you cannot rely on text-based grading.</p><p>The transition from <em>LLM-as-a-Judge</em> to <em>Agent-as-a-Judge</em> is the transition from <strong>hope to engineering</strong>. By giving your evaluators the tools to verify ground truth, you close the hallucination loop and build automated deployment gates you can actually trust.</p><p>Welcome to the era of transactional swarms.</p><h3>References &amp; resources</h3><p><strong>My Previous Blogs:</strong></p><ul><li><a href="https://discuss.google.dev/t/the-ai-litmus-test-scientifically-evaluating-genai-playbook-agents/340720">The AI Litmus Test: Scientifically Evaluating GenAI Playbook Agents (Agrawal, 2026)</a></li><li><a href="https://discuss.google.dev/t/the-ai-litmus-test-2-0-scientifically-evaluating-genai-swarms-with-agent-as-a-judge-vertex-ai/371661">The AI Litmus Test 2.0: Scientifically evaluating GenAI Swarms with Agent-as-a-Judge &amp; Vertex AI (Agrawal, 2026)</a></li><li><a href="https://discuss.google.dev/t/building-agentic-graphrag-on-vertex-ai-part-1-architecture-development-with-neo4j/328329">Building Agentic GraphRAG on Vertex AI: Part 1 — Architecture &amp; development with Neo4j</a> <a href="https://discuss.google.dev/t/the-ai-litmus-test-2-0-scientifically-evaluating-genai-swarms-with-agent-as-a-judge-vertex-ai/371661">(Agrawal, 2026)</a></li></ul><p><strong>My Source Code:</strong></p><ul><li><a href="https://github.com/GoogleCloudPlatform/generative-ai/tree/main/gemini/evaluation/agent_as_a_judge_eval.ipynb">Agent-as-a-Judge Evaluation Notebook (GitHub)</a></li><li><a href="https://github.com/GoogleCloudPlatform/generative-ai/blob/main/gemini/evaluation/multi_agent_state_verification_eval.ipynb">Multi-Agent State Verification Notebook (GitHub)</a></li></ul><p><strong>Other code, research, Google Cloud documentation, links, and assets:</strong></p><ul><li><strong>Source Code:</strong> <a href="https://github.com/GoogleCloudPlatform/generative-ai/tree/main/gemini/evaluation/evaluating_adk_agent.ipynb">Evaluating ADK Agents with SDK Notebook (GitHub)</a></li><li><strong>Research:</strong> <a href="https://arxiv.org/abs/2306.05685">Judging LLM-as-a-Judge with MT-Bench (Zheng et al., 2023)</a></li><li><strong>Research:</strong> <a href="https://arxiv.org/abs/2309.15217">RAGAS: Automated Evaluation of Retrieval Augmented Generation (Es et al., 2023)</a></li><li><strong>Research:</strong> <a href="https://arxiv.org/abs/2410.10934">Agent-as-a-Judge: Evaluate Agents with Agents (Zhuge et al., 2024)</a></li><li><strong>Documentation:</strong> <a href="https://cloud.google.com/vertex-ai/docs/generative-ai/reasoning-engine/overview">Google Cloud Vertex AI Reasoning Engine</a></li><li><strong>Documentation:</strong> <a href="https://python.langchain.com/docs/integrations/graphs/neo4j_cypher">Neo4j Graph Database Integration with LangChain</a></li><li><strong>Documentation:</strong> <a href="https://cloud.google.com/vertex-ai/generative-ai/docs/models/determine-eval">Google Cloud Vertex AI Gen AI Evaluation Services</a></li><li><strong>APIs Used:</strong> <a href="https://open-meteo.com/">Open-Meteo</a>, <a href="https://www.frankfurter.app/">Frankfurter Forex</a>, <a href="https://restcountries.com/">RESTCountries</a></li></ul><p>We can’t wait to see what you build. Share your creations and ask questions in the Google Cloud Community. Happy coding!</p><p><strong>Let’s keep the conversation going! Share your thoughts, questions, and ideas in the comments.</strong></p><p><strong>Note:</strong> <em>Should you have any concerns or queries about this post or my implementation, please feel free to connect with me on </em><a href="https://www.linkedin.com/in/aniket-agrawal-a18990266/"><em>LinkedIn</em></a><em>! Thanks!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f54781a00cbf" width="1" height="1" alt=""><hr><p><a href="https://medium.com/google-cloud/beyond-llm-as-a-judge-the-dawn-of-agent-as-a-judge-a3j-for-enterprise-ai-f54781a00cbf">Beyond LLM-as-a-Judge: The Dawn of Agent-as-a-Judge (A3J) for Enterprise AI</a> was originally published in <a href="https://medium.com/google-cloud">Google Cloud - Community</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Architecting Agent-Led Escalation in Generative AI]]></title>
            <link>https://medium.com/google-cloud/architecting-agent-led-escalation-in-generative-ai-03136849f3cb?source=rss-13a446e68524------2</link>
            <guid isPermaLink="false">https://medium.com/p/03136849f3cb</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[chatbots]]></category>
            <category><![CDATA[google-cloud-platform]]></category>
            <category><![CDATA[vertex-ai]]></category>
            <dc:creator><![CDATA[Aniket Agrawal]]></dc:creator>
            <pubDate>Fri, 20 Mar 2026 05:59:13 GMT</pubDate>
            <atom:updated>2026-03-20T05:59:13.904Z</atom:updated>
            <content:encoded><![CDATA[<p>In high-stakes environments like banking and healthcare, the most dangerous thing an AI agent can do is guess. When dealing with a complex mortgage restructuring or a distressed patient, a hallucination isn’t just a poor user experience — it is a compliance violation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1UpTrUD6h-8tIhokhJJwnQ.png" /><figcaption>Architecture Diagram: Phase 1</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cx-fsSFPfYcwKj-s8P1CUw.png" /><figcaption>Architecture Diagram: Phase 2</figcaption></figure><p>Enterprise GenAI requires a paradigm shift: <strong>We must teach the AI to know what it does <em>not</em> know.</strong></p><p>While many chatbots rely on the user clicking a “Talk to a Human” button, true “Agentic AI” takes the initiative. In this deep dive, we will architect <strong>Agent-Led Escalation</strong> using Vertex AI Playbooks. We will build a system where the Large Language Model (LLM) autonomously monitors the conversation, recognizes its own limitations, and programmatically triggers a seamless handoff to a human agent, complete with a synthesized context summary.</p><h3>Part 1: The Concept of “Graceful Degradation”</h3><p>A production-grade AI system must fail safely. In conversational AI, “failing safely” means routing the user to a human operator before they become frustrated.</p><p>We achieve this by treating <strong>Human Escalation as an API Tool</strong>.</p><p>Instead of relying on fragile keyword matching (e.g., waiting for the user to type “manager”), we provide the Vertex AI Playbook with a specific Human_Handoff_Tool. We then use Prompt Engineering to define the exact business conditions under which the LLM should invoke this tool.</p><h4>The Escalation Triggers</h4><p>We can instruct the Playbook to escalate based on:</p><ol><li><strong>Sentiment:</strong> The user expresses anger or extreme distress.</li><li><strong>Complexity:</strong> The user asks a multi-part question that spans beyond the agent’s provided tools.</li><li><strong>Policy:</strong> The transaction value exceeds a defined threshold (e.g., “If the requested loan exceeds $1,000,000, escalate to a Senior Banker”).</li></ol><h3>Part 2: The Architecture — Human-in-the-Loop</h3><p>When the Playbook decides to escalate, it calls the Handoff Tool. This tool triggers a Cloud Run webhook that formats the conversation history and pushes it to a live agent dashboard (e.g., Google Contact Center AI, Salesforce, or Zendesk).</p><h4>Architecture Diagram: The Escalation Pathway</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tFVXLFq4VWusQyOF5bWnZQ.png" /></figure><h3>Part 3: The Implementation (Python SDK)</h3><p>We will use the google-cloud-dialogflow-cx library to programmatically deploy the Playbook and the Escalation Tool.</p><h4>Step 1: Defining the Handoff Tool (OpenAPI)</h4><p>Notice the requestBody schema. We are forcing the LLM to do the heavy lifting: before it hands off to the human, it must generate a concise summary of the problem. This saves the live agent valuable time.</p><pre>import os<br>import textwrap<br>from google.cloud import dialogflowcx_v3beta1 as dfcx<br>from google.api_core.client_options import ClientOptions<br><br>PROJECT_ID = os.environ.get(&quot;GOOGLE_CLOUD_PROJECT&quot;, &quot;your-project-id&quot;)<br>REGION = &quot;us-central1&quot;<br>AGENT_ID = f&quot;projects/{project-id}/locations/{location}/agents/{your-agent-id}&quot;<br><br>client_options = ClientOptions(api_endpoint=f&quot;{id}-dialogflow.googleapis.com&quot;)<br>tools_client = dfcx.ToolsClient(client_options=client_options)<br>playbooks_client = dfcx.PlaybooksClient(client_options=client_options)<br><br>print(&quot;🛠️ Defining Human Escalation Tool...&quot;)<br><br>escalation_spec = textwrap.dedent(&quot;&quot;&quot;<br>openapi: 3.0.0<br>info:<br>  title: Live Agent Routing API<br>  version: 1.0.0<br>servers:<br>  - url: https://your-secure-webhook.run.app<br>paths:<br>  /escalate:<br>    post:<br>      summary: Transfer the user to a live human agent.<br>      description: Use this tool immediately if the user asks for a human, expresses high frustration, or asks a question outside your knowledge domain.<br>      operationId: triggerHumanHandoff<br>      requestBody:<br>        required: true<br>        content:<br>          application/json:<br>            schema:<br>              type: object<br>              required: [reason, user_summary]<br>              properties:<br>                reason:<br>                  type: string<br>                  enum: [USER_REQUESTED, HIGH_FRUSTRATION, OUT_OF_SCOPE, HIGH_VALUE_TRANSACTION]<br>                  description: The primary reason for the handoff.<br>                user_summary:<br>                  type: string<br>                  description: A 2-sentence summary of what the user is trying to achieve, to be read by the live agent.<br>      responses:<br>        &#39;200&#39;:<br>          description: Successfully routed to a human.<br>&quot;&quot;&quot;).strip()<br><br># Create the Tool<br>escalation_tool = tools_client.create_tool(<br>    parent=AGENT_ID,<br>    tool=dfcx.Tool(<br>        display_name=&quot;Human_Handoff_Tool&quot;,<br>        description=&quot;Routes the conversation to a human support desk.&quot;,<br>        open_api_spec=dfcx.Tool.OpenApiTool(text_schema=escalation_spec)<br>    )<br>)<br>print(f&quot;✅ Tool Created: {escalation_tool.name}&quot;)</pre><h4>Step 2: Prompting the Playbook (The “Conscience”)</h4><p>Now, we write the instructions. This is where we define the exact business logic that triggers the tool. We are giving the LLM a “Conscience.”</p><pre>print(&quot;🧠 Architecting the Playbook Instructions...&quot;)<br><br>instruction_prompt = &quot;&quot;&quot;<br>You are the First-Line Banking Assistant.<br>Your goal is to answer basic account questions.<br><br># CRITICAL ESCALATION POLICIES<br>You are strictly prohibited from answering questions outside your domain. You MUST use the `Human_Handoff_Tool` under the following conditions:<br><br>1. **Frustration:** If the user uses profanity or expresses anger, use the tool immediately with reason &#39;HIGH_FRUSTRATION&#39;. Do not attempt to calm them down yourself.<br>2. **High Value:** If the user mentions transferring or investing an amount greater than $100,000, use the tool with reason &#39;HIGH_VALUE_TRANSACTION&#39;.<br>3. **Out of Scope:** If the user asks for legal or investment advice, use the tool with reason &#39;OUT_OF_SCOPE&#39;.<br>4. **Explicit Request:** If the user says &quot;human&quot;, &quot;agent&quot;, or &quot;representative&quot;, use the tool with reason &#39;USER_REQUESTED&#39;.<br><br># POST-HANDOFF BEHAVIOR<br>After successfully calling the `Human_Handoff_Tool`, tell the user: &quot;I have escalated this to a senior specialist who will be with you shortly. Please hold.&quot; Do not ask any further questions.<br>&quot;&quot;&quot;<br><br>playbook = playbooks_client.create_playbook(<br>    parent=AGENT_ID,<br>    playbook=dfcx.Playbook(<br>        display_name=&quot;Secure_Banking_Frontdesk&quot;,<br>        goal=&quot;Assist users and route complex issues to humans.&quot;,<br>        referenced_tools=[escalation_tool.name],<br>        instruction=dfcx.Playbook.Instruction(<br>            steps=[{&quot;text&quot;: s} for s in instruction_prompt.split(&#39;\n&#39;) if s.strip()]<br>        )<br>    )<br>)<br>print(f&quot;✅ Playbook Created: {playbook.name}&quot;)</pre><h4>Part 4: The Reasoning Trace in Action</h4><p>If a user logs in and says: <em>“I’m trying to move $250,000 to my escrow account and I need to know the tax implications.”</em></p><p>Standard chatbots would either fail entirely or, worse, attempt to give hallucinated tax advice. Here is how our <strong>Agentic Architecture</strong> handles it:</p><ol><li><strong>Observation:</strong> The LLM parses the input. It detects the value ($250,000) and the intent (tax advice).</li><li><strong>Policy Evaluation:</strong> The LLM checks its constraints. It hits <em>two</em> escalation triggers: Rule 2 (&gt;$100k) and Rule 3 (Out of Scope/Advice).</li><li><strong>Action (Tool Call):</strong> The LLM autonomously triggers the Human_Handoff_Tool, generating the following structured JSON payload for the webhook:</li></ol><pre>{<br>  &quot;reason&quot;: &quot;HIGH_VALUE_TRANSACTION&quot;,<br>  &quot;user_summary&quot;: &quot;User is attempting to transfer $250k into an escrow account and is requesting specific tax advice regarding the transfer.&quot;<br>}</pre><p><strong>Fulfillment:</strong> The Webhook pushes this rich context to the live agent’s screen, and the bot replies to the user: <em>“I have escalated this to a senior specialist…”</em></p><h3>Conclusion</h3><p>In Enterprise GenAI, the goal is not to automate 100% of interactions. The goal is to automate the mundane and seamlessly route the complex to humans, without losing context.</p><p>By treating human escalation as just another API tool in your Vertex AI Playbook, you empower the LLM to act as a highly intelligent triage system. This guarantees that your AI fails safely, protecting your brand reputation and ensuring compliance in high-stakes environments.</p><h3>References</h3><p>[¹]: Google Cloud Documentation. <a href="https://www.google.com/url?sa=E&amp;q=https%3A%2F%2Fcloud.google.com%2Fdialogflow%2Fcx%2Fdocs%2Fconcept%2Fplaybook">“Vertex AI Playbooks Overview.”</a> Guide to building goal-driven generative agents.</p><p>[²]: Google Cloud Documentation. “<a href="https://docs.cloud.google.com/dialogflow/cx/docs/concept/fulfillment#handoff">Dialogflow CX: Live Agent Handoff.</a>” Native architectural patterns for integrating with Contact Center AI (CCAI) and external CRMs.</p><p>[³]: Google Cloud Architecture Center. “<a href="https://cloud.google.com/discover/human-in-the-loop?e=48754805">Human in the loop (HITL) for Generative AI</a>.” Enterprise design patterns for maintaining human oversight in automated pipelines.</p><p>[⁴]: <a href="https://cloud.google.com/blog/topics/developers-practitioners/create-a-self-escalating-chatbot-in-conversational-agents?e=48754805">Google Cloud Blog</a>: Create a self-escalating chatbot in Conversational Agents using Webhook and Generators</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=03136849f3cb" width="1" height="1" alt=""><hr><p><a href="https://medium.com/google-cloud/architecting-agent-led-escalation-in-generative-ai-03136849f3cb">Architecting Agent-Led Escalation in Generative AI</a> was originally published in <a href="https://medium.com/google-cloud">Google Cloud - Community</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[“Confused Deputy Attack” on Cloud Run]]></title>
            <link>https://medium.com/google-cloud/confused-deputy-attack-on-cloud-run-4e4037d8fc5d?source=rss-13a446e68524------2</link>
            <guid isPermaLink="false">https://medium.com/p/4e4037d8fc5d</guid>
            <category><![CDATA[google-cloud-platform]]></category>
            <category><![CDATA[gcp-security-operations]]></category>
            <category><![CDATA[security]]></category>
            <category><![CDATA[google-cloud-run]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Aniket Agrawal]]></dc:creator>
            <pubDate>Wed, 18 Mar 2026 06:46:50 GMT</pubDate>
            <atom:updated>2026-03-18T06:46:50.033Z</atom:updated>
            <content:encoded><![CDATA[<p>In the rush to build Generative AI agents — bots that check bank balances, approve loans, or book flights — developers often focus entirely on the “Brain” (the LLM) and neglect the “Body” (the infrastructure).</p><p>This leads to a classic yet dangerous vulnerability in microservices: <strong>The Confused Deputy</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zoB4aRjIcJ086b_Q-En8VA.png" /></figure><p>If you secure your backend API by simply asking <em>“Is this a valid Google Cloud Service Account?”</em>, you are effectively leaving the door open. If an attacker steals a valid token meant for a <em>different</em> internal service (e.g., a non-sensitive log viewer), they can use that valid identity to unlock your production banking vault.</p><p>In this deep dive, we will deconstruct a <strong>Defense-in-Depth</strong> architecture on <strong>Google Cloud Run</strong>. We will simulate a “Red Team” attack using generic credentials and then implement the “Blue Team” fix: <strong>Audience (aud) Validation</strong>.</p><h3>The Vulnerability: Identity is Not Enough</h3><p>In a naive “Zero Trust” setup, developers often rely solely on <strong>Authentication</strong> (verifying who the caller is). However, for high-security workloads, we must also verify <strong>Intent</strong> (verifying where the caller intended to send the request).</p><p>Without verifying intent, a generic token issued for <em>any</em> service in your project can be replayed against <em>your</em> specific service.</p><h3>Architecture Diagram: The Confused Deputy Attack</h3><p>In this scenario, an attacker possesses a valid Google Cloud credential. However, the token they generate is generic (lacking a specific target). The Cloud Run IAM Proxy acts as a firewall, inspecting the token’s claims and rejecting it.</p><pre>+-----------------------------------------------------------------------+<br>|  Google Cloud Project (VPC-SC Perimeter)                              |<br>|                                                                       |<br>|  +--------------+             +------------------------------------+  |<br>|  |   Attacker   |             |         Cloud Run Service          |  |<br>|  | (Valid User/ |             |       (Banking Vault API)          |  |<br>|  |  Service Acct)|            |                                    |  |<br>|  |              |             |   +----------------------------+   |  |<br>|  | [Generic JWT]------X------&gt;|   | IAM Proxy (The Gatekeeper) |   |  |<br>|  |              |   (403)     |   | Check: aud == service_url? |   |  |<br>|  +--------------+             |   +----------------------------+   |  |<br>|                               +------------------------------------+  |<br>+-----------------------------------------------------------------------+<br>       ^<br>       |<br>(Public Internet - Blocked via --no-allow-unauthenticated)</pre><h3>Step 1: Deploying the “JWT-Aware” Vault</h3><p>Let’s deploy a Python microservice that acts as our sensitive banking backend. We will deploy it with the — no-allow-unauthenticated flag, forcing all traffic to pass through Google’s IAM layer .</p><p>Crucially, our app includes a /debug endpoint to inspect the incoming security tokens for educational purposes.</p><h4>main.py:</h4><pre>import os<br>import jwt<br>from flask import Flask, jsonify, request<br><br>app = Flask(__name__)<br><br># The Sensitive Data<br>MORTGAGE_RATES = {<br>  &quot;provider&quot;: &quot;SOL309-Secure-Backend&quot;,<br>  &quot;tier&quot;: &quot;INSTITUTIONAL_VIP&quot;,<br>  &quot;rate&quot;: 5.25<br>}<br><br>@app.route(&#39;/rates&#39;)<br>def get_rates():<br>  # If requests reach here, Cloud Run has already validated the signature.<br>  return jsonify(MORTGAGE_RATES)<br><br>@app.route(&#39;/debug&#39;)<br>def debug_token():<br>  # Forensics: Let&#39;s look inside the token<br>  auth_header = request.headers.get(&#39;Authorization&#39;, &#39;&#39;)<br>  token = auth_header.split(&quot; &quot;)[1]<br>  # Decode without verifying signature just for inspection<br>  decoded = jwt.decode(token, options={&quot;verify_signature&quot;: False})<br>  return jsonify({<br>    &quot;token_type&quot;: &quot;JWT&quot;,<br>    &quot;audience_claim&quot;: decoded.get(&quot;aud&quot;, &quot;MISSING&quot;)<br>  })<br><br>if __name__ == &quot;__main__&quot;:<br>  app.run(host=&#39;0.0.0.0&#39;, port=8080)</pre><h4>Deployment:</h4><pre>gcloud run deploy banking-vault \<br> - source . \<br> - region us-central1 \<br> - no-allow-unauthenticated</pre><p>(After deployment, save your service URL as $SERVICE_URL)</p><h3>Step 2: The “Red Team” Audit</h3><p>Imagine you are a developer with valid access to the Google Cloud project. You assume you can access the service because you are “authenticated.”</p><h4>Attempt 1: The Access Token (OAuth2)</h4><p>You try using the standard CLI access token typically used for managing resources (Control Plane).</p><pre>TOKEN=$(gcloud auth print-access-token)<br>curl -H &quot;Authorization: Bearer $TOKEN&quot; $SERVICE_URL/rates</pre><p><strong>Result:</strong> HTTP 401 Unauthorized.</p><p><strong>Why:</strong> Cloud Run service-to-service authentication requires an <strong>OIDC Identity Token</strong>, not an OAuth Access Token . Access tokens authorize actions on resources (e.g., “Delete this VM”), whereas Identity tokens prove who you are to a service.</p><h4>Attempt 2: The Generic ID Token</h4><p>You correct your mistake and generate a valid OIDC Identity Token.</p><pre>TOKEN=$(gcloud auth print-identity-token)<br>curl -H &quot;Authorization: Bearer $TOKEN&quot; $SERVICE_URL/rates</pre><p><strong>Result:</strong> HTTP 403 Forbidden.</p><p><strong>The “Confused Deputy” moment:</strong> You have a valid ID, signed by Google, but Cloud Run rejects you.</p><p><strong>Why:</strong> By default, gcloud auth print-identity-token generates a token with a generic audience. Cloud Run inspects the <strong>Audience (aud)</strong> claim, sees it does not match the URL of the banking service, and blocks the request to prevent token replay attacks .</p><h3>Step 3: The “Blue Team” Fix (Audience Validation)</h3><p>To successfully connect your GenAI Agent to this backend, you must perform <strong>Targeted Token Minting</strong>.</p><p>We use the — audiences flag to cryptographically stamp the destination URL into the token signature. This proves <strong>Intent</strong>.</p><h4>Architecture Diagram: The Secure Handshake</h4><p>In the secure flow, the token carries the destination address inside it. The Gatekeeper validates this before allowing entry.</p><pre>+-----------------------------------------------------------------------+<br>|  Google Cloud Project (Trusted Flow)                                  |<br>|                                                                       |<br>|  +--------------+             +------------------------------------+  |<br>|  |   AI Agent   |             |         Cloud Run Service          |  |<br>|  | (Service Acct)|            |       (Banking Vault API)          |  |<br>|  |              |             |                                    |  |<br>|  | 1. Mint Token|             |   +----------------------------+   |  |<br>|  |    (Targeted)|------------&gt;|   | IAM Proxy (The Gatekeeper) |   |  |<br>|  |              |   200 OK    |   | Check: aud == service_url? |   |  |<br>|  +--------------+             |   |      Result: MATCH         |   |  |<br>|                               |   +-------------+--------------+   |  |<br>|                               |                 |                  |  |<br>|                               |          +------+-------+          |  |<br>|                               |          |  Flask App   |          |  |<br>|                               |          +--------------+          |  |<br>+-----------------------------------------------------------------------+</pre><h4>The Execution</h4><ol><li><strong>Generate the Targeted Token:</strong> We explicitly state <em>where</em> this token will be used.</li></ol><pre>TARGET_TOKEN=$(gcloud auth print-identity-token - audiences=$SERVICE_URL)</pre><p><strong>2. Access the Vault:</strong></p><pre>curl -H &quot;Authorization: Bearer $TARGET_TOKEN&quot; $SERVICE_URL/rates</pre><p><strong>Result:</strong> HTTP 200 OK 🟢. You receive: {“rate”: 5.25}.</p><h4>Forensics (Why it worked):</h4><p>Send the token to our debug endpoint.</p><pre>curl -s -H &quot;Authorization: Bearer $TARGET_TOKEN&quot; $SERVICE_URL/debug</pre><p><strong>Output:</strong></p><pre>{<br>&quot;audience_claim&quot;: &quot;https://banking-vault-xyz.a.run.app&quot;,<br>&quot;token_type&quot;: &quot;JWT&quot;<br>}</pre><p>Because the audience_claim inside the token exactly matches the URL of the service receiving it, the Cloud Run IAM Proxy allows the request to pass.</p><h3>Conclusion</h3><p>When building Hybrid AI Agents using <strong>Vertex AI Playbooks</strong> or <strong>Dialogflow CX</strong>, security is paramount. You are effectively giving an LLM access to your internal API surface.</p><ol><li><strong>Zero Trust:</strong> Never expose backend APIs to the public internet ( — no-allow-unauthenticated).</li><li><strong>Identity:</strong> Always use Service Accounts for agent execution.</li><li><strong>Intent:</strong> Ensure your Agent is minting OIDC tokens with the specific <strong>Audience</strong> of the target tool.</li></ol><p>By enforcing Audience Validation, you ensure that even if a token is leaked from a lower-security development environment, it cannot be used to “confuse the deputy” and access your production banking data.</p><h3>References:</h3><p>[¹]: <a href="https://www.google.com/url?sa=E&amp;q=https%3A%2F%2Fcloud.google.com%2Frun%2Fdocs%2Fauthenticating%2Foverview">Cloud Run Authentication Overview</a><br>[²]: <a href="https://www.google.com/url?sa=E&amp;q=https%3A%2F%2Fcloud.google.com%2Fdocs%2Fauthentication%2Ftoken-types">Google Cloud Authentication: Token Types</a><br>[³]: <a href="https://www.google.com/url?sa=E&amp;q=https%3A%2F%2Fcloud.google.com%2Frun%2Fdocs%2Fauthenticating%2Fservice-to-service">Service-to-Service Authentication (Audience Validation)</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4e4037d8fc5d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/google-cloud/confused-deputy-attack-on-cloud-run-4e4037d8fc5d">“Confused Deputy Attack” on Cloud Run</a> was originally published in <a href="https://medium.com/google-cloud">Google Cloud - Community</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Real-Time OmniCommerce Agents (Part 2: ADK-JAX Intelligence Layer)]]></title>
            <link>https://medium.com/google-cloud/real-time-omnicommerce-agents-part-2-adk-jax-intelligence-layer-b652ad9fc038?source=rss-13a446e68524------2</link>
            <guid isPermaLink="false">https://medium.com/p/b652ad9fc038</guid>
            <category><![CDATA[vertex-ai]]></category>
            <category><![CDATA[agent-development-kit]]></category>
            <category><![CDATA[google]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Aniket Agrawal]]></dc:creator>
            <pubDate>Mon, 20 Oct 2025 11:43:59 GMT</pubDate>
            <atom:updated>2025-10-20T11:43:59.732Z</atom:updated>
            <content:encoded><![CDATA[<h4>Create the Intelligence Layer &amp; Production Path in Part 2</h4><h3>Introduction: From Transaction to Intelligence</h3><p>Welcome back! In <a href="https://medium.com/@aniketagrawal_14703/real-time-omnicommerce-agents-part-1-adk-jax-transaction-core-ecfba3933981"><strong>Part 1 of this series</strong></a>, we did the foundational “hard hat” work. We architected the <strong>transactional core</strong> of our OmniCommerce Genius. We established a robust, scalable data backbone on <a href="https://www.google.com/search?q=httpss://cloud.google.com/bigquery">Google BigQuery</a>, architected an atomic inventory system to prevent race conditions, and used the <a href="https://www.google.com/search?q=httpss://github.com/GoogleCloudPlatform/adk">Google Agent Development Kit (ADK)</a> to create a <em>reliable</em> agent. In short, we built an agent that can be trusted to sell products.</p><p>Please request access with valid justification for the following:<br>To see it in action, click on <a href="https://drive.google.com/file/d/1fQtVeRPmwoIGVPtk8luk8jyFUJgG-hIT/view?usp=drive_link"><strong>OmniCommerce ADK Demo Video (4K)</strong></a>.<br>To check code, click on <a href="https://drive.google.com/file/d/1WXqgveGHQRt3dPsSglCNr-pCx5hBclsS/view?usp=drive_link"><strong>OmniCommerce Agent Code</strong></a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*dEfwM6knSrobkJmrHuNy6A.gif" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*ZvW_iG3pO0rjSTEH1EoTBg.gif" /><figcaption>Real-Time OmniCommerce Agent in action with ADK web</figcaption></figure><p>Now, we build the <strong>intelligence layer</strong>. This is where our agent transcends a simple “bot” and becomes a true assistant. This is the “why” that justifies our cloud-native architecture. In this final part, we’ll cover:</p><ol><li><strong>AI-Driven Workflows:</strong> Building a proactive meal planner and a personal stylist.</li><li><strong>Personalization &amp; Proactivity:</strong> Using user history to anticipate needs.</li><li><strong>Contextual Agility:</strong> How the agent adapts to seasonal events like Diwali.</li><li><strong>Advanced Computation:</strong> Integrating a <a href="https://www.google.com/search?q=httpss://jax.readthedocs.io/en/latest/">JAX</a>-powered “StyleFusion” engine for creative recommendations.</li><li><strong>The Production Path:</strong> A clear blueprint for deploying our agent to a global audience using <a href="https://www.google.com/search?q=httpss://cloud.google.com/vertex-ai/docs/agent-engine/develop-an-agent">Vertex AI Agent Engine</a>.</li></ol><p>This is the journey from a reliable cashier to an indispensable, 24/7 personal shopper.</p><h3>1. The Proactive &amp; Personalized Assistant</h3><p>An intelligent agent doesn’t just wait for commands; it anticipates needs. This is achieved by leveraging user data (like UserPurchaseHistory) and building tools that execute multi-step logic.</p><h4>The Proactive Grocer: get_smart_shopping_list</h4><p>This tool transforms the agent from a reactive search bar into a proactive assistant. It checks a user’s purchase history to see which recurring items (like eggs or milk) they are likely running low on. This simple, data-driven feature is often the most powerful form of “AI” a user can experience.</p><p>The logic is a straightforward SQL query that runs when the user opens the grocery section.</p><pre># --- Tool: Proactive Smart List ---<br>def get_smart_shopping_list(user_id: str) -&gt; str:<br>    &quot;&quot;&quot;Proactively finds items the user is likely running low on.&quot;&quot;&quot;<br>    try:<br>        # This query joins the user&#39;s history with the main catalog<br>        # It uses DATE_DIFF to see if enough time has passed.<br>        query = f&quot;&quot;&quot;<br>            SELECT t1.name, t1.sub_category, t2.last_purchase_date<br>            FROM `{CATALOG_ID}` AS t1<br>            JOIN `{HISTORY_ID}` AS t2 ON t1.item_id = t2.item_id<br>            WHERE t2.user_id = @p_user_id<br>              AND DATE_DIFF(CURRENT_DATE(), t2.last_purchase_date, DAY) &gt;= t2.frequency_days<br>        &quot;&quot;&quot;<br>        params = [bigquery.ScalarQueryParameter(&quot;p_user_id&quot;, &quot;STRING&quot;, user_id)]<br>        df = db_client.query(query, ...).to_dataframe()<br>        <br>        return json.dumps({<br>            &quot;tool_name&quot;: &quot;get_smart_shopping_list&quot;, <br>            &quot;items&quot;: df.to_dict(&#39;records&#39;)<br>        })<br>    except Exception as e:<br>        return json.dumps({&quot;error&quot;: f&quot;Smart list generation failed: {e}&quot;})</pre><h4>The Creative Chef: build_meal_plan</h4><p>This tool is a perfect example of the <a href="https://www.google.com/search?q=httpss://arxiv.org/abs/2210.03629"><strong>ReAct (Reason + Act)</strong></a> paradigm. The agent doesn’t just fetch data; it reasons about a goal, acts to get information, and then reasons about the <em>next</em> act.</p><p>When a user says, <em>“I have chicken and lemons, what’s for dinner?”</em>:</p><ul><li><strong>Step 1 (Reason):</strong> The user has [chicken, lemon]. This matches the trigger_ingredients for a &quot;Grocery&quot; workflow.</li><li><strong>Step 2 (Act):</strong> Call the build_meal_plan tool.</li><li><strong>Step 3 (Tool Execution):</strong></li><li>The tool queries the Recipes table and finds &quot;Lemon Herb Chicken.&quot;</li><li>It then cross-references the recipe’s required_ingredients ([chicken, lemon, olive oil, rosemary]) with the user&#39;s pantry.</li><li>It reasons that [olive oil, rosemary] are missing.</li><li>It <strong>acts again</strong> by querying the MasterProductCatalog for the prices of the missing items.</li><li><strong>Step 4 (Observe):</strong> The tool returns a single JSON object containing the recipe <em>and</em> a pre-built shopping list.</li><li><strong>Step 5 (Reason):</strong> The agent receives this rich JSON and passes it to the _format_response tool to present a complete solution.</li></ul><pre># --- Tool: AI-Driven Meal Planner ---<br>def build_meal_plan(pantry_items: List[str]) -&gt; str:<br>    &quot;&quot;&quot;Finds a recipe and builds a shopping list for missing ingredients.&quot;&quot;&quot;<br>    try:<br>        pantry_set = set(item.lower() for item in pantry_items)<br>        <br>        # Step 1: Find a recipe<br>        query = f&quot;&quot;&quot;<br>            SELECT title, description, required_ingredients<br>            FROM `{RECIPE_ID}`<br>            WHERE EXISTS (<br>                SELECT 1 FROM UNNEST(trigger_ingredients) as trigger WHERE trigger IN UNNEST(@p_pantry)<br>            ) LIMIT 1<br>        &quot;&quot;&quot;<br>        params = [bigquery.ArrayQueryParameter(&quot;p_pantry&quot;, &quot;STRING&quot;, list(pantry_set))]<br>        recipe_df = db_client.query(query, ...).to_dataframe()<br>        <br>        if recipe_df.empty: <br>            return json.dumps({&quot;error&quot;: &quot;I couldn&#39;t find a recipe suggestion...&quot;})<br><br>        recipe = recipe_df.iloc[0].to_dict()<br>        recipe[&#39;required_ingredients&#39;] = list(recipe[&#39;required_ingredients&#39;]) <br>        # Step 2: Reason about missing ingredients<br>        missing_items = list(set(recipe[&#39;required_ingredients&#39;]) - pantry_set)<br>        <br>        # Step 3: Act again to build a shopping list<br>        shopping_list = []<br>        if missing_items:<br>            product_query = f&quot;&quot;&quot;<br>                SELECT name, sub_category, price FROM `{CATALOG_ID}`<br>                WHERE category = &#39;Grocery&#39; AND EXISTS (<br>                    SELECT 1 FROM UNNEST(search_tags) AS tag WHERE tag IN UNNEST(@p_items)<br>                )<br>            &quot;&quot;&quot;<br>            product_params = [bigquery.ArrayQueryParameter(&quot;p_items&quot;, &quot;STRING&quot;, missing_items)]<br>            shopping_list = db_client.query(product_query, ...).to_dataframe().to_dict(&#39;records&#39;)<br>        <br>        return json.dumps({<br>            &quot;tool_name&quot;: &quot;build_meal_plan&quot;, <br>            &quot;recipe&quot;: recipe, <br>            &quot;shopping_list&quot;: shopping_list<br>        })<br>    except Exception as e: <br>        return json.dumps({&quot;error&quot;: f&quot;Meal plan generation failed: {e}&quot;})</pre><h3>2. The Domain Specialist (Stylist &amp; Critic)</h3><p>An intelligent agent must also have deep domain expertise. We provide this by giving it specialized tools for complex verticals like fashion.</p><h4>The Personal Stylist: find_fashion_item</h4><p>This tool allows the agent to act as a personal stylist. It takes multiple constraints — category, style, and budget — and builds a dynamic SQL query to find the perfect item. This is far more powerful than a simple keyword search.</p><pre># --- Tool: Personal Fashion Stylist ---<br>def find_fashion_item(category: str, style_tags: List[str], max_price: float) -&gt; str:<br>    &quot;&quot;&quot;Finds a single fashion item matching style, category, and budget.&quot;&quot;&quot;<br>    try:<br>        # Base query<br>        query_parts = [<br>            f&quot;SELECT item_id, name, sub_category, price FROM `{CATALOG_ID}`&quot;,<br>            f&quot;WHERE category = &#39;Fashion&#39; AND sub_category = @p_category AND price &lt;= @p_max_price&quot;<br>        ]<br>        params = [<br>            bigquery.ScalarQueryParameter(&quot;p_category&quot;, &quot;STRING&quot;, category),<br>            bigquery.ScalarQueryParameter(&quot;p_max_price&quot;, &quot;FLOAT64&quot;, max_price)<br>        ]<br>        <br>        # Dynamically add style tag constraints<br>        for i, tag in enumerate(style_tags):<br>            param_name = f&quot;p_tag{i}&quot;<br>            query_parts.append(f&quot;AND @{param_name} IN UNNEST(style_tags)&quot;)<br>            params.append(bigquery.ScalarQueryParameter(param_name, &quot;STRING&quot;, tag))<br>        <br>        query_parts.append(&quot;ORDER BY price DESC LIMIT 1&quot;)<br>        <br>        query = &quot;\n&quot;.join(query_parts)<br>        df = db_client.query(query, job_config=..._).to_dataframe()<br>        <br>        if df.empty:<br>            return json.dumps({&quot;error&quot;: f&quot;No {category} found for that style and budget.&quot;})<br>        <br>        return df.to_json(orient=&#39;records&#39;) # Returns JSON list<br>    except Exception as e:<br>        return json.dumps({&quot;error&quot;: f&quot;Database query failed in find_fashion_item: {e}&quot;})</pre><h4>The “X-Factor” (JAX): generate_stylefusion_item</h4><p>This is our most advanced tool. It allows the agent to be <em>creative</em>. It “fuses” the styles of two items (e.g., “a sofa” and “an abstract rug”) by averaging their style_embedding vectors from the MasterProductCatalog.</p><pre># --- Tool: JAX-Powered StyleFusion ---<br>def generate_stylefusion_item(item_id_1: str, item_id_2: str) -&gt; str:<br>    &quot;&quot;&quot;(JAX-Powered) Fuses the style embeddings of two parent items.&quot;&quot;&quot;<br>    if not jax: <br>        return json.dumps({&quot;error&quot;: &quot;JAX is not installed. Run &#39;pip install jax jaxlib&#39; to enable.&quot;})<br>    try:<br>        # 1. Fetch the two embedding vectors from BigQuery<br>        query = f&quot;SELECT name, style_embedding FROM `{CATALOG_ID}` WHERE item_id IN (@p_id1, @p_id2)&quot;<br>        params = [...]<br>        df = db_client.query(query, ...).to_dataframe()<br>        if len(df) &lt; 2: <br>            return json.dumps({&quot;error&quot;: &quot;Could not find one or both parent items.&quot;})<br><br>        # 2. Convert to JAX arrays for high-performance computation<br>        embed1 = jnp.array(df.iloc[0][&#39;style_embedding&#39;])<br>        embed2 = jnp.array(df.iloc[1][&#39;style_embedding&#39;])<br>        <br>        # 3. Perform the vector operation in JAX<br>        fused_embedding = jnp.mean(jnp.array([embed1, embed2]), axis=0)<br>        <br>        return json.dumps({<br>            &quot;tool_name&quot;: &quot;generate_stylefusion_item&quot;, <br>            &quot;fused_embedding&quot;: [round(float(x), 4) for x in fused_embedding]<br>        })<br>    except Exception as e:<br>        return json.dumps({&quot;error&quot;: f&quot;JAX StyleFusion model failed: {e}&quot;})</pre><p><strong>Deep Dive: Why JAX? The Deeper Architectural Reason</strong></p><p>On the surface, jnp.mean is a trivial operation. <strong>This is a crucial architectural point.</strong> The generate_stylefusion_item tool is a <em>placeholder</em> for a much more complex, JAX-native ML ecosystem.</p><ul><li><strong>High-Performance Training:</strong> The style_embedding vectors themselves are not static. They would be created by a deep learning model trained on our entire product catalog. This model could be a <a href="https://huggingface.co/docs/transformers/en/model_doc/vit"><strong>Vision Transformer (ViT)</strong></a> that analyzes product images, or a generative model (like a <a href="https://www.geeksforgeeks.org/deep-learning/generative-adversarial-network-gan/"><strong>GAN</strong></a>) trained on fashion synthesis.</li><li><strong>JAX for ML:</strong> We would use <strong>JAX</strong> to build, train, and serve this model due to its:</li><li><strong>Automatic Differentiation (</strong><strong>jax.grad):</strong> For effortlessly training complex, modern ML architectures.</li><li><strong>JIT Compilation (</strong><strong>jax.jit):</strong> For compiling Python/NumPy code directly to highly optimized XLA, enabling blazing-fast execution on GPUs and TPUs.</li><li><strong>Scalability (</strong><strong>jax.pmap):</strong> For easily distributing training and inference across massive hardware pods.</li><li><strong>The Big Picture:</strong> Our simple tool is the “tip of the iceberg,” the final connection point between the agent and a powerful, JAX-native ML pipeline running on <a href="https://cloud.google.com/vertex-ai/docs/training/overview"><strong>Vertex AI Training</strong></a>. This is how you integrate high-performance, custom AI into an agent framework.</li></ul><h3>3. Contextual Agility &amp; Worldly Knowledge</h3><p>An agent must be able to adapt to changing contexts and handle out-of-domain queries gracefully.</p><h4>The Seasonal Specialist: get_diwali_gifting_ideas</h4><p>This tool demonstrates <strong>contextual agility</strong>. It is a specialized tool that the agent learns to use (via its prompt) <em>only</em> when the user’s intent is appropriate (e.g., they mention “Diwali” or “gifts”). This is a key concept from the <a href="https://www.google.com/search?q=httpss://arxiv.org/abs/2302.04761"><strong>Toolformer</strong></a> paper, showing how an LLM’s “toolbox” can be expanded.</p><pre># --- Tool: Diwali Gifting Ideas (Contextual Tool) ---<br>def get_diwali_gifting_ideas(max_budget: float) -&gt; str:<br>    &quot;&quot;&quot;Finds a pre-made Diwali gift bundle that fits within a USD budget.&quot;&quot;&quot;<br>    try:<br>        # Query the specialized `DiwaliGiftBundles` table<br>        query = f&quot;&quot;&quot;<br>            SELECT t1.plan_name, t1.budget_tier_usd,<br>                   ARRAY_AGG(STRUCT(t2.name, t2.price)) AS items<br>            FROM `{DIWALI_BUNDLES_ID}` AS t1<br>            JOIN `{CATALOG_ID}` AS t2 ON t2.item_id IN UNNEST(t1.item_ids)<br>            WHERE t1.budget_tier_usd &lt;= @p_budget<br>            GROUP BY 1, 2 ORDER BY 2 DESC LIMIT 1<br>        &quot;&quot;&quot;<br>        params = [bigquery.ScalarQueryParameter(&quot;p_budget&quot;, &quot;FLOAT64&quot;, max_budget)]<br>        df = db_client.query(query, ...).to_dataframe()<br>        <br>        if df.empty:<br>            return json.dumps({&quot;error&quot;: f&quot;Sorry, I couldn&#39;t find any gift bundles...&quot;})<br>            <br>        result = df.to_dict(&#39;records&#39;)[0]<br>        result[&#39;items&#39;] = [{&#39;name&#39;: item[&#39;name&#39;], &#39;price&#39;: item[&#39;price&#39;]} for item in result[&#39;items&#39;]]<br>        <br>        return json.dumps({&quot;tool_name&quot;: &quot;get_diwali_gifting_ideas&quot;, &quot;bundle&quot;: result})<br>    except Exception as e:<br>        return json.dumps({&quot;error&quot;: f&quot;Diwali gifting query failed: {e}&quot;})</pre><h4>The Worldly Assistant: get_general_info</h4><p>A user might ask “What is Diwali?” before asking for gifts. If the agent can’t answer, the conversation feels brittle. This tool connects to a third-party search API to handle general knowledge questions, making the agent more robust and helpful.</p><pre># --- Tool: General Knowledge ---<br>def get_general_info(topic: str) -&gt; str:<br>    &quot;&quot;&quot;Uses DuckDuckGo to answer general knowledge questions.&quot;&quot;&quot;<br>    try:<br>        url = f&quot;httpss://api.duckduckgo.com/?q={requests.utils.quote(topic)}&amp;format=json&quot;<br>        data = requests.get(url, headers={&#39;User-Agent&#39;: &#39;OmniCommerceGenius/1.0&#39;}).json()<br>        summary = data.get(&quot;AbstractText&quot;)<br>        <br>        if not summary: <br>            return json.dumps({&quot;error&quot;: f&quot;I couldn&#39;t find a summary for &#39;{topic}&#39;.&quot;})<br>            <br>        return json.dumps({&quot;tool_name&quot;: &quot;get_general_info&quot;, &quot;summary&quot;: summary})<br>    except Exception as e:<br>        return json.dumps({&quot;error&quot;: f&quot;Could not connect to the information service: {e}&quot;})</pre><h3>4. How to run the code</h3><p>With your prerequisites configured and your agent.py file created, running Aura is incredibly simple thanks to the ADK.</p><ol><li><strong>Ensure you are in the correct directory:</strong> Your terminal should be in the root folder, i.e., directory having agent.py.</li><li><strong>Activate your virtual environment:</strong></li></ol><pre>source venv/bin/activate</pre><p><strong>Run OmniCommerce in one of two modes:</strong></p><ul><li><strong>Interactive Command-Line Mode:</strong><br>This is perfect for quick tests and development, as you’ll see the agent’s thoughts and tool calls directly in the terminal.</li></ul><pre>./venv/bin/adk run retail_agent</pre><ul><li><strong>Sleek Web Interface:</strong><br>To showcase your agent with a shareable UI, use the web command.</li></ul><pre>./venv/bin/adk web .</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/690/0*MDKhGv6GnCiOQQ0j.jpeg" /><figcaption><a href="https://d2yds90mtvelsl.cloudfront.net/original/3X/6/7/67b8b2cf4dacd710c949dd21676a2feb527fc7ab.jpeg">Terminal showing an ADK web server startup with HTTP requests and responses from a Gemini API backend.</a></figcaption></figure><p>The ADK will start a local server (usually on `<a href="http://127.0.0.1:8000`">http://127.0.0.1:8000`</a>) and provide a URL to a beautiful chat interface right in your browser.</p><h3>5. The Production Path: From ADK to Agent Engine</h3><p>We’ve built a powerful, sophisticated prototype. Now, how do we serve it to millions of users? This is the step that separates our current project from my <a href="https://www.google.com/search?q=httpss://medium.com/google-cloud/agentic-ml-pipeline-with-google-adk-no-gcp-project-needed-gcp-project-not-required-324e65a6e270">previous Colab-only agent</a>.</p><p><strong>Step 1: Evolve the Agent</strong></p><ul><li><strong>Model:</strong> Upgrade the model parameter in the Agent class from gemini-2.0-flash to a more powerful model like <strong>Gemini Pro</strong> for even more complex, multi-step reasoning.</li><li><strong>Data:</strong> Move from static BigQuery tables to real-time data. This involves:</li><li><strong>RAG (Retrieval-Augmented Generation):</strong> Integrating <a href="https://www.google.com/search?q=httpss://cloud.google.com/vertex-ai/docs/generative-ai/rag/overview"><strong>Vertex AI Search</strong></a> to ground the agent’s product knowledge in a real-time, searchable catalog.</li><li><strong>Real APIs:</strong> Replacing placeholder tools with calls to live inventory, pricing, and shipping APIs.</li></ul><p><strong>Step 2: Containerize with Docker</strong></p><p>We create a Dockerfile to package our entire agent—the Python code, the ADK, and all its dependencies—into a lightweight, portable container. This is the industry standard for reliable, reproducible deployments.</p><p><strong>Step 3: Deploy to a Scalable Agent Engine</strong></p><p>The ADK’s local server (adk web) is for development. For production, we need a platform that can handle global traffic and scale automatically. As the <a href="https://www.google.com/search?q=httpss://cloud.google.com/vertex-ai/docs/agent-engine/develop-an-agent">official documentation</a> highlights, we have two excellent choices:</p><ul><li><a href="https://www.google.com/search?q=httpss://cloud.google.com/run"><strong>Google Cloud Run</strong></a>: The ultimate serverless platform. We simply give Cloud Run our Docker container, and it handles everything — providing a public HTTPS endpoint, scaling from zero to thousands of instances, and scaling back down, so we only pay for what we use.</li><li><a href="https://www.google.com/search?q=httpss://cloud.google.com/vertex-ai/docs/agent-engine/develop-an-agent"><strong>Vertex AI Agent Engine</strong></a>: This is the <strong>purpose-built, fully managed platform</strong> for deploying agents. This path is ideal because the ADK is a template “designed based on Google’s internal best practices” specifically for this. It’s a framework-agnostic engine that can also host agents built with <a href="https://www.google.com/search?q=httpss://python.langchain.com/v0.1/docs/integrations/platforms/google/">LangChain</a>, LangGraph, or even multi-agent systems communicating via the <a href="https://www.google.com/search?q=httpss://github.com/a2a-dev/protocol"><strong>A2A (Agent2Agent) protocol</strong></a>.</li></ul><h3>Conclusion: The Full-Stack AI Agent</h3><p>Our two-part journey is complete. We started in <strong>Part 1</strong> by building a <strong>rock-solid transactional core</strong>, proving our agent’s reliability with atomic inventory management. In <strong>Part 2,</strong> we built the <strong>intelligence layer</strong> on top, creating a proactive, context-aware, and creative assistant.</p><p>We’ve shown how to combine the reasoning power of <a href="https://www.google.com/search?q=httpss://deepmind.google/technologies/gemini/">Gemini</a>, the data-handling of BigQuery, the high-performance ML of JAX, and the robust development framework of the ADK. The result is not just a “chatbot” — it’s a full-stack, production-ready OmniCommerce Genius, a true blueprint for the future of AI-driven retail.</p><h3>References and Further Reading</h3><p>Ready to start your own agent-building journey? Here are the official resources and foundational research to get you started.</p><h4>Official documentation</h4><ul><li><a href="https://github.com/google/adk-python"><strong>Agent Development Kit (ADK) on GitHub</strong></a>: The official repository for the ADK.</li><li><a href="https://cloud.google.com/vertex-ai/generative-ai/docs/agent-development-kit/quickstart"><strong>ADK Quickstart</strong></a>: The official starting point for the ADK.</li><li><a href="https://github.com/google/adk-samples"><strong>ADK Samples</strong></a>: Sample agents under ADK Repo.</li><li><a href="https://ai.google.dev/"><strong>Google AI for Developers</strong></a>: Your central hub for Gemini API documentation, tutorials, and examples.</li><li><a href="https://cloud.google.com/bigquery/docs"><strong>BigQuery Documentation</strong></a>: Learn more about how to manage and query data at scale.</li><li><a href="https://cloud.google.com/run/docs"><strong>Cloud Run Documentation</strong></a>: A complete guide to deploying and managing serverless applications.</li></ul><h4>Data and Compute</h4><ul><li><a href="https://cloud.google.com/bigquery/docs/reference/standard-sql/data-manipulation-language"><strong>Google BigQuery DML Documentation</strong></a>: Official guide on using UPDATE, INSERT, and DELETE.</li><li><a href="https://cloud.google.com/bigquery/docs"><strong>Managing Data in BigQuery</strong></a>: Best practices for data manipulation and storage.</li></ul><h4>Foundational research papers</h4><ul><li><a href="https://arxiv.org/abs/2210.03629"><strong>ReAct: Synergizing Reasoning and Acting in Language Models (Yao, et al., 2022)</strong></a>: A groundbreaking paper that introduced the “Reason, Act” paradigm, which is fundamental to how modern agents like Aura decide which tool to use.</li><li><a href="https://arxiv.org/abs/2302.04761"><strong>Toolformer: Language Models Can Teach Themselves to Use Tools (Schick, et al., 2023)</strong></a>: This paper demonstrates how LLMs can learn to use external tools through simple APIs, a core concept in our agent’s design.</li><li><a href="https://arxiv.org/abs/2201.11903"><strong>Chain of Thought Prompting Elicits Reasoning in Large Language Models (Wei, et al., 2022)</strong></a>: While not strictly about agents, this paper is essential for understanding how to prompt models to perform complex, multi-step reasoning, which is the basis for Aura’s “Master Workflow.”</li></ul><h4><strong>High-Performance ML &amp; JAX</strong></h4><ul><li><a href="https://docs.jax.dev/en/latest/"><strong>JAX: Composable transformations of Python+NumPy programs</strong></a><strong> </strong>(Official JAX Documentation)</li><li><a href="https://arxiv.org/abs/2503.12687"><strong>AI Agents: Evolution, Architecture, and Real-World Applications</strong></a></li><li><a href="https://github.com/a2aproject/A2A"><strong>Agent2Agent (A2A) Protocol </strong></a>— An open standard for multi-agent communication, donated by Google Cloud.</li></ul><h4>Assets</h4><ul><li><a href="https://medium.com/@aniketagrawal_14703/real-time-omnicommerce-agents-part-1-adk-jax-transaction-core-ecfba3933981"><strong>Real-Time OmniCommerce Agents (Part 1: ADK-JAX Transaction Core)</strong></a></li><li><a href="https://drive.google.com/file/d/1fQtVeRPmwoIGVPtk8luk8jyFUJgG-hIT/view?usp=drive_link"><strong>OmniCommerce ADK Demo Video (4K)</strong></a></li><li><a href="https://drive.google.com/file/d/1WXqgveGHQRt3dPsSglCNr-pCx5hBclsS/view?usp=drive_link"><strong>OmniCommerce Agent Code</strong></a></li><li><a href="https://discuss.google.dev/t/build-aura-genai-travel-concierge-with-adk/274125"><strong>Build Aura: GenAI Travel Concierge with ADK</strong></a></li><li><a href="https://drive.google.com/file/d/1Tr_HXOC1oweVJzvNa84J4beYB_9ahM3c/view?usp=drive_link"><strong>Aura Demo Video (4K)</strong></a></li><li><a href="https://drive.google.com/file/d/1qGfLc8iFXmvq6oW-rDvHDtOxXJ-iB-XW/view?usp=drive_link"><strong>Aura Agent Code</strong></a></li></ul><p>We can’t wait to see what you build. Share your creations and ask questions in the Google Cloud Community. Happy coding!</p><p><strong>Let’s keep the conversation going! Share your thoughts, questions, and ideas in the comments.</strong></p><p><strong>Note:</strong> <em>Should you have any concerns or queries about this post or my implementation, please feel free to connect with me on </em><a href="https://www.linkedin.com/in/aniket-agrawal-a18990266/"><em>LinkedIn</em></a><em>! Thanks!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b652ad9fc038" width="1" height="1" alt=""><hr><p><a href="https://medium.com/google-cloud/real-time-omnicommerce-agents-part-2-adk-jax-intelligence-layer-b652ad9fc038">Real-Time OmniCommerce Agents (Part 2: ADK-JAX Intelligence Layer)</a> was originally published in <a href="https://medium.com/google-cloud">Google Cloud - Community</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Real-Time OmniCommerce Agents (Part 1: ADK-BQ Transaction Core)]]></title>
            <link>https://medium.com/google-cloud/real-time-omnicommerce-agents-part-1-adk-transaction-core-ecfba3933981?source=rss-13a446e68524------2</link>
            <guid isPermaLink="false">https://medium.com/p/ecfba3933981</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[bigquery]]></category>
            <category><![CDATA[agent-development-kit]]></category>
            <category><![CDATA[google]]></category>
            <dc:creator><![CDATA[Aniket Agrawal]]></dc:creator>
            <pubDate>Mon, 20 Oct 2025 11:43:40 GMT</pubDate>
            <atom:updated>2025-10-23T16:45:45.461Z</atom:updated>
            <content:encoded><![CDATA[<h4>Architecting the OmniCommerce Genius Core in Part 1</h4><h3>Introduction: From Colab to Cloud-Native Agents</h3><p>We are at a fascinating inflection point in AI. The conversation has decisively shifted from building simple chatbots to architecting sophisticated, multi-domain <strong>AI agents</strong> that can reason, plan, and execute complex, real-world tasks.</p><p>Please request access with valid justification for the following:<br>To see it in action, click on <a href="https://drive.google.com/file/d/1fQtVeRPmwoIGVPtk8luk8jyFUJgG-hIT/view?usp=drive_link"><strong>OmniCommerce ADK Demo Video (4K)</strong></a>.<br>To check code, click on <a href="https://drive.google.com/file/d/1WXqgveGHQRt3dPsSglCNr-pCx5hBclsS/view?usp=drive_link"><strong>OmniCommerce Agent Code</strong></a>.</p><p>This is my first multi-part technical blog, and it’s a direct sequel to my previous post, <a href="https://medium.com/google-cloud/agentic-ml-pipeline-with-adk-no-gcp-project-needed-bebdec063ee1">“<strong>Agentic ML Pipeline with Google ADK: No GCP Project Needed!</strong>”</a>. In that article, we built a sequential agent “squad” <em>entirely in a Colab notebook</em> using an in-memory session. It was a fantastic way to learn the fundamentals of the <a href="https://github.com/google/adk-python">Google Agent Development Kit (ADK)</a> with zero setup.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*d86edSmE1az70fSRcq49vw.gif" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*g934ZNPwv7YFcyIhPoGqJA.gif" /><figcaption>Real-Time OmniCommerce Agent in action with ADK web</figcaption></figure><p>Now, we’re taking the crucial next step.</p><p>We are moving from a stateless, local-only prototype to a stateful, production-aware agent that connects to a real cloud backend. This time, <strong>a Google Cloud project is required</strong>, and this two-part series will explore <em>why</em> that is non-negotiable for building a reliable, scalable agent.</p><p>We will architect the <strong>“OmniCommerce Genius,”</strong> a full-stack AI <strong>Retail Concierge</strong>.</p><ul><li><strong>In Part 1 (this post),</strong> we will obsess over the foundation. We’ll architect the <strong>transactional core</strong>, focusing on the <a href="https://cloud.google.com/bigquery">Google BigQuery</a> data layer, the foundational tools (cart, inventory), and solving critical concurrency challenges like <strong>race conditions</strong> to make our agent reliable.</li><li><strong>In Part 2,</strong> we’ll build the <strong>intelligence layer</strong> on this solid foundation, exploring AI-driven workflows (a proactive meal planner), high-performance ML with <a href="https://jax.readthedocs.io/en/latest/">JAX</a>, and the final deployment path to a production-grade <a href="https://cloud.google.com/vertex-ai/generative-ai/docs/agent-engine/deploy">Vertex AI Agent Engine</a>.</li></ul><h3>The Customer Journey: Why the Foundation Matters</h3><p>An agent’s intelligence is a liability if its core transactions fail. Before we write any AI prompts, let’s understand the complex, real-time demands our agent must handle.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_vybjuTukeyvnq9Z1d5Yuw.png" /></figure><h4>Journey 1: Priya, the Meticulous Planner</h4><p>Priya is planning for Diwali. Her journey is complex and crosses multiple retail domains.</p><ol><li><strong>Finance &amp; Gifting:</strong> She starts with a local budget: <em>“I’m looking for Diwali gift ideas under 5000 INR.”</em></li><li><strong>Agent Response (Tool: </strong><strong>convert_currency):</strong> The agent first calls an external API, replying, <em>&quot;OK. 5000 INR converts to $56.83 USD. I&#39;ll use that for my search.&quot;</em> It then calls its get_diwali_gifting_ideas tool.</li><li><strong>Cross-Domain Pivot (Fashion):</strong> Impressed, she continues, <em>“That’s great. Now, I need a new kurta for the event.”</em></li><li><strong>Agent Response (Tool: </strong><strong>find_diwali_specials + </strong><strong>check_stock_level):</strong> The agent finds a &quot;Men&#39;s Silk Kurta (Blue)&quot; (Item 403). Priya asks, <em>&quot;How many can I buy?&quot;</em> The agent checks stock and replies, <em>&quot;There are 50 in stock.&quot;</em></li><li><strong>The Transaction (Tool: </strong><strong>process_transaction):</strong> Priya adds 49 to her cart and says, <em>&quot;Let&#39;s buy them with my card.&quot;</em> The agent calls process_transaction. This tool not only &quot;completes&quot; the sale but also <strong>atomically updates the </strong><strong>inventory_count in BigQuery from 50 to 1.</strong></li></ol><p><strong>Takeaway:</strong> Priya’s journey requires a system that is multi-domain (finance, seasonal, fashion), stateful (managing a cart), and <strong>transactionally robust</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PNPam7odmYtshgpd2CCM4Q.png" /></figure><h4>Journey 2: Rohan, the Spontaneous Chef</h4><p>Rohan is at home. His journey is creative and utility-driven.</p><ol><li><strong>Creative Prompt:</strong> He opens the app and says, <em>“I have some chicken and lemons. What can I make for dinner?”</em></li><li><strong>Agent Response (Tool: </strong><strong>build_meal_plan):</strong> The agent recognizes the &quot;Grocery&quot; domain. It finds a &quot;Lemon Herb Chicken&quot; recipe.</li><li><strong>Proactive Assistance:</strong> It then cross-references the recipe with his “pantry” (which could be his recent purchases) and presents a one-click shopping list for the missing items.</li></ol><p><strong>Takeaway:</strong> Rohan’s journey shows the agent’s ability to pivot from a “seller” to a “utility,” turning a simple query into an actionable, value-added shopping experience.</p><h3>Prerequisites: Setting up your agent workshop</h3><p>Before we can build, we need to set up our workshop. This guide assumes you’re on a macOS or Linux-based system.</p><p><strong>1. Google Cloud setup:</strong></p><ul><li><strong>Create a Google Cloud Project:</strong> If you don’t have one already, create a new project in the <a href="https://console.cloud.google.com/">Google Cloud Console</a>.</li><li><strong>Enable APIs:</strong> In your new project, enable the <strong>BigQuery API</strong> and the <strong>Vertex AI API</strong>. This allows our agent to use these services.</li><li><strong>Install the </strong><strong>gcloud CLI:</strong> Follow the instructions to <a href="https://cloud.google.com/sdk/docs/install">install the Google Cloud SDK</a>.</li><li><strong>Authenticate:</strong> Log in with your Google account by running:</li></ul><pre>gcloud auth application-default login</pre><p><strong>2. Local development environment:</strong></p><ul><li><strong>Python:</strong> Ensure you have Python 3.10 or higher installed.</li><li><strong>Create a Virtual Environment:</strong> This is crucial for managing dependencies.</li></ul><pre>python3 -m venv venv source venv/bin/activate</pre><ul><li><strong>Install dependencies:</strong> We’ll need a few Python libraries for Aura.</li></ul><pre>pip install google-adk google-cloud-bigquery pandas requests jax jaxlib</pre><p><strong>3. Configure your Gemini API key:</strong></p><ul><li><strong>Get Your Key:</strong> Obtain your Gemini API key from the <a href="https://ai.google.dev/">Google AI for Developers</a> website.</li><li><strong>Create a </strong><strong>.env file:</strong> This file will securely store your API key. Inside the /tourism_assistant directory (which you will create inside the adk folder), create a new file named .env.</li><li><strong>Verify the file:</strong> Sometimes this file can be hidden. You can check that it exists using the command ls -la tourism_assistant. You should see .env in the list.</li><li><strong>Add your key:</strong> Open the .env file and add the following line, replacing &quot;your-key-here&quot; with your actual key:</li></ul><pre>GOOGLE_API_KEY=&quot;your-key-here&quot;</pre><p>With your workshop set up, you’re ready now to build!</p><p>To build this agent, we adopt a clean, three-part architectural model:</p><ol><li><strong>The Agent Development Kit (ADK):</strong> This is our <strong>developer’s workbench</strong>. As highlighted in the <a href="https://www.google.com/search?q=https://cloud.google.com/vertex-ai/docs/agent-engine/develop-an-agent">Vertex AI documentation</a>, the ADK is a template “designed based on Google’s internal best practices.” It provides the core Agent and FunctionTool classes that bridge our Python code with the Gemini model, allowing for rapid, robust prototyping.</li><li><strong>The Model Context Protocol (MCP) Server:</strong> This is an <strong>architectural pattern</strong>. An MCP server’s job is to expose tools (especially complex ones like database queries) to an agent over a network. The ADK’s local web server (adk web) implicitly acts as our development MCP server.</li><li><strong>The Agent Engine:</strong> This is our <strong>production deployment environment</strong>. While the ADK is our local engine, a true Agent Engine is a scalable, managed platform like <strong>Google Cloud Run</strong> or <strong>Vertex AI Agent Engine</strong>. This platform is framework-agnostic; while we’ve chosen the ADK, it can also host agents built with LangGraph, or even multi-agent systems communicating via the A2A (Agent2Agent) protocol.</li></ol><h3>The Anatomy of the Genius (Part 1): The Transactional Core</h3><p>Before our agent can be “intelligent,” it must be <em>reliable</em>. This reliability is built on two pillars: a solid data backbone and bulletproof transactional logic.</p><h4>1. The Data Backbone: Google BigQuery</h4><p>We chose <strong>Google BigQuery</strong> as our primary data warehouse. Its serverless, auto-scaling nature means we can handle massive product catalogs and millions of user transactions without managing infrastructure. Our data model is unified, containing tables for:</p><ul><li><strong>MasterProductCatalog</strong>: The single source of truth for all items.</li><li><strong>StoreInfo &amp; </strong><strong>FoodCourtTenants</strong>: For our omni-channel, in-store capabilities.</li><li><strong>UserCarts</strong>: A transactional table for active user sessions.</li><li><strong>UserPurchaseHistory</strong>: The foundation for future personalization.</li><li><strong>DiwaliGiftBundles</strong>: A seasonal, pre-curated table demonstrating event-driven marketing.</li></ul><p>A snippet of our MasterProductCatalog schema highlights its richness. The inventory_count is critical for Part 1, and the style_embedding vector is the key to the advanced AI we&#39;ll build in Part 2.</p><pre># --- BigQuery Schema for MasterProductCatalog ---<br># We define this in our initialization script<br>schema = [<br>    bigquery.SchemaField(&quot;item_id&quot;, &quot;STRING&quot;, mode=&quot;REQUIRED&quot;),<br>    bigquery.SchemaField(&quot;name&quot;, &quot;STRING&quot;),<br>    bigquery.SchemaField(&quot;category&quot;, &quot;STRING&quot;),<br>    bigquery.SchemaField(&quot;price&quot;, &quot;FLOAT64&quot;),<br>    <br>    # Critical for transactional logic<br>    bigquery.SchemaField(&quot;inventory_count&quot;, &quot;INTEGER&quot;),<br>    <br>    # Rich metadata for search and AI (Part 2)<br>    bigquery.SchemaField(&quot;search_tags&quot;, &quot;STRING&quot;, mode=&quot;REPEATED&quot;),<br>    bigquery.SchemaField(&quot;style_embedding&quot;, &quot;FLOAT64&quot;, mode=&quot;REPEATED&quot;), <br>]<br><br>db_client = bigquery.Client()<br>table = bigquery.Table(f&quot;{GCP_PROJECT_ID}.{DATASET_ID}.{CATALOG_TABLE}&quot;, schema=schema)<br>db_client.create_table(table)</pre><h4>2. The Presentation Engine: _format_response</h4><p>A raw JSON output is accurate for a machine but terrible for a human. A core component of our architecture is a single, centralized tool named _format_response.</p><p>The agent’s master prompt <em>forces</em> it to send the final JSON output from <em>any</em> other tool into this one formatting tool. This _format_response function acts as a <strong>Presentation Engine</strong>, converting data into beautiful, human-readable markdown. This design pattern enforces a clean <strong>separation of concerns</strong>:</p><ul><li><strong>Tools (</strong><strong>find_products, etc.):</strong> Focus <em>only</em> on fetching data and returning raw JSON.</li><li><strong>Formatter (</strong><strong>_format_response):</strong> Focuses <em>only</em> on presenting that JSON in an elegant way.</li></ul><pre># --- Tool 0: The Presentation Engine ---<br>def _format_response(tool_json: str) -&gt; str:<br>    &quot;&quot;&quot;<br>    (AGENT TOOL) Central helper to format all tool outputs beautifully.<br>    This is the &quot;Presentation Engine&quot;.<br>    &quot;&quot;&quot;<br>    try:<br>        data = json.loads(tool_json)<br>        # --- Global Error Handler ---<br>        if &quot;error&quot; in data:<br>            # Format any error from any tool consistently<br>            return f&quot;**😕 I ran into a problem.**\n\n&gt; {data[&#39;error&#39;]}&quot;<br><br>        tool_name = data.get(&quot;tool_name&quot;, &quot;&quot;)<br><br>        # --- Formatter for: get_diwali_gifting_ideas ---<br>        if tool_name == &quot;get_diwali_gifting_ideas&quot;:<br>            bundle = data.get(&#39;bundle&#39;, {})<br>            items = bundle.get(&#39;items&#39;, [])<br>            response = [f&quot;## 🎁 Your Diwali Gift Idea 🎁\n&quot;]<br>            response.append(f&quot;I recommend the **{bundle.get(&#39;plan_name&#39;)}**!\n&quot;)<br>            response.append(&quot;| Item | Price |&quot;)<br>            response.append(&quot;| :--- | :--- |&quot;)<br>            for item in items:<br>                response.append(f&quot;| {item[&#39;name&#39;]} | ${item[&#39;price&#39;]:.2f} |&quot;)<br>            response.append(&quot;\n---\n&quot;)<br>            response.append(f&quot;### **Total Bundle Price: ${bundle.get(&#39;budget_tier_usd&#39;):,.2f}**&quot;)<br>            return &quot;\n&quot;.join(response)<br>        # --- Formatter for: convert_currency ---<br>        if tool_name == &quot;convert_currency&quot;:<br>            to_currency = data.get(&#39;to_currency&#39;, &#39;USD&#39;)<br>            converted_amount = data.get(&#39;converted_amount&#39;, 0)<br>            prefix = &quot;$&quot; if to_currency == &quot;USD&quot; else &quot;&quot; # Dynamic symbol<br>            <br>            return f&quot;Got it. Just so you know, **{data.get(&#39;original_amount&#39;):,.2f} {data.get(&#39;from_currency&#39;)}** is about **{prefix}{converted_amount:,.2f} {to_currency.lower()}**. I&#39;ll use that for my search.&quot;<br>        # ... (Dozens of other formatters for every other tool) ...<br>        # --- Fallback for tools without a formatter ---<br>        return json.dumps(data, indent=2)<br><br>    except Exception as e:<br>        return f&quot;**System Error:** I had trouble formatting my response. {e}\nRaw Data: {tool_json}&quot;</pre><h4>3. The External API Gateway: convert_currency</h4><p>This tool shows how the agent connects to the outside world. It’s fully dynamic, handling any from or to currency. This is vital for two reasons:</p><ul><li><strong>User-Facing:</strong> Answering queries like <em>“how much is 50 USD in INR?”</em></li><li><strong>Internal Budgeting:</strong> Handling queries like Priya’s <em>“gifts under 5000 INR,”</em> by converting that amount to USD <em>before</em> searching the database.</li></ul><p>This ability for a model to decide <em>how</em> and <em>when</em> to use external tools is a core concept explored in the foundational <a href="https://arxiv.org/abs/2302.04761"><strong>Toolformer</strong></a> research paper.</p><pre># --- Tool 5: Currency Conversion (FIXED) ---<br>def convert_currency(amount: float, from_currency: str, to_currency: str = &quot;USD&quot;) -&gt; str:<br>    &quot;&quot;&quot;Converts an amount from one currency to another using an API.&quot;&quot;&quot;<br>    try:<br>        from_currency_upper = from_currency.upper()<br>        to_currency_upper = to_currency.upper()<br><br>        # Using a free, public API for this example<br>        url = f&quot;https://api.frankfurter.app/latest?amount={amount}&amp;from={from_currency_upper}&amp;to={to_currency_upper}&quot;<br>        data = requests.get(url).json()<br>        converted_amount = data.get(&#39;rates&#39;, {}).get(to_currency_upper)<br>        <br>        if not converted_amount:<br>            return json.dumps({&quot;error&quot;: f&quot;Could not convert from &#39;{from_currency_upper}&#39; to &#39;{to_currency_upper}&#39;.&quot;})<br>        <br>        # Pass dynamic keys to the formatter<br>        return json.dumps({<br>            &quot;tool_name&quot;: &quot;convert_currency&quot;, <br>            &quot;original_amount&quot;: amount, <br>            &quot;from_currency&quot;: from_currency_upper,<br>            &quot;converted_amount&quot;: converted_amount,<br>            &quot;to_currency&quot;: to_currency_upper<br>        })<br><br>    except Exception as e: <br>        return json.dumps({&quot;error&quot;: f&quot;Currency conversion API failed: {e}&quot;}) </pre><h4>4. The Transactional Tools: Conquering Concurrency</h4><p>This is the most critical technical challenge for any <em>real</em> e-commerce agent. A naive implementation will fail under load.</p><p><strong>The Caution: </strong>Race Conditions &amp; BigQuery’s Nuances</p><p>A “check-then-act” logic (e.g., check_stock_level then process_transaction) creates a classic race condition. Imagine:</p><ul><li>User A asks: “How many kurtas (Item 403) are left?” Agent: “There are 50.”</li><li>User B asks: “How many kurtas (Item 403) are left?” Agent: “There are 50.”</li><li>User A buys 49. The transaction processes. inventory_count is now 1.</li><li>User B tries to buy 49. Their transaction <em>also</em> processes (if naively written) or fails cryptically. We have oversold our inventory because our “check” and “act” were not <strong>atomic</strong>.</li></ul><p>Furthermore, BigQuery has specific limitations. Using fast streaming inserts (insert_rows_json) for add_to_cart places data in a &quot;streaming buffer.&quot; This buffer <strong>locks the table</strong> from DML operations (UPDATE, DELETE), meaning our process_transaction tool would fail!</p><p><strong>The Robust Solution: Unified DML</strong></p><p>We solve <em>both</em> problems with one architectural decision: <strong>We will not use streaming inserts.</strong> We will use standard SQL DML for all cart and inventory operations.</p><p><strong>Tool 1: add_to_cart (Using DML)</strong></p><p>This tool uses a standard INSERT query. This avoids the streaming buffer entirely, making it compatible with our other transactional tools.</p><pre># --- Tool 11: Add to Cart (FIXED with Standard SQL) ---<br>def add_to_cart(user_id: str, item_id: str, quantity: int) -&gt; str:<br>    &quot;&quot;&quot;Adds a specified quantity of an item to the user&#39;s cart using standard SQL.&quot;&quot;&quot;<br>    try:<br>        # Use a standard INSERT DML query to avoid streaming buffer conflicts.<br>        query = f&quot;&quot;&quot;<br>            INSERT INTO `{CART_ID}` (user_id, item_id, quantity, added_at)<br>            VALUES (@p_user_id, @p_item_id, @p_quantity, CURRENT_TIMESTAMP())<br>        &quot;&quot;&quot;<br>        <br>        params = [<br>            bigquery.ScalarQueryParameter(&quot;p_user_id&quot;, &quot;STRING&quot;, user_id),<br>            bigquery.ScalarQueryParameter(&quot;p_item_id&quot;, &quot;STRING&quot;, item_id),<br>            bigquery.ScalarQueryParameter(&quot;p_quantity&quot;, &quot;INTEGER&quot;, quantity),<br>        ]<br>        job_config = bigquery.QueryJobConfig(query_parameters=params)<br>        <br>        db_client.query(query, job_config=job_config).result() # Run and wait<br>        <br>        return json.dumps({&quot;tool_name&quot;: &quot;add_to_cart&quot;, &quot;success&quot;: f&quot;Item {item_id} added to cart.&quot;})<br>        <br>    except Exception as e:<br>        return json.dumps({&quot;error&quot;: f&quot;Failed to add to cart: {e}&quot;})</pre><p><strong>Tool 2: process_transaction (Atomic Update)</strong></p><p>This is the star of our transactional core. It performs the inventory check and update in a single, atomic DML statement.</p><pre># --- Tool 15: Process Transaction (FIXED with Atomic Inventory Update) ---<br>def process_transaction(user_id: str, payment_method: str) -&gt; str:<br>    &quot;&quot;&quot;<br>    Processes the payment, ATOMICALLY updates item inventory, and clears the user&#39;s cart.<br>    &quot;&quot;&quot;<br>    try:<br>        # 1. Get all items from the user&#39;s cart<br>        cart_data = json.loads(view_cart(user_id))<br>        items_in_cart = cart_data.get(&#39;items&#39;, [])<br>        if not items_in_cart:<br>            return json.dumps({&quot;error&quot;: &quot;Your cart is empty.&quot;})<br><br>        amount = cart_data.get(&#39;total_price&#39;, 0)<br>        <br>        # --- ATOMIC INVENTORY LOGIC ---<br>        for item in items_in_cart:<br>            item_id = item[&#39;item_id&#39;]<br>            quantity_purchased = item[&#39;quantity&#39;]<br>            <br>            # This query is atomic. It will only update rows<br>            # WHERE the inventory is sufficient.<br>            update_query = f&quot;&quot;&quot;<br>                UPDATE `{CATALOG_ID}`<br>                SET inventory_count = inventory_count - @p_quantity<br>                WHERE item_id = @p_item_id <br>                  AND inventory_count &gt;= @p_quantity <br>            &quot;&quot;&quot;<br>            params = [<br>                bigquery.ScalarQueryParameter(&quot;p_quantity&quot;, &quot;INTEGER&quot;, quantity_purchased),<br>                bigquery.ScalarQueryParameter(&quot;p_item_id&quot;, &quot;STRING&quot;, item_id),<br>            ]<br>            update_job = db_client.query(update_query, job_config=bigquery.QueryJobConfig(query_parameters=params))<br>            update_job.result() # Wait for the update to finish<br>            <br>            # 3. Check if the update was successful (i.e., if rows were affected)<br>            if update_job.num_dml_affected_rows == 0:<br>                # The database itself rejected the transaction.<br>                # This is the correct way to handle a race condition.<br>                return json.dumps({&quot;error&quot;: f&quot;Sale failed: Not enough stock for item {item_id}.&quot;})<br>        <br>        # --- END ATOMIC LOGIC ---<br>        <br>        # 4. If all stock updates succeeded, clear the cart (also a DML op)<br>        clear_cart(user_id)<br>        # 5. Generate order confirmation<br>        order_id = str(uuid.uuid4()).split(&#39;-&#39;)[0].upper()<br>        <br>        return json.dumps({<br>            &quot;tool_name&quot;: &quot;process_transaction&quot;, <br>            &quot;order_id&quot;: order_id, <br>            &quot;amount&quot;: amount, <br>            &quot;payment_method&quot;: payment_method, <br>            &quot;status&quot;: &quot;Purchase complete and inventory updated.&quot;<br>        })<br>        <br>    except Exception as e:<br>        return json.dumps({&quot;error&quot;: f&quot;Transaction failed: {e}&quot;})</pre><h3>Part 1 Conclusion: A Rock-Solid Foundation</h3><p>We have now successfully built the transactional core of the OmniCommerce Genius. We have a:</p><ul><li><strong>Brain:</strong> A <a href="https://deepmind.google/technologies/gemini/">Gemini</a>-powered <a href="https://www.google.com/search?q=https://github.com/GoogleCloudPlatform/adk">ADK</a> agent.</li><li><strong>Backbone:</strong> A robust and scalable <a href="https://cloud.google.com/bigquery">BigQuery</a> data model.</li><li><strong>Transactional Core:</strong> A set of essential, conflict-free tools for browsing, cart management, and real-time, <strong>atomic</strong> inventory-aware checkout.</li><li><strong>Polished Voice:</strong> A decoupled presentation engine for a premium user experience.</li></ul><p>With this solid, production-aware foundation in place, we are ready to move beyond basic transactions. <strong>In </strong><a href="https://medium.com/@aniketagrawal_14703/real-time-omnicommerce-agents-part-2-intelligence-layer-b652ad9fc038"><strong>Part 2</strong></a><strong>,</strong> we will explore the <strong>intelligence layer</strong>: building the AI-driven build_meal_plan tool, creating a personal stylist with our high-performance <a href="https://jax.readthedocs.io/en/latest/">JAX</a> generate_stylefusion_item function, and discussing the final deployment path to a production <a href="https://www.google.com/search?q=https://cloud.google.com/vertex-ai/docs/agent-engine/develop-an-agent">Vertex AI Agent Engine</a>.</p><h3>References and Further Reading</h3><p>Ready to start your own agent-building journey? Here are the official resources and foundational research to get you started.</p><h4>Official documentation</h4><ul><li><a href="https://github.com/google/adk-python"><strong>Agent Development Kit (ADK) on GitHub</strong></a>: The official repository for the ADK.</li><li><a href="https://cloud.google.com/vertex-ai/generative-ai/docs/agent-development-kit/quickstart"><strong>ADK Quickstart</strong></a>: The official starting point for the ADK.</li><li><a href="https://github.com/google/adk-samples"><strong>ADK Samples</strong></a>: Sample agents under ADK Repo.</li><li><a href="https://ai.google.dev/"><strong>Google AI for Developers</strong></a>: Your central hub for Gemini API documentation, tutorials, and examples.</li><li><a href="https://cloud.google.com/bigquery/docs"><strong>BigQuery Documentation</strong></a>: Learn more about how to manage and query data at scale.</li><li><a href="https://cloud.google.com/run/docs"><strong>Cloud Run Documentation</strong></a>: A complete guide to deploying and managing serverless applications.</li></ul><h4><strong>Data and Compute</strong></h4><ul><li><a href="https://cloud.google.com/bigquery/docs/reference/standard-sql/data-manipulation-language"><strong>Google BigQuery DML Documentation</strong></a><strong>:</strong> Official guide on using UPDATE, INSERT, and DELETE.</li><li><a href="https://cloud.google.com/bigquery/docs"><strong>Managing Data in BigQuery</strong></a><strong>:</strong> Best practices for data manipulation and storage.</li></ul><h4>Foundational research papers</h4><ul><li><a href="https://arxiv.org/abs/2210.03629"><strong>ReAct: Synergizing Reasoning and Acting in Language Models (Yao, et al., 2022)</strong></a>: A groundbreaking paper that introduced the “Reason, Act” paradigm, which is fundamental to how modern agents like OmniCommerce decide which tool to use.</li><li><a href="https://arxiv.org/abs/2302.04761"><strong>Toolformer: Language Models Can Teach Themselves to Use Tools (Schick, et al., 2023)</strong></a>: This paper demonstrates how LLMs can learn to use external tools through simple APIs, a core concept in our agent’s design.</li><li><a href="https://arxiv.org/abs/2201.11903"><strong>Chain of Thought Prompting Elicits Reasoning in Large Language Models (Wei, et al., 2022)</strong></a>: While not strictly about agents, this paper is essential for understanding how to prompt models to perform complex, multi-step reasoning, which is the basis for our agent’s “Master Workflow.”</li></ul><h4>Related Assets</h4><ul><li><a href="https://medium.com/@aniketagrawal_14703/real-time-omnicommerce-agents-part-2-intelligence-layer-b652ad9fc038"><strong>Real-Time OmniCommerce Agents (Part 2: ADK-JAX Intelligence Layer)</strong></a></li><li><a href="https://drive.google.com/file/d/1fQtVeRPmwoIGVPtk8luk8jyFUJgG-hIT/view?usp=drive_link"><strong>OmniCommerce ADK Demo Video (4K)</strong></a></li><li><a href="https://drive.google.com/file/d/1WXqgveGHQRt3dPsSglCNr-pCx5hBclsS/view?usp=drive_link"><strong>OmniCommerce Agent Code</strong></a></li><li><a href="https://discuss.google.dev/t/build-aura-genai-travel-concierge-with-adk/274125"><strong>Build Aura: GenAI Travel Concierge with ADK</strong></a></li><li><a href="https://drive.google.com/file/d/1Tr_HXOC1oweVJzvNa84J4beYB_9ahM3c/view?usp=drive_link"><strong>Aura Demo Video (4K)</strong></a></li><li><a href="https://drive.google.com/file/d/1qGfLc8iFXmvq6oW-rDvHDtOxXJ-iB-XW/view?usp=drive_link"><strong>Aura Agent Code</strong></a></li></ul><p>We can’t wait to see what you build. Share your creations and ask questions in the Google Cloud Community. Happy coding!</p><p><strong>Let’s keep the conversation going! Share your thoughts, questions, and ideas in the comments.</strong></p><p><strong>Note:</strong> <em>Should you have any concerns or queries about this post or my implementation, please feel free to connect with me on </em><a href="https://www.linkedin.com/in/aniket-agrawal-a18990266/"><em>LinkedIn</em></a><em>! Thanks!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ecfba3933981" width="1" height="1" alt=""><hr><p><a href="https://medium.com/google-cloud/real-time-omnicommerce-agents-part-1-adk-transaction-core-ecfba3933981">Real-Time OmniCommerce Agents (Part 1: ADK-BQ Transaction Core)</a> was originally published in <a href="https://medium.com/google-cloud">Google Cloud - Community</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Agentic ML Pipeline with Google ADK: No GCP Project Needed!]]></title>
            <link>https://medium.com/google-cloud/agentic-ml-pipeline-with-adk-no-gcp-project-needed-bebdec063ee1?source=rss-13a446e68524------2</link>
            <guid isPermaLink="false">https://medium.com/p/bebdec063ee1</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[agent-development-kit]]></category>
            <category><![CDATA[health]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[google-adk]]></category>
            <dc:creator><![CDATA[Aniket Agrawal]]></dc:creator>
            <pubDate>Tue, 07 Oct 2025 10:33:34 GMT</pubDate>
            <atom:updated>2025-10-13T09:07:53.240Z</atom:updated>
            <content:encoded><![CDATA[<h4>Tired of monolithic scripts and tangled ML workflows?</h4><p>In this beginner-friendly tutorial, we’re going to build a complete machine learning pipeline to predict patient readmission. But here’s the twist: we’ll assemble a “squad” of ML agents to do the heavy lifting. Each agent will have a specific job, from fetching data to training the model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*SrpEH1qViX0K3Of5xPdEzQ.gif" /><figcaption>Multi-Agent System GIF by Veo 4</figcaption></figure><p>And the best part? You can build and run this entire project in a Google Colab notebook <strong>without needing a Google Cloud project or a credit card.</strong> All you need is your curiosity and the power of the open-source <a href="https://google.github.io/adk-docs/"><strong>Google Agent Development Kit (ADK)</strong></a>.</p><p><strong>Notebook link:</strong> <strong>👉 </strong><a href="https://colab.sandbox.google.com/drive/1a9vJI0Fg2PKy8WApnLjrUICaAcImpZtt#scrollTo=c_bpV2Vwa7gR">Simply open the notebook in Google Colab!</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2TaNHp3BPvb0ro8b1gcaLw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*E7JsbmvfTI0R6aOic24jfg.png" /><figcaption>Left: Image generated by Gemini 2.5 pro, Right: Google ADK Logo</figcaption></figure><h3>Why Use AI Agents for MLOps? 🤖</h3><p>Traditional machine learning pipelines can quickly become a complex web of scripts for data ingestion, preprocessing, training, and evaluation. This can be difficult to manage, debug, and scale. The agentic approach, powered by frameworks like Google ADK, changes the game. Think of it like managing a project: instead of doing everything yourself, you hire specialists.</p><ul><li><strong>Clarity and Modularity</strong>: Each agent has one responsibility. This makes the entire workflow incredibly easy to understand.</li><li><strong>Reusability</strong>: Need to load data for a different project? You can reuse your DataIngestionAgent without modification.</li><li><strong>Maintainability</strong>: If you need to change your training logic, you only update the ModelTrainingAgent, leaving the rest of the pipeline untouched.</li></ul><p>It’s a shift from writing a single, complex program to orchestrating a team of efficient, single-tasked workers.</p><h3>Prerequisites 🛠️</h3><p>Before we dive in, let’s get our environment set up. It’s quick and easy!</p><ol><li><strong>A Google Account</strong>: To run the notebook in Google Colab.</li><li><strong>Basic Knowledge</strong>: A general understanding of Python and machine learning concepts will be helpful.</li><li><strong>Required Libraries</strong>: The entire project relies on a few key open-source libraries. You can install them by running the following command in the first cell of the Colab notebook:</li></ol><pre>! pip install --upgrade --user --quiet torch scikit-learn pandas numpy matplotlib seaborn tqdm google-adk</pre><p>That’s it! You’re ready to build.</p><h3>Meet the AI Agent Squad</h3><p>In our notebook, we build a pipeline by assembling three specialist agents. They are surprisingly easy to define. Let’s meet the team and look at their code.</p><h4>1. The Data Librarian (DataIngestionAgent)</h4><p>This agent’s sole purpose is to locate and load the dataset. It checks if the diabetic_data.csv file exists and loads it into the shared session state for the next agent. Simple, reliable, and focused.</p><pre>class DataIngestionAgent(BaseAgent):<br>    &quot;&quot;&quot;An agent responsible for loading the patient dataset.&quot;&quot;&quot;<br>    name: str = &quot;DataIngestionAgent&quot;<br><br>    async def _run_async_impl(self, ctx: InvocationContext) -&gt; AsyncGenerator[Event, None]:<br>        yield Event(author=self.name, content=genai_types.Content(parts=[genai_types.Part(text=&quot;Starting data ingestion...&quot;)]))<br><br>        data_path = &#39;diabetic_data.csv&#39;<br>        if not os.path.exists(data_path):<br>            error_msg = f&quot;ERROR: Dataset &#39;{data_path}&#39; not found. Cannot proceed.&quot;<br>            yield Event(author=self.name, content=genai_types.Content(parts=[genai_types.Part(text=error_msg)]))<br>            yield Event(author=self.name, actions=Event.EventActions(escalate=True))<br>            return<br><br>        yield Event(author=self.name, content=genai_types.Content(parts=[genai_types.Part(text=f&quot;Found data file: {data_path}&quot;)]))<br>        df = pd.read_csv(data_path)<br>        <br>        # Store the raw dataframe in the shared session state<br>        ctx.session.state[&#39;raw_dataframe&#39;] = df<br><br>        yield Event(author=self.name, content=genai_types.Content(parts=[genai_types.Part(text=f&quot;Successfully loaded {len(df)} patient records. Data is now in session state.&quot;)]))</pre><h4>2. The Data Cleaner (FeatureEngineeringAgent)</h4><p>Once the Data Librarian passes off the raw data, this agent takes over. It performs crucial cleaning tasks: handling missing values (?), dropping irrelevant columns, and preparing the dataset for the model.</p><pre>class FeatureEngineeringAgent(BaseAgent):<br>    &quot;&quot;&quot;An agent that cleans and prepares the data for modeling.&quot;&quot;&quot;<br>    name: str = &quot;FeatureEngineeringAgent&quot;<br><br>    async def _run_async_impl(self, ctx: InvocationContext) -&gt; AsyncGenerator[Event, None]:<br>        yield Event(author=self.name, content=genai_types.Content(parts=[genai_types.Part(text=&quot;Starting data cleaning and feature engineering...&quot;)]))<br><br>        raw_df = ctx.session.state.get(&#39;raw_dataframe&#39;)<br>        if raw_df is None:<br>            # Error handling if the previous agent failed<br>            yield Event(author=self.name, content=genai_types.Content(parts=[genai_types.Part(text=&quot;Error: Raw dataframe not found in session state.&quot;)]))<br>            yield Event(author=self.name, actions=Event.EventActions(escalate=True))<br>            return<br>        <br>        # Basic data cleaning<br>        processed_df = raw_df.copy()<br>        processed_df = processed_df.replace(&#39;?&#39;, np.nan)<br>        processed_df.drop([&#39;weight&#39;, &#39;payer_code&#39;, &#39;medical_specialty&#39;, &#39;encounter_id&#39;, &#39;patient_nbr&#39;], axis=1, inplace=True)<br>        processed_df.dropna(inplace=True)<br>        <br>        ctx.session.state[&#39;processed_dataframe&#39;] = processed_df<br>        yield Event(author=self.name, content=genai_types.Content(parts=[genai_types.Part(text=f&quot;Data cleaning and preparation complete. Processed dataframe is now in session state.&quot;)]))</pre><h4>3. The Master Trainer (ModelTrainingAgent)</h4><p>This is the core of our operation. The Master Trainer takes the cleaned data and orchestrates the entire PyTorch training and evaluation process by calling a standalone function. It then places the final results back into the session state.</p><pre>class ModelTrainingAgent(BaseAgent):<br>    &quot;&quot;&quot;An agent that orchestrates the model training and evaluation process.&quot;&quot;&quot;<br>    name: str = &quot;ModelTrainingAgent&quot;<br><br>    async def _run_async_impl(self, ctx: InvocationContext) -&gt; AsyncGenerator[Event, None]:<br>        yield Event(author=self.name, content=genai_types.Content(parts=[genai_types.Part(text=&quot;Initializing model training and evaluation pipeline...&quot;)]))<br><br>        processed_df = ctx.session.state.get(&#39;processed_dataframe&#39;)<br>        if processed_df is None:<br>            yield Event(author=self.name, content=genai_types.Content(parts=[genai_types.Part(text=&quot;Error: Processed dataframe not found in session state.&quot;)]))<br>            yield Event(author=self.name, actions=Event.EventActions(escalate=True))<br>            return<br><br>        config = ModelConfig(output_dir=&#39;./readmission_agentic_model&#39;)<br>        yield Event(author=self.name, content=genai_types.Content(parts=[genai_types.Part(text=f&quot;Configuration created. Artifacts will be saved to &#39;{config.BASE_OUTPUT_DIR}&#39;&quot;)]))<br><br>        # This agent calls the complex ML logic function<br>        training_results = execute_training_and_evaluation(processed_df, config)<br><br>        ctx.session.state[&#39;training_results&#39;] = training_results<br>        yield Event(author=self.name, content=genai_types.Content(parts=[genai_types.Part(text=f&quot;Model training and evaluation complete. Results: {json.dumps(training_results, indent=2)}&quot;)]))</pre><h3>The Blueprint: Assembling the Pipeline</h3><p>With our specialists defined, we just need to put them in order. The ADK makes this incredibly intuitive. First, we define our core ML logic, like this PyTorch model.</p><p><strong>Notice this code is completely separate from the agents</strong>, making it easy to test and manage.</p><pre>class ReadmissionClassifier(torch.nn.Module):<br>    &quot;&quot;&quot;A simple neural network for readmission classification.&quot;&quot;&quot;<br>    def __init__(self, n_features, n_classes, dropout_rate):<br>        super(ReadmissionClassifier, self).__init__()<br>        self.layer_1 = torch.nn.Linear(n_features, 128)<br>        self.layer_2 = torch.nn.Linear(128, 64)<br>        self.layer_out = torch.nn.Linear(64, n_classes)<br>        <br>        self.relu = torch.nn.ReLU()<br>        self.dropout = torch.nn.Dropout(p=dropout_rate)<br>        self.batchnorm1 = torch.nn.BatchNorm1d(128)<br>        self.batchnorm2 = torch.nn.BatchNorm1d(64)<br><br>    def forward(self, inputs):<br>        x = self.relu(self.layer_1(inputs))<br>        x = self.batchnorm1(x)<br>        x = self.relu(self.layer_2(x))<br>        x = self.batchnorm2(x)<br>        x = self.dropout(x)<br>        x = self.layer_out(x)<br>        return x</pre><p>Next, we instantiate our agents and use SequentialAgent to create the final pipeline. It&#39;s as simple as creating a list!</p><pre># Create an instance of each agent<br>data_ingestion_agent = DataIngestionAgent()<br>feature_engineering_agent = FeatureEngineeringAgent()<br>model_training_agent = ModelTrainingAgent()<br><br># Assemble them into an end-to-end pipeline<br>patient_readmission_pipeline = SequentialAgent(<br>    name=&quot;PatientReadmissionPipeline&quot;,<br>    sub_agents=[<br>        data_ingestion_agent,<br>        feature_engineering_agent,<br>        model_training_agent,<br>    ]<br>)</pre><p>Finally, we use the ADK Runner to execute the pipeline. This code sets up an in-memory session and kicks off the first agent.</p><pre>async def main():<br>    &quot;&quot;&quot;Main function to set up and run the ADK agent pipeline.&quot;&quot;&quot;<br>    session_service = InMemorySessionService()<br>    # ... session creation logic ...<br><br>    runner = Runner(agent=patient_readmission_pipeline, app_name=APP_NAME, session_service=session_service)<br>    <br>    print(&quot;--- STARTING AGENTIC PIPELINE ---&quot;)<br>    initial_message = genai_types.Content(role=&#39;user&#39;, parts=[genai_types.Part(text=&quot;Start the patient readmission prediction pipeline.&quot;)])<br>    <br>    async for event in runner.run_async(user_id=USER_ID, session_id=SESSION_ID, new_message=initial_message):<br>        if event.content:<br>            print(f&quot;[{event.author}]: {event.content.parts[0].text}\\n&quot;)<br><br>    print(&quot;--- AGENTIC PIPELINE COMPLETED ---&quot;)<br><br>await main()</pre><h3>Your Turn: Build It in 5 Minutes! 🚀</h3><p>Ready to command your own AI agent squad? You can run this entire project right now, for free.</p><p><strong>👉 </strong><a href="https://colab.sandbox.google.com/drive/1a9vJI0Fg2PKy8WApnLjrUICaAcImpZtt#scrollTo=c_bpV2Vwa7gR"><strong>Open the notebook in Google Colab! </strong></a>Simply follow these steps:</p><ol><li>Click the link above.</li><li>Run the first code cell to install the necessary libraries, including google-adk.</li><li>Execute the remaining cells one by one to define the agents and run the pipeline.</li></ol><p>You’ll see the agents reporting their progress in real-time as they work together to build, train, and evaluate a patient readmission prediction model.</p><h3>From Colab to Cloud: What’s Next in Our Series? ☁️</h3><p>This notebook is just the beginning! Running an agentic pipeline in Colab is fantastic for development and learning, but the real power comes when you scale it in the cloud. In our upcoming blog posts, we will take this exact agent squad and level them up:</p><ul><li><strong>Persistent State with Agent Engine</strong>: We’ll swap the InMemorySessionService for a persistent, cloud-based session, allowing our agents to remember conversations and handle long-running tasks.</li><li><strong>Scalable Infrastructure with MCP</strong>: We will deploy our agents to the <strong>Managed Compute Platform (MCP)</strong>, giving them a serverless, scalable, and secure environment to run in.</li><li><strong>Production-Grade Orchestration with Vertex AI Pipelines</strong>: Finally, we’ll show you how to integrate this entire agentic workflow into a robust, schedulable <strong>Vertex AI Pipeline</strong> for true, end-to-end MLOps automation.</li><li>Stay tuned as we take our agent squad from the local playground to a production-ready, cloud-native powerhouse! Follow to be notified of the next post in the series.</li></ul><p><strong>Let’s keep the conversation going! Share your thoughts, questions, and ideas in the comments.</strong></p><p><strong>Note:</strong> <em>Should you have any concerns or queries about this post or my implementation, please feel free to connect with me on </em><a href="https://www.linkedin.com/in/aniket-agrawal-a18990266/"><em>LinkedIn</em></a><em>! Thanks!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bebdec063ee1" width="1" height="1" alt=""><hr><p><a href="https://medium.com/google-cloud/agentic-ml-pipeline-with-adk-no-gcp-project-needed-bebdec063ee1">Agentic ML Pipeline with Google ADK: No GCP Project Needed!</a> was originally published in <a href="https://medium.com/google-cloud">Google Cloud - Community</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[NotebookLM: One-Click Accident Report Comprehension]]></title>
            <link>https://medium.com/google-cloud/notebooklm-one-click-accident-report-comprehension-d492ab6e9e4c?source=rss-13a446e68524------2</link>
            <guid isPermaLink="false">https://medium.com/p/d492ab6e9e4c</guid>
            <category><![CDATA[generative-ai-tools]]></category>
            <category><![CDATA[google-cloud-platform]]></category>
            <category><![CDATA[notebooklm]]></category>
            <category><![CDATA[aviation]]></category>
            <category><![CDATA[automation]]></category>
            <dc:creator><![CDATA[Aniket Agrawal]]></dc:creator>
            <pubDate>Wed, 23 Jul 2025 03:41:02 GMT</pubDate>
            <atom:updated>2025-07-31T13:51:57.721Z</atom:updated>
            <content:encoded><![CDATA[<p><em>A beginner-friendly and technical walkthrough on harnessing Generative AI to transform a dense, sensitive document into accessible multimedia briefings with the click of a button.</em></p><h3>Important Disclaimers</h3><h4>On Sensitivity and Technological Purpose</h4><p>The source material for this demonstration is the public preliminary accident report for <strong>Air India flight VT-ANB</strong> released recently. This is a serious and sensitive subject, and we extend our deepest respect and condolences to everyone affected by the incident.</p><h4>On the Factual Correctness of AI-Generated Content</h4><p>The outputs showcased below (summaries, FAQs, etc.) are generated by a large language model based on the source provided. They are a powerful starting point for analysis but are not a substitute for expert human verification. <strong>All AI-generated content should be critically reviewed for accuracy and completeness</strong> before being used in any decision-making process.</p><h3>Overview</h3><p>This article is <strong>not</strong> an analysis, interpretation, or commentary on the accident itself. It is a <strong>technical demonstration</strong> of Google Cloud’s NotebookLM, using the report solely as an example of a complex, real-world data source. Our focus remains entirely on the tool, its workflow, and its capabilities.</p><p>Technical teams, investigators, and leaders are often faced with the challenge of quickly understanding and communicating insights from dense, jargon-filled reports. Manually creating summaries, timelines, and FAQs is time-consuming and prone to human error. What if you could do it all with the click of a button?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rB6n4zyfBrOx9P6FvsXPQA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-MGE32jlD_D4AgsG19I7oQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pH1p8cDv-wKbaNSkZiC3SQ.png" /><figcaption>NotebookLM in action with it’s new feature ‘Video Overview’ rolled out on 29th July</figcaption></figure><p>This is the promise of tools like <strong>NotebookLM</strong>, a research and writing assistant grounded in your specific sources. To test this, we used a single, complex source — the <strong>preliminary investigation report for the Air India B787 aircraft, VT-ANB</strong> — to see if its built-in features could automatically generate a full suite of briefing materials.</p><h3>What is NotebookLM?</h3><p>Before we dive into the experiment, it’s important to understand what NotebookLM is. At its core, NotebookLM is a research and writing assistant designed to be <strong>grounded in your specific source materials</strong>. Unlike a general-purpose chatbot, its knowledge is limited to the documents you provide — be it PDFs, Google Docs, or transcripts. This allows it to act as an expert on <em>your</em> data, helping you find connections, summarize complex topics, and generate new content, all while providing citations back to the original source.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*UQBLa_djJhQgCevn.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*awrHPBw0exv84-VctI0a8w.png" /></figure><p>So, where does this fit with a tool like <strong>Vertex AI Agent Builder or AgentSpace or Agent Engine</strong>? Think of them as two sides of a powerful coin.</p><ul><li><strong>NotebookLM</strong> excels at the <strong>“comprehension and synthesis”</strong> phase. It’s the ideal environment for a human user to deeply understand a complex issue, like analyzing an incident report or synthesizing feedback from multiple documents.</li><li><strong>AgentSpace,</strong> which is NOT the focus of this blog, on the other hand, is built for the <strong>“action and execution”</strong> phase. An agent built here can take the insights you’ve uncovered in NotebookLM and perform tasks: querying a live database, updating a Jira ticket, or calling an external API.</li></ul><p>The workflow is synergistic under Google Cloud’s powerful AI portfolio: use NotebookLM to formulate a plan based on your documents, then instruct an agent in AgentSpace to carry it out. You think with NotebookLM, and you act with the other.</p><h3>The Experiment: One-Click Report Distillation</h3><p>The process is simple: we uploaded the PDF report into a new notebook. From that moment, NotebookLM’s entire understanding was based exclusively on the facts within that document. We then used its one-click generative features to create a variety of assets.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YcMnv-kJHJlzv5hqPDWVww.png" /><figcaption>The preliminary report PDF used as the sole source to generate insights</figcaption></figure><h4>1. The Video Overview: A Script for Visual Briefings</h4><p>Visual communication is powerful. NotebookLM can instantly generate a blueprint for a short informational video.</p><ul><li><strong>Action:</strong> Select the <strong>“Video Overview”</strong> option.</li><li><strong>Result:</strong> The AI produces a structured full voiceover script alongside corresponding on-screen visuals (e.g., “Timeline graphic”). This provides a ready-to-use storyboard for a production team.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xv38fxfBE_ZRz5x3WM2DzA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6WRyh5eUxpKcaPqID2n_uA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tdx_x5KtNppqWSIF7nZ4DQ.png" /><figcaption>Sample screenshots from the presentation video</figcaption></figure><ul><li><strong>Video Link: </strong><a href="https://drive.google.com/file/d/1zfOIRroTVA9BhXpVl3QjdSAmO3kdv2zW/view?usp=sharing">https://drive.google.com/file/d/1zfOIRroTVA9BhXpVl3QjdSAmO3kdv2zW/view?usp=sharing</a></li></ul><h4>2. The Audio Overview: A Podcast for Stakeholders</h4><p>For executives and stakeholders on the move, a concise audio briefing is invaluable. NotebookLM generates this automatically.</p><ul><li><strong>Action:</strong> Click the <strong>“Audio Overview”</strong> button.</li><li><strong>Result:</strong> NotebookLM produces a factual, podcast-style summary of the report’s key findings. The AI synthesizes the main points into a clear narrative, transforming a lengthy document into a digestible audio file.</li><li><strong>Audio Link: </strong><a href="https://drive.google.com/file/d/1zHqxT0hp5-MAAJf9QrLs8Mnktf14-Rig/view?usp=drive_link">https://drive.google.com/file/d/1zHqxT0hp5-MAAJf9QrLs8Mnktf14-Rig/view?usp=drive_link</a></li></ul><h4>3. The Mind Map: Visualizing Connections</h4><p>Complex reports contain interconnected facts and hierarchies of information that are difficult to see in linear text. A mind map is the perfect tool to visualize these relationships.</p><ul><li><strong>Action:</strong> Use the <strong>“Mind Map”</strong> feature.</li><li><strong>Result:</strong> NotebookLM analyzes the report’s structure and key entities (like flight phases, technical terms, and locations) and automatically generates a visual mind map. This provides an at-a-glance understanding of how different pieces of information relate to one another.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*k54ULUavbye0vo6lKymfug.png" /></figure><ul><li><strong>Full Mind Map Link: </strong><a href="https://drive.google.com/file/d/1vNvi2oGURB_q8OkH3CcqrT4U07AsUvCe/view?usp=sharing">https://drive.google.com/file/d/1vNvi2oGURB_q8OkH3CcqrT4U07AsUvCe/view?usp=sharing</a></li></ul><h4>4. The Report Suite: FAQs, Study Guides, and More</h4><p>For deeper analysis, NotebookLM offers a suite of tools to automatically structure and distill the report’s content.</p><h4><strong>Action 1: Click “FAQ”</strong></h4><ul><li><strong>Result:</strong> The AI anticipates likely questions based on the text and provides direct, factual answers, citing its sources within the document. It correctly identifies what the report does and does not contain.</li></ul><h4><strong>Action 2: Click “Study guide”</strong></h4><ul><li><strong>Result:</strong> NotebookLM produces a comprehensive guide with key terms, summaries of each section, and potential discussion questions, perfect for team onboarding or deep-dive sessions.</li></ul><h4><strong>Action 3: Use the “Timeline” feature.</strong></h4><ul><li><strong>Result:</strong> The tool scans the document for all time-stamped events and organizes them into a clean, chronological list, saving hours of manual work.</li></ul><h4><strong>Action 4: Click “Briefing doc”</strong></h4><ul><li><strong>Result:</strong> A formal, structured summary document is created, complete with an executive summary, key findings, and conclusions, ready for distribution.</li></ul><p><strong>Notebook link: </strong><a href="https://notebooklm.google.com/notebook/865aa3c3-c12d-4703-8647-e83d434ce291">https://notebooklm.google.com/notebook/865aa3c3-c12d-4703-8647-e83d434ce291</a></p><h3>AI as a Tool for Comprehension, Not Conclusion</h3><p>This experiment demonstrates that modern Generative AI tools are moving beyond simple Q&amp;A. With intuitive, one-click features, NotebookLM can act as a powerful analytical partner, transforming a single, complex document into a full suite of multimedia assets. This capability along with RAG allows technical teams to understand, process, and communicate critical information with unprecedented speed and clarity.</p><p>However, the role of the human expert remains paramount. The AI makes the data comprehensible; the expert provides the critical thinking, verification, and final judgment. By handling the heavy lifting of data distillation, these tools empower us to focus on what truly matters: the insights that drive better decisions.</p><h3>References</h3><ul><li><a href="https://drive.google.com/file/d/1zfOIRroTVA9BhXpVl3QjdSAmO3kdv2zW/view?usp=sharing">Generated Presentation Video Link</a></li><li><a href="https://drive.google.com/file/d/1zHqxT0hp5-MAAJf9QrLs8Mnktf14-Rig/view?usp=drive_link">Generated Audio Link</a></li><li><a href="https://cloud.google.com/resources/notebooklm-enterprise?e=48754805">NotebookLM for Enterprise</a></li><li><a href="https://x.com/NotebookLM/status/1950250899269472760">29th July, 2025 Release</a></li><li><a href="https://blog.google/technology/google-labs/notebooklm-video-overviews-studio-upgrades/">NotebookLM Blog Post</a></li></ul><p><strong>Let’s keep the conversation going! Share your thoughts, questions, and ideas in the comments.</strong></p><p><strong>Note:</strong> <em>Should you have any concerns or queries about this post or my implementation, please feel free to connect with me on </em><a href="https://www.linkedin.com/in/aniket-agrawal-a18990266/"><em>LinkedIn</em></a><em>! Thanks!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d492ab6e9e4c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/google-cloud/notebooklm-one-click-accident-report-comprehension-d492ab6e9e4c">NotebookLM: One-Click Accident Report Comprehension</a> was originally published in <a href="https://medium.com/google-cloud">Google Cloud - Community</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>