Building an adaptive AI gateway with Apigee for stateful multi-agent workloads

TL;DR: Single-turn prompt routing cuts LLM serving costs by over 70% for stateless Q&A, but multi-agent systems introduce new stateful challenges. Once your agents run multi-turn loops, you face compounding context bloat, repetitive tool-retry loops, and cross-agent state bleed. This article shows how you can evolve Apigee from a stateless prompt router into a model-agnostic, stateful multi-agent control plane for Google Agent Development Kit (ADK) and Gemini Enterprise Agent Platform workloads. By governing tier selection, isolating worker sessions, healing tool loops, compacting traces, and pre-warming Turn-0 caches, you can achieve 40%–80% net FinOps savings and zero unhandled rate-limit crashes in our reference multi-agent benchmark*.


1. From single-turn prompt routing to a stateful agent control plane

In Dynamic Model Routing with Apigee X, we solved the cost-performance trade-off for stateless prompts by pairing Apigee with a DeBERTa-v3 classifier on Cloud Run. Scoring incoming queries across six complexity dimensions let the gateway route simple questions to lightweight models while reserving frontier models for complex reasoning. That stateless pattern works well when every request stands alone, but production AI is now shifting toward autonomous multi-agent systems built with the Google Agent Development Kit (ADK) on the Agent Platform. In these workflows, a single user request kicks off a stateful, multi-turn agent loop. A Lead Orchestrator agent breaks down the goal, delegates sub-tasks to parallel child workers, calls internal APIs, and synthesizes a structured response.

The 75% routine execution vs. 25% deep reasoning workload split

Production telemetry across multi-agent deployments on the Agent Platform reveals a consistent workload split. Understanding this distribution explains why static model assignments break down when your agents run multi-turn loops:

  • Routine tool execution (~75% of turns): Fetching database records, validating schemas, and extracting parameters. These mechanical turns run fastest and most cost-effectively on Gemini Flash Models (such as Gemini Flash-Lite and Gemini Flash).
  • Deep reasoning and synthesis (~25% of turns): Decomposing ambiguous goals, recovering from unexpected tool errors, and reconciling multi-worker outputs. These high-stakes planning and synthesis turns require a Gemini Frontier Model.
  • The over-provisioning trap (100% Gemini Frontier Model): Paying a 10x–30x token premium on routine tool calls while raw API JSON responses pile up across turns, pushing Time-to-First-Token (TTFT) to 4–8 seconds.
  • The under-provisioning trap (100% Gemini Flash-Lite): Suffering planning drift during goal decomposition, hallucinations during final synthesis, and endless retry loops when a downstream database returns a lock error.

A stateless prompt classifier cannot govern this lifecycle because every turn in an agent loop carries the growing conversation history of all previous turns. As tool outputs accumulate, a stateless classifier misreads the bloated payload as a complex query and routes routine lookups to your most expensive model tier. Governing multi-agent systems requires a model-agnostic, stateful agent control plane that tracks session hierarchies, turn phases, token budgets, and tool call patterns in flight.


2. Five core pillars of an adaptive AI gateway

Building routing, retry logic, and history pruning inside each agent’s application code quickly gets brittle at scale. Container restarts wipe in-memory step counters, adopting a new model family forces you to redeploy dozens of microservices, and independent worker pods cannot coordinate shared departmental token quotas. Moving these responsibilities into Apigee centralizes governance behind a single proxy endpoint (/v1/agentic-router). Your agent containers simply speak the standard Agent Platform API contract while the gateway enforces five core architectural pillars:

Core pillar Enterprise challenge How Apigee governs it in-flight Production impact*
1. Model-agnostic zigzagging & FinOps Paying frontier rates on routine tool calls or risking departmental budget overruns. Switches between Gemini Frontier Model on planning and synthesis turns and Gemini Flash Models on tool turns via API Product attributes. 90% lower spend on tool turns; zero budget overruns.
2. Parallel delegation & namespace isolation Concurrent worker fan-out overwrites shared session state and bleeds context across sibling tasks. Partitions distributed cache keys by both parent session ID and child worker name for isolated parallel state. Zero sibling context bleed across concurrent child workflows.
3. Resource guarding & self-healing Lightweight models repeat failing tool calls until the session crashes. Enforces rolling token quotas, boosts looping turns to a stronger model, removes failing tools, and triggers a soft summary at step limits. Zero unhandled HTTP 429 crashes; automatic loop recovery.
4. Trace compaction & sequential rollup Verbose tool logs bloat prompts and trigger a KV cache miss on synthesis. Compacts oversized payloads in-flight and merges child worker findings into <execution_memory> before synthesis while preserving JSON schemas. 35%–85% smaller synthesis prompts (90%–97% on heavy logs); 340ms TTFT.
5. Turn-0 prompt caching & live telemetry Re-sending static policy manuals on every session wastes tokens and latency. Pre-warms Agent Platform context caches for static manuals on Turn 0 while attaching audit headers to every response. 100% Turn-0 cache hit rate (up to 90%–95% cached token discount) and full FinOps visibility.


3. How the control plane governs multi-agent turns in-flight

To see how these five pillars work together, let’s trace one continuous scenario in chronological order from Turn 0 through final synthesis: Airline Disruption Recovery (session disruption-902). When a severe storm grounds a flight, a Lead Orchestrator agent (built with ADK) breaks down the recovery plan and spawns five parallel child workers. Those five specialists handle seat rebooking (seat-worker), baggage recovery (baggage-worker), hotel vouchers (hotel-worker), ground transport (transport-worker), and loyalty compensation (loyalty-worker). The sequence diagram below maps the entire multi-agent workflow across Apigee and the Agent Platform:

3.1 Turn 0 and planning: Pre-warming static context and configuring model tiers

Before any passenger disruption session starts, your airline agents share a static 25,000-token operational handbook covering DOT compensation rules and rebooking policies. Re-sending that static manual on the first turn of every conversation wastes both latency and token budget. Apigee exposes an administrative /prewarm endpoint that registers only the static 25,000-token operational handbook in Agent Platform cachedContent ahead of time. This delivers a 100% Turn-0 cache hit rate with up to a 90%–95% cached token discount, while keeping tools declarations dynamic outside cachedContent so Apigee can modify individual tools mid-flight.

Alongside Turn-0 context pre-warming, you configure model-agnostic tier mappings, step ceilings, token budgets, and escalation locks as declarative attributes on Apigee API Products:

{
  "name": "Airline-Disruption-Support-Tier",
  "attributes": [
    { "name": "model_planning", "value": "gemini-frontier-model" },
    { "name": "model_execution", "value": "gemini-flash-lite" },
    { "name": "model_synthesis", "value": "gemini-frontier-model" },
    { "name": "escalation_enabled", "value": "true" },
    { "name": "max_child_steps", "value": "5" },
    { "name": "token_quota_limit", "value": "1000000" }
  ]
}

When the Lead Orchestrator agent sends its initial planning request for session disruption-902, Apigee verifies your API key, binds the pre-warmed cachedContent pointer, and routes the turn to the Gemini Frontier Model. Setting "escalation_enabled": "true" on Airline-Disruption-Support-Tier lets live passenger recovery sessions automatically boost stuck child workers to a stronger model mid-flight. For non-critical back-office tiers, you can set "escalation_enabled": "false" to enforce a strict budget lock.

3.2 Parallel execution: Isolating child worker sessions on Gemini Flash-Lite

Once the Lead Orchestrator agent finishes its planning turn for disruption-902, it spawns all five child workers (seat-worker, baggage-worker, hotel-worker, transport-worker, and loyalty-worker) concurrently to run domain API calls. Without gateway coordination, five parallel multi-turn loops sharing a parent session ID would overwrite one another’s step counters and scratchpad histories in cache. Apigee governs this parallel fan-out using a lightweight HTTP header contract sent by each worker on every turn:

POST /v1/agentic-router HTTP/1.1
Host: api.enterprise.example.com
x-apikey: <airline-support-api-key>
x-session-id: disruption-902/seat-worker
x-agent-phase: execution

Apigee parses the composite x-session-id header (disruption-902/seat-worker) and partitions its distributed cache keys by both the parent session ID (disruption-902) and the child worker name (seat-worker). This gives each of your five airline specialists a strictly isolated namespace for step counters, working scratchpads, and final findings. At the same time, the gateway routes all routine execution turns to Gemini Flash-Lite at a 90% lower per-token cost.

3.3 Mid-flight self-healing: Recovering from tool loops and enforcing step ceilings

While baggage-worker, hotel-worker, transport-worker, and loyalty-worker finish their routine API calls on Gemini Flash-Lite, suppose disruption-902/seat-worker hits a database lock on seat 12B. Instead of letting a repetitive retry loop crash the recovery session, Apigee guides the worker loop through a turn-by-turn escalation ladder:

  • Turns 1–2 (Lock detected on Gemini Flash-Lite): seat-worker calls lookup_seat for seat 12B twice in a row with identical arguments and hits a downstream database lock on both turns.
  • Turn 3 (Cognitive loop boost + Surgical tool redaction): Apigee detects the two identical lookup_seat calls and upgrades Turn 3 from Gemini Flash-Lite to Gemini Flash with a system hint to vary its approach. Because tools were kept outside cachedContent, Apigee also removes lookup_seat from the outbound tools list so seat-worker calls issue_seat_override and succeeds on Turn 3.
  • Outer safety net (Graceful soft landing at Turn 5 & Rolling token budgets): What if a worker reaches max_child_steps: 5 (or 8 turns for a standalone agent), or nears token_quota_limit? Apigee strips all remaining tool declarations to force a clean partial summary before any hard HTTP 429 fault can occur.

As each of the five child workers finishes its final turn, Apigee automatically caches its verified outcome under the parent disruption-902 session key. Your Lead Orchestrator agent can then synthesize the recovery plan without re-processing raw tool logs.

3.4 Final synthesis: Compacting worker traces and emitting telemetry

Different model tiers have incompatible internal neural dimensions, so the Gemini Frontier Model cannot reuse the Key-Value (KV) attention cache built by Gemini Flash Models during tool execution. Forwarding raw multi-worker tool history into the final synthesis turn would force the Agent Platform to re-process every intermediate JSON log from scratch at frontier pricing. Apigee eliminates this cross-model switch penalty across two distinct stages:

  • During tool execution (preserving the Gemini Flash Model prefix cache): Under 180 KB (a configurable threshold sized to stay comfortably within Apigee distributed cache entry limits), Apigee keeps message history append-only. Consecutive Gemini Flash-Lite turns achieve a 100% implicit prefix cache hit rate while Apigee saves each turn’s result in gateway memory. Only when verbose diagnostic logs push a payload past 180 KB does Apigee compact the middle turns into a concise scratchpad summary, cutting payload size by 90%–97%.
  • Entering final synthesis (avoiding the cross-model KV cache miss): When the Lead Orchestrator agent sends its final synthesis request for disruption-902, Apigee pulls the cached findings from all five airline workers. It replaces their raw tool JSON and tool declarations with a single <execution_memory> rollup block while preserving your target JSON output schema:
<execution_memory session="disruption-902">
  [seat-worker]: Priority override confirmed (Seat 14A). [baggage-worker]: Tag #8821 rerouted to ORD.
  [hotel-worker]: Voucher #HV-409 issued. [transport-worker]: Shuttle booked. [loyalty-worker]: +15,000 miles credited.
</execution_memory>

Replacing 55,000 tokens of raw worker tool logs with this compact rollup shrinks the synthesis prompt by 35%–85% and cuts synthesis TTFT on the Gemini Frontier Model from 6.8 seconds to 340 milliseconds. On the return path, Apigee attaches phase-specific audit headers to every HTTP response so your agent callbacks and Cloud Monitoring dashboards can verify every intervention:

  • After seat-worker Turn 3 (Self-healing execution):

    x-apigee-agent-phase: execution
    x-apigee-routed-model: gemini-flash
    x-apigee-step-count: 3
    x-apigee-surgical-tool-redacted: lookup_seat
    
  • After Lead Orchestrator agent Final Turn (Compacted synthesis):

    x-apigee-agent-phase: synthesis
    x-apigee-routed-model: gemini-frontier-model
    x-apigee-compaction-applied: true
    x-apigee-compaction-tokens-saved: 46250
    

4. Live benchmark verification and FinOps impact*

To quantify the production impact of stateful gateway governance, we benchmarked the five-worker airline disruption recovery workflow (disruption-902) against live Agent Platform endpoints. Each run includes 1 planning turn, 5 parallel child worker loops with an injected seat-lock fault, and 1 JSON synthesis turn. We compared two setups: a static 100% Gemini Frontier Model baseline versus the Apigee adaptive AI gateway:

Benchmark metric 1. Static 100% Gemini Frontier Model 2. Apigee adaptive AI gateway
Model routing behavior Runs all turns on Gemini Frontier Model. Zigzags cleanly: Gemini Frontier Model on planning and synthesis turns; Gemini Flash Models on 75% tool turns.
Static schema caching Re-computes 25K static handbook tokens on Turn 0. Binds pre-warmed cache pointers for a 100% Turn-0 hit rate (up to 90%–95% cached token discount).
Response to locked tool Retries lookup_seat at frontier pricing. Boosts looping turn to Gemini Flash, removes lookup_seat, and uses override fallback.
Billed tokens / session ~310,000 tokens (baseline) ~68,000 tokens (78% reduction)
Final synthesis TTFT ~6.8 seconds ~340 milliseconds (20x faster)
Unhandled crash rate 14% (quota exhaustion) 0% unhandled HTTP 429 crashes
Average cost / session $0.78 / session $0.17 / session (78% net savings)

Across both live passenger recovery and back-office airline workloads, shifting stateful guardrails to Apigee cuts net serving costs by 40%–80% and speeds up P90 tool execution by 2x–5x (under 1.5 seconds per turn). Your agents also retain over 90% cache hit rates across multi-turn sessions, while response headers give your FinOps and platform teams complete per-session cost attribution without modifying agent code.


5. Conclusion and getting started

As enterprise AI evolves from single-turn chatbots into autonomous multi-agent systems, your API gateway can no longer treat LLM calls as stateless requests. By evolving Apigee into a model-agnostic, stateful multi-agent control plane for the Agent Platform, you decouple agent code from model tiering, context compaction, loop recovery, and FinOps enforcement. That gives you up to 80% lower serving costs and resilient multi-agent execution through one governance layer.

What’s next (Part 3 sample release): Building stateful multi-agent policies from scratch requires coordinating several Apigee policies and distributed cache partitions. In an upcoming Part 3 fast-follow article, we will release the complete deployable agentic-router Apigee proxy bundle, API Product templates, and 5-worker ADK test harness. If you would like early access to the reference implementation for a pilot, reach out to your Google Cloud account team.

How is your team governing model routing, tool retry loops, and context growth across multi-agent workloads? Share your architecture or questions in the comments below!

*Benchmark methodology and disclaimer: All token, latency (TTFT), and cost reduction numbers come from internal benchmark testing of the 5-worker ADK airline disruption recovery scenario (1 planning turn, 5 parallel child worker loops with an injected tool lock, a 25K-token static handbook, and 1 synthesis turn). Actual production results will vary based on prompt size, model selection, and agent topology.


:thought_balloon: Plan your next step with a Google Cloud Sales Specialist

5 Likes