Book TOC · Previous · Chapter 3 of 8 · Next
Chapter 3: Custom Agentic Workflows in Code: Models, ADK, Sessions & Memory Bank
Official Exam Guide Subsections Consolidated: 3.1
Chapter Consolidation Telemetry: Synthesizes 43 architectural scenarios across 1 Exam Subsections and 4 Official Considerations into consolidated takeaway pillars, paired with 1 Reference Architecture Mermaid Diagrams and 10 Curated Visual Illustrations.
Chapter Focus: Gemini Flash vs. Pro routing, ADK Sequential/Parallel/Loop/Coordinator patterns, Session state vs. Memory Bank, and context window compaction.
Subsection 3.1: Designing and Building Custom Agentic Workflows in Code: Models, ADK, Sessions, Memory Bank, and CLI Skills
Part III: Developing Custom Agents (~33% of Exam) · 4 Official Considerations · 43 Scenarios Consolidated
Domain Overview and Reference Architecture
Engineering Code-First Agents: Model Economics, Stateless Checkpointing & Dual-Tier Memory
Welcome to Part III: Developing Custom Agents, which carries the single largest weight on the Professional Agentic Architect exam (~33%). In Subsection 3.1, you transition from using low-code builders and coding assistants to writing custom production agentic systems in code using the Google Agent Development Kit (ADK) and open-source frameworks.
Four architectural pillars define this chapter:
- Model Selection & Routing Economics (
3.1a): A production multi-agent system rarely uses a single model for every node. Using a frontier Large Language Model (LLM) likeGemini Proto classify simple intents at 10,000 QPS wastes budget and violates sub-second latency SLAs. Conversely, using a Small Language Model (SLM) to synthesize a 500-page legal discovery corpus fails on reasoning depth and context length. You must know when to pair SLM routers (Gemini Flash-Lite/Gemma) with LLM planners (Gemini Pro), and when strict regulatory data-residency or air-gapped sovereignty requires self-hosting open-weight models (Gemma,Llama) on GKE from Model Garden versus consuming SaaS Vertex AI endpoints (with Provisioned Throughput for predictable high-volume cost). - Building Stateful Agents on Stateless Compute (
3.1b): When you deploy a custom ADK or LangGraph agent on Cloud Run, containers scale horizontally and terminate at will. Storing conversation history in local Python memory (dict) guarantees data loss. You must architect externalized checkpointers backed by Cloud Firestore or Memorystore for Redis, and pass large binary blobs via Cloud Storage URIs. - Dual-Tier Memory Architecture (
3.1c): Architects must strictly separate Short-Term Session State (Managed Sessions, sliding windows, running summaries, strict TTLs) from Long-Term Cross-Session Memory (Agent Platform Memory Bank, which asynchronously distills durable user facts and preferences across sessions with strict multi-tenant namespace isolation). - Operating Skills via Agents CLI (
3.1d): Governing whenAgents CLIruns skills autonomously in Agent Mode (CI/CD pipelines) versus requiring interactive confirmation in Human Mode (high-risk production mutations).
Core Foundational Primitives & Mental Models (Subsection 3.1)

Core Concept / Service | Winning Architectural Rule & Default Behavior | Common Exam Trap to Avoid |
|---|---|---|
Agent Development Kit (Services: vertex_ai, vertex_ai:agent_builder) | The Agent Development Kit is the dedicated open-source framework provided for programmatic agent creation. | Kubeflow Pipelines orchestrates ML training pipelines rather than custom AI conversational/action agents. |
Small language model (Services: vertex_ai, vertex_ai:model_garden, vertex_ai:gemma) | Small language models have fewer parameters, which drastically reduces computational overhead, per-token cost, and inference latency for specialized workloads. | Diffusion models generate images through iterative computational steps, which introduces substantial latency and does not address text-based specialized tasks. |
Software as a service (Services: vertex_ai, vertex_ai:model_garden, vertex_ai:gemini_api) | Software as a service exposes model endpoints through managed APIs without requiring developers to provision or manage underlying infrastructure. | Self-hosting on GKE requires managing Kubernetes clusters, node pools, container workloads, and hardware drivers. |
Agent Platform Memory Bank (Services: vertex_ai:agent_builder, vertex_ai:agents) | Agent Platform Memory Bank provides long-term context storage of past conversation history and preferences for custom agents. | BigQuery BI Engine accelerates analytical SQL queries, not conversational agent memory. |
Managed sessions (Services: vertex_ai:agent_builder, dialogflow_cx) | Managed sessions automatically store and track state and conversation history across multiple turns in conversational agents. | Static JSON files are static configuration resources and do not dynamically track conversational session state. |
Agent mode (Services: vertex_ai:agents, vertex_ai:agent_builder) | Agent mode runs tasks autonomously end-to-end without pausing for user confirmation before executing tool calls. | Supervised mode pauses for approval during critical actions rather than running fully autonomously. |
Human mode (Services: vertex_ai:agents, vertex_ai:reasoning_engine) | Human mode pauses tool execution and requires explicit human approval before running sensitive or destructive actions. | Autonomous mode allows the agent to execute actions continuously without human confirmation. |
Model Garden (Services: vertex_ai:model_garden, vertex_ai) | Model Garden is the Vertex AI hub designed specifically for discovering, testing, and deploying both first-party proprietary and open-source foundation models. | Cloud Spanner is a relational database service, not a model repository or deployment platform. |
Skill Registry (Services: vertex_ai:agents, vertex_ai:reasoning_engine) | A Skill Registry serves as the central directory of enterprise tools and functions that custom agents can discover and execute. | Cloud DNS manages domain name resolution, not tool registries for agent execution. |
Memorystore for Redis (Services: memorystore:redis, memorystore) | Memorystore for Redis is a fully managed in-memory caching service optimized for sub-millisecond read and write latency. | Cloud Storage Coldline is a high-latency, cold-tier object storage class meant for long-term disaster recovery and archiving. |
Firestore (Services: firestore, vertex_ai:agents) | Firestore is Google Cloud's fully managed, serverless NoSQL document database ideal for storing conversational session states and agent histories. | Cloud Spanner is a distributed relational SQL database, not a serverless NoSQL document database. |
Agent Development Kit (Services: vertex_ai:agents, vertex_ai:genai) | The Agent Development Kit (ADK) provides open-source core abstractions specifically built for defining and orchestrating custom agent multi-step loops. | TensorFlow Lite targets on-device machine learning inference, not multi-step generative AI agent workflows. |
LLM versus SLM selection (Services: vertex_ai:generative_ai, vertex_ai:model_garden) | Choosing between LLMs and SLMs directly balances parameter footprint, latency, and computational expense. | Hard drive spindle speed is a legacy physical storage metric unrelated to model selection. |
Official Exam Considerations & Consolidated Takeaways (Subsection 3.1)
Consideration 3.1a: Selecting and configuring the appropriate language model (e.g., large language model [llm] vs. small language model [slm], self-hosted vs. software as a service [saas], and open-source software [oss] vs. proprietary llm) considering cost, security, and agent architecture
When evaluating model selection scenarios across LLM vs. SLM, SaaS vs. Self-Hosted, and Proprietary vs. Open-Source (OSS):
- Tiered SLM → LLM Routing: Use a lightweight SLM (
Gemini Flash-Lite,Gemini Flash, or a fine-tunedGemmamodel) for high-frequency, low-latency tasks like intent routing, PII classification, or simple JSON extraction, and route only complex multi-step reasoning or synthesis tasks to a frontier LLM (Gemini Pro). - SaaS Managed APIs vs. Self-Hosted OSS on GKE: Default to Vertex AI SaaS endpoints (
Gemini LLMs) for zero infrastructure management, native 1M–2M token context windows, and built-in Context Caching. Choose Self-Hosted Open-Weight Models (Gemma,Llama,Mistralfrom Model Garden) on GKE with GPUs/TPUs only when the scenario mandates air-gapped/disconnected operation, full weight-level control, or strict regulatory rules forbidding external multi-tenant SaaS APIs. - Pay-As-You-Go vs. Provisioned Throughput: For steady, high-volume enterprise production pipelines requiring guaranteed QPS and predictable monthly cost, purchase Vertex AI Provisioned Throughput rather than relying solely on dynamic pay-as-you-go tokens.


Takeaway 1: Latency and Cost Optimization with SLM Routers (vertex_ai:gemini · vertex_ai:model_garden)
- Core Concept: Hierarchical Model Selection (SLM vs. LLM)
- Scenario Trigger & Requirement: A high-volume platform experiencing high token costs and latency during the triage stage of an agentic workflow. The key requirements are reducing operational cost and response latency while maintaining deep reasoning capability for technical troubleshooting tasks.
- Winning Architecture & Implementation: Deploy a lightweight small language model (SLM) for intent classification and routing, and invoke a frontier large language model (LLM) only for complex multi-step reasoning. Using a hierarchical model architecture is a recommended design pattern for agentic workflows. Small language models (SLMs) or lightweight models (such as Gemini Flash or Gemma) feature significantly lower latency and lower token inference costs, making them ideal for high-volume, structured tasks like query triage, intent detection, and routing.
- Exam Traps to Reject: Sending all initial traffic through a large frontier model is costly and introduces unnecessary inference latency. SLMs alone often lack the reasoning capability required to solve complex technical troubleshooting tasks.
Takeaway 2: Data Sovereignty and Isolation in Regulated Banking (vertex_ai:endpoints · vertex_ai:model_garden · vpc:private_service_connect)
- Core Concept: Self-Hosted Open-Source Models vs. Multi-Tenant SaaS
- Scenario Trigger & Requirement: Two strict compliance constraints: customer PII must never leave the bank's VPC network, and model inference must run on dedicated, non-shared infrastructure without external SaaS API dependencies. You need an architecture that combines self-hosted open-source models with private networking.
- Winning Architecture & Implementation: Deploy an open-source model to a dedicated Vertex AI private endpoint connected to your VPC network. Deploying an open-source foundation model (such as Gemma or Llama) onto dedicated compute infrastructure with Vertex AI private endpoints ensures that inference traffic stays entirely within your Virtual Private Cloud (VPC) network.
- Exam Traps to Reject: Default Gemini endpoints run on shared multi-tenant SaaS infrastructure rather than isolated dedicated instances. Cloud NAT still sends customer PII outside the VPC network to external SaaS providers.
Takeaway 3: Predictable Cost Modeling for Continuous High-Throughput Pipelines (gke · compute_engine:gpus · vertex_ai:model_garden)
- Core Concept: Fixed-Cost Self-Hosted Infrastructure vs. Pay-Per-Token SaaS
- Scenario Trigger & Requirement: A scenario with two key technical constraints: continuous high-throughput traffic (500 requests per second 24/7) and a business requirement for a flat, predictable monthly budget without token-based cost variability. You must choose between pay-per-token managed SaaS APIs and self-hosted infrastructure with reserved capacity.
- Winning Architecture & Implementation: Deploy an open-source language model on Google Kubernetes Engine (GKE) with dedicated GPUs and purchase Committed Use Discounts (CUDs). Hosting an open-source language model on dedicated infrastructure, such as Google Kubernetes Engine (GKE) backed by GPUs, establishes a predictable infrastructure cost baseline.
- Exam Traps to Reject: Scaling to zero is designed for sporadic traffic, not for continuous 24/7 baseline loads. Pay-per-token APIs generate variable consumption charges that do not satisfy flat budget constraints at high throughput.
Takeaway 4: Massive Context Analysis for Legal Discovery Agent (vertex_ai:gemini · vertex_ai:model_garden)
- Core Concept: Proprietary Frontier LLM with Ultra-Large Context Windows
- Scenario Trigger & Requirement: The scenario requires an automated agent to process over 800,000 tokens of legal text in a single execution step while avoiding complex document chunking or RAG pipelines. Key considerations include model context capacity, operational overhead (fully managed vs. self-hosted), and retrieval accuracy over massive document lengths.
- Winning Architecture & Implementation: Select a fully managed frontier model with an ultra-large context window, such as Gemini 1.5 Pro on Vertex AI. Gemini 1.5 Pro provides a native context window of up to two million tokens. This capability allows an agent to ingest large document sets directly into the prompt context without requiring vector chunking heuristics or complex Retrieval-Augmented Generation (RAG) pipelines.
- Exam Traps to Reject: Truncating data to 32,000 tokens discards most of the 800,000 tokens of legal documents. Self-hosting large models introduces high operational overhead, and sliding-window attention fails to preserve long-range cross-document references.
Consolidated Golden Rules (Consideration 3.1a):
- Hierarchical model design routes high-frequency classification tasks to lightweight SLMs to reduce cost and latency.
- Frontier LLMs should be reserved for complex reasoning, planning, and specialized domain troubleshooting.
- Avoid using large, expensive models for tasks that require only simple intent triage.
- Choose self-hosted open-source models deployed to private endpoints when strict regulatory mandates require full compute isolation and internal network boundaries.
- Multi-tenant SaaS model endpoints route requests through managed shared cloud infrastructure.
- Private endpoints ensure traffic between your agent workloads and language models stays within your private VPC network.
Consideration 3.1b: Building custom agents using open-source libraries (e.g., agent development kit [adk])
When architecting code-first agents with the Google Agent Development Kit (ADK) or LangGraph:
- External Checkpointing on Stateless Compute: Serverless containers on Cloud Run do not share memory, and session affinity is best-effort. Always configure an external Checkpointer / Session Service backed by Cloud Firestore or Memorystore for Redis (or deploy directly to Agent Runtime [Agent Engine], which provides built-in managed session persistence).
- Handling Mid-Turn Crashes & Human-in-the-Loop Interrupts: Checkpointing after every graph node allows an agent to pause before a high-risk tool call, wait hours or days for human approval, and resume execution from the exact saved state snapshot on any container instance without re-running completed upstream tools.
- Claim-Check Pattern for Large Artifacts: Never serialize a 50MB PDF or dataset directly into the ADK/LangGraph state object (causes database write bottlenecks and context window explosion). Write the file to Cloud Storage and pass only the lightweight
gs://bucket/objectURI inside the shared state dictionary!


Takeaway 1: Distributed State Persistence in Multi-Turn Agent Workflows (cloud_run · firestore · memorystore)
- Core Concept: Session and checkpoint persistence with open-source agent frameworks
- Scenario Trigger & Requirement: Deploying an open-source agent framework on Cloud Run, which is a stateless, autoscaling compute service. The key challenge is preserving agent checkpoint state across multi-turn interactions where subsequent requests may arrive at different container instances. The solution must provide low-latency reads and writes and avoid data loss.
- Winning Architecture & Implementation: Configure an external checkpointer backed by Cloud Firestore or Cloud Memorystore to persist conversational checkpoints across turns. Serverless compute platforms such as Cloud Run are inherently stateless and scale up or down dynamically. When building custom multi-turn agents with open-source frameworks (such as LangGraph or Google Agent Development Kit), each turn requires loading the conversation history and intermediate tool-execution state.
- Exam Traps to Reject: Session affinity does not guarantee state persistence because container instances can scale down or restart at any time. Batching state exports at the end of a session causes state loss during intermediate conversational turns.
Takeaway 2: Dynamic OpenAPI Tool Ingestion with Vertex AI Extension Compatibility (vertex_ai:gemini · vertex_ai:tool_calling)
- Core Concept: Tool declaration and dynamic schema translation
- Scenario Trigger & Requirement: The scenario requires dynamically integrating internal REST microservices defined by OpenAPI 3.0 specifications into a custom agent on Vertex AI. The key requirements are dynamically translating endpoints into model-compatible tool declarations and enforcing strict runtime parameter validation to avoid invalid backend API requests.
- Winning Architecture & Implementation: Parse the OpenAPI specifications into FunctionDeclaration objects with JSON Schema parameters, and validate the model arguments against the schema with a runtime validator before executing backend API requests. Converting OpenAPI 3.0 specifications into native
FunctionDeclarationobjects provides Gemini with structured JSON Schema definitions of endpoints and parameters. - Exam Traps to Reject: Setting temperature to zero does not provide formal schema enforcement or parameter validation. Text prompts and regular expressions lack structural schema enforcement and bypass native tool calling.
Takeaway 3: Hierarchical Multi-Agent Supervisor Pattern Deployment (vertex_ai:agent_builder · vertex_ai:reasoning_engine)
- Core Concept: Multi-agent orchestration and role decomposition
- Scenario Trigger & Requirement: Two main technical requirements: coordinating specialized worker agents and preventing both circular delegation loops and token bloat. The solution must provide structured routing and state control across agent boundaries.
- Winning Architecture & Implementation: Implement a centralized supervisor agent pattern where worker agents return results directly to the orchestrator instead of communicating with each other. A centralized supervisor (or hierarchical orchestrator) pattern assigns a top-level agent to direct the workflow. The supervisor invokes individual specialized worker agents, collects their outputs, and decides the next step.
- Exam Traps to Reject: Peer-to-peer communication increases token overhead and creates circular handoff loops. Unstructured shared history inflates prompt context size and lacks deterministic termination control.
Takeaway 4: Human-in-the-Loop Interrupt and Resume Patterns (cloud_run · cloud_sql · pubsub)
- Core Concept: Agent interruption and workflow state suspension
- Scenario Trigger & Requirement: The scenario requires an asynchronous human-in-the-loop pattern where an open-source AI agent pauses before executing a high-value transaction, persists state, and resumes from that specific point upon human approval.
- Winning Architecture & Implementation: Configure an interrupt breakpoint before the transaction node to serialize graph state to Cloud SQL by thread ID, send a notification, and resume the graph using the thread ID upon approval. When building human-in-the-loop (HITL) workflows with open-source agent frameworks (such as LangGraph or custom Agent Development Kits), best practice involves setting an interrupt or breakpoint before sensitive actions.
- Exam Traps to Reject: Restarting the agent from the start re-runs past steps and client-side storage is insecure. Continuous polling in a busy loop wastes compute resources and exceeds Cloud Run request timeout limits.
Consolidated Golden Rules (Consideration 3.1b):
- Cloud Run instances are stateless and ephemeral; conversational agent state must never be stored exclusively in container memory.
- Open-source agent frameworks require checkpointer backends to maintain thread state and step execution history across turns.
- Use low-latency, highly available datastores such as Cloud Firestore or Cloud Memorystore for externalized agent state persistence.
- Translate OpenAPI specifications into model-native FunctionDeclaration schemas to support dynamic tool calling.
- Always perform runtime parameter validation before dispatching model-generated tool calls to backend microservices.
- Avoid relying on prompt-based text parsing or low temperature alone for structured API interactions.
Consideration 3.1c: Configuring sessions and memory (e.g., agent platform memory bank and managed sessions)
Distinguish clearly between Session State (Short-Term) and Memory Bank (Long-Term):
- Managed Sessions (Short-Term Conversational State): Tracks the active multi-turn dialogue thread, current tool-call trajectory, and temporary scratchpad variables (
session.state). To prevent 200-turn conversations from exceeding token budgets, implement Conversation Summarization + Sliding Window retention. - Agent Platform Memory Bank (Long-Term Semantic/Episodic Memory): Persists distilled user facts, preferences, and historical summaries across separate sessions (e.g., remembering a customer's preferred seat class or dietary restriction three months later). Use asynchronous state extraction callbacks at the end of a session to distill facts into Memory Bank without adding latency to live user turns.
- Privacy, TTL & Multi-Tenant Isolation: Enforce automated Time-to-Live (TTL) policies on Firestore/Session stores to purge raw logs per GDPR/compliance rules, and strictly scope all Memory Bank queries by authenticated
user_idandtenant_idnamespaces to prevent cross-tenant memory bleed.


Takeaway 1: Short-Term Conversation History vs. Persistent Long-Term Memory (vertex_ai:agent_builder · vertex_ai:agents)
- Core Concept: Distinguishing Managed Session State from Agent Memory Bank
- Scenario Trigger & Requirement: Two distinct memory requirements: 1) Isolate short-term, turn-level states (payment steps) to the active session. 2) Persist specific entities and user facts (vehicle details) across multiple conversations months apart without overloading prompt tokens.
- Winning Architecture & Implementation: Store current interaction variables in a managed session, and configure an Agent Platform Memory Bank to extract and persist user-level facts across sessions. Using managed sessions for short-term state and an Agent Platform Memory Bank for long-term facts is the recommended architectural pattern.
- Exam Traps to Reject: Memory Bank is for persistent facts rather than temporary workflow states like payment steps. Managed sessions are short-lived and should not be used as persistent storage across months.
Takeaway 2: Strict Session TTL and Privacy Compliance (vertex_ai:agent_builder · vertex_ai:sessions)
- Core Concept: Configuring Session Expiration and Time-To-Live (TTL) Policies
- Scenario Trigger & Requirement: The scenario requires automatically purging active conversational states, variables, and transcripts after exactly 15 minutes of inactivity for privacy and compliance. The core requirement emphasizes reliable server-side enforcement rather than client-dependent state clearing.
- Winning Architecture & Implementation: Set the session time-to-live (TTL) parameter to 900 seconds in the managed session configuration in your code. Vertex AI Agent Builder managed sessions support specifying a time-to-live (TTL) policy directly on the session resource.
- Exam Traps to Reject: Scheduled Cloud Functions add custom maintenance overhead when built-in session TTL settings are already available. Client-side timers fail if the user closes the browser or loses network connection before the timer finishes.
Takeaway 3: Automatic Fact Distillation for User Profiles (vertex_ai:agent_builder · vertex_ai:agents · vertex_ai:memory_bank)
- Core Concept: Automated Memory Bank Ingestion and Extraction
- Scenario Trigger & Requirement: Requires a way to automatically and incrementally extract user facts (sizes, preferences, aversions) from conversational dialogue across sessions. The key constraints are avoiding explicit forms/interruptions and maintaining long-term cross-session memory natively.
- Winning Architecture & Implementation: Enable automated memory extraction on the Memory Bank configuration to continuously synthesize user assertions into long-term memory. Enabling automated memory extraction on the Memory Bank allows the platform to analyze conversation turns asynchronously.
- Exam Traps to Reject: Explicit parameter prompting disrupts natural conversation and goes against passive preference extraction. Regular expressions lack natural language understanding and create unnecessary operational maintenance compared to managed memory services.
Consolidated Golden Rules (Consideration 3.1c):
- Use Managed Sessions to maintain short-term, turn-level conversation state and ephemeral workflow variables.
- Use Agent Platform Memory Bank to persist extracted user facts and preferences across different sessions.
- Avoid stuffing raw chat transcripts into context prompts to optimize token usage and latency.
- Always enforce compliance-driven session expiration using server-side TTL settings rather than client-side logic.
- Managed Sessions store ephemeral turn states and parameters, whereas Memory Bank stores long-term persistent information.
- Session TTL is expressed in seconds (e.g., 900 seconds = 15 minutes) and is evaluated based on inactivity from the last interaction.
Consideration 3.1d: Configuring skills using agents cli (e.g., plugins and agent vs. human mode)
When managing skills and plugins with Agents CLI:
- Agent Mode vs. Human Mode: Use Agent Mode (
--agent/ headless autonomous mode) when running non-destructive tasks or automated CI/CD evaluation pipelines. Enforce Human Mode (interactive confirmation gate) whenever a skill invokes destructive or production-mutating tools (e.g., dropping database tables, modifying IAM policies, executing financial refunds). - OpenAPI Plugin Ingestion & Namespace Disambiguation:
Agents CLIcan ingest standard OpenAPI 3.0 specifications to register external microservices as agent plugins. When multiple registered plugins expose identically named tools (e.g.,get_statusin both Billing and Shipping plugins), configure explicit tool prefixes / namespaces (billing_get_status,shipping_get_status) and descriptive docstrings so the LLM router never calls the wrong backend. - Local Emulation & Mocking: Use
Agents CLIlocal emulation with mock tool responses during development so engineers can test agent reasoning loops without hitting live production payment or ERP endpoints.


Takeaway 1: Interactive Human-in-the-Loop Confirmation for High-Risk Skill Invocation (vertex_ai:agents · vertex_ai:reasoning_engine)
- Core Concept: Configuring execution modes (agent vs. human mode) for sensitive skill execution
- Scenario Trigger & Requirement: The scenario requires granular control over agent execution. Autonomous execution is desirable for safe tasks such as read-only invoice lookups, but sensitive, high-impact operations like wire transfers require human-in-the-loop oversight.
- Winning Architecture & Implementation: Set the wire transfer skill execution mode to human mode in the agent skill configuration, while keeping the invoice lookup skill set to agent mode. Configuring the wire transfer skill with human execution mode ensures that the runtime pauses and solicits explicit human approval before executing the tool.
- Exam Traps to Reject: Interception logic inside unrelated tools is anti-pattern and does not use native CLI skill modes. Global human mode pauses all skills rather than selectively gating high-risk actions.
Takeaway 2: Configuring Third-Party OpenAPI 3.0 Plugins via Agents CLI (vertex_ai:agents · secret_manager)
- Core Concept: Registering OpenAPI endpoints and security schemes using CLI tool definitions
- Scenario Trigger & Requirement: The scenario requires integrating an external REST API described by an OpenAPI 3.0 specification into an AI agent using the CLI. The solution must handle API key authentication securely without exposing credentials in source code.
- Winning Architecture & Implementation: Define a tool manifest that references the OpenAPI specification file and configure authentication by referencing a secret stored in Secret Manager. When registering external tools and plugins through the Agents CLI, the recommended and secure approach is to provide the OpenAPI 3.0 specification file and map the required security scheme (such as an API key header) to a secret reference in Secret Manager.
- Exam Traps to Reject: Raw credentials should never be hardcoded into OpenAPI specification files. Plaintext environment variables risk credential leakage and do not integrate with cloud secret management.
Takeaway 3: Local CLI Emulation and Mocking of External APIs (vertex_ai:agents · vertex_ai:reasoning_engine)
- Core Concept: Simulating skill responses during development without incurring live API calls
- Scenario Trigger & Requirement: The scenario requires testing an agentic workflow locally using the CLI while preventing live external API calls to third-party SMS and payment providers, all without modifying the production code.
- Winning Architecture & Implementation: Provide a local mock configuration file to the Agents CLI to stub responses for the gateway skills. Using a local mock configuration file with the Agents command-line interface (CLI) allows you to intercept skill calls and supply deterministic stub payloads.
- Exam Traps to Reject: Blocking firewall egress causes connection failures instead of structured mock responses. Modifying agent source code directly for testing is risky and anti-pattern.
Takeaway 4: Resolving Tool Name Collisions Across Multiple CLI-Registered Plugins (vertex_ai:agent_builder · vertex_ai:reasoning_engine)
- Core Concept: Namespacing and aliasing skills during CLI plugin import
- Scenario Trigger & Requirement: A common tool collision problem where two independent vendor plugins define identically named skills (
get_user_profile). The primary constraint is resolving the collision cleanly without modifying external source code. - Winning Architecture & Implementation: Configure unique namespace prefixes and skill aliases in the agent CLI configuration manifest for each imported plugin. When integrating multiple third-party plugins that have identical function or tool names, defining distinct namespace prefixes or method aliases in your CLI configuration file resolves the ambiguity.
- Exam Traps to Reject: Human-in-the-loop is meant for oversight, not for resolving deterministic naming collisions. Directly modifying upstream third-party plugin schemas breaks updates and creates maintenance overhead.
Consolidated Golden Rules (Consideration 3.1d):
- Enforce human-in-the-loop policies at the individual skill level to secure high-risk actions.
- Keep low-risk and read-only skills in autonomous agent mode to maintain conversational efficiency.
- Avoid global restrictions when fine-grained skill configurations fulfill specific governance requirements.
- External REST services are integrated into agents by providing OpenAPI 3.0 specifications to tool definitions.
- Sensitive credentials like API keys must be referenced via Secret Manager rather than embedded in code or specification files.
- Human-in-the-loop controls are used for operational approvals, not for passing system credentials.
Multi-Constraint Production Architecture Scenarios (Subsection 3.1)

Production Scenario & Hard Constraints | Winning Google Cloud Architecture | Why Look-Alike Alternatives Fail |
|---|---|---|
Vertex AI capability that minimizes cost and latency when repeatedly passing the same: Two distinct architectural challenges: high latency and high token costs resulting from repeatedly sending identical static context (five hundred pages of regulatory material) across hundreds of consecutive queries. | Enable Vertex AI Context Caching for the static regulatory document context. Context caching pre-processes and stores static prompt tokens across multiple requests, significantly cutting input token costs and accelerating time-to-first-token latency. | Foundation models lack proprietary regulatory details in weights, leading to inaccurate responses. Truncation discards essential legal context and leads to inaccurate discovery analysis. |
Proper session management strategy to preserve chat history during an active session: Two core constraints: the shopping agent must maintain conversation context during an active multi-turn interaction, but the agent must discard transient details once the user departs. Recognizing that large language models are fundamentally stateless highlights the necessity of an ephemeral, session-bound memory tier. | Implement short-term in-memory session management within the ADK session state handler. In-memory session management maintains context during active user interactions and automatically clears transient context once the session ends. | Requiring the user to repeat prior messages ruins the user experience and fails to implement conversational session state. BigQuery is an analytical data warehouse intended for permanent storage, not low-latency ephemeral session management. |
Persistence mechanism to manage long-term state and memory for conversational agents: A banking conversational agent that must preserve customer account settings and historical transaction patterns across sessions separated by multiple weeks. Key concepts include identifying the boundaries between short-term conversational context and durable long-term memory architectures. | Implement a long-term memory store backed by a persistent database such as Cloud Firestore or Cloud Spanner. Persistent databases such as Cloud Firestore or Cloud Spanner provide reliable, external storage required to maintain long-term agent memory across weeks. | Local virtual machine (VM) memory is volatile and cannot persist customer preferences across long intervals or across multiple server instances. Context windows only hold active conversational turns and do not persist data once a session terminates. |
Standard memory management technique for long multi-turn agent sessions to optimize: An enterprise conversational agent undergoing unbounded context expansion across hundreds of turns. The candidate must identify the architectural pattern that stabilizes token usage and stays within optimal context windows while maintaining interaction coherence. | Implement conversation summarization and sliding-window memory pruning in the ADK session pipeline. Summarization and sliding-window pruning compress historical context while preserving recent interactions within token budgets. | Arbitrarily terminating conversations damages customer experience and fails to address proper state management. Removing system instructions strips foundational agent behavior and safety parameters without resolving turn growth. |
Proper architectural pattern for managing user session state across distributed: The core challenge revolves around two constraints: multiple stateless Cloud Run container instances and the requirement for consistent session state across any instance handling subsequent requests. Cloud Run instances are dynamic, ephemeral, and scale out or in based on incoming traffic. | Configure an external session persistence store using Cloud Memorystore for Redis or Cloud Firestore. External centralized storage such as Cloud Memorystore or Cloud Firestore guarantees session consistency across ephemeral and autoscaling Cloud Run instances. | Using a single virtual machine (VM) introduces a single point of failure and undermines serverless scalability. Local memory is ephemeral and lost during instance scaling or restarts; relying on sticky routing is insufficient for distributed persistence. |
An episodic memory retrieval system for an AI agent by indexing summarized conversations: The design requirement specifies an episodic memory system for a conversational agent that retrieves past interactions based on semantic similarity. | Store past conversation summaries in Vertex AI Vector Search and query them before generating responses. Vertex AI Vector Search provides approximate nearest neighbor retrieval based on semantic embeddings to retrieve relevant past memories. | Cloud Logging supports keyword and regex filtering rather than semantic vector similarity retrieval. Appending full conversation logs exceeds context windows, incurs high token costs, and degrades performance. |
Standard architectural pattern for sharing state asynchronously across agents: An asynchronous dependency between two agents in a multi-agent architecture: Agent A collects data at one point in time, and Agent B requires that data thirty minutes later. Key elements to identify are: state persistence, asynchronous coordination, and state sharing across agents. | Persist the shared state object in a central ADK session state store accessible by both agents. Centralized session state storage allows multiple agents to asynchronously share and access context across turns and sessions. | Agents must never be instructed to hallucinate factual enterprise data. Manual email forwarding introduces user friction and latency instead of maintaining automated system state. |
Standard agent framework mechanism for parsing runtime entities and synchronizing: The scenario requires an conversational agent to capture dynamic conversational information (e.g., phone numbers, addresses) and immediately reflect those values in a structured profile state. Key constraints include real-time extraction, structured state persistence, and native framework capabilities. | Implement state extraction callbacks in ADK that parse tool outputs and messages into structured session variables. State extraction callbacks in agent frameworks parse incoming messages and tool responses directly into structured session variables in real time. | Retraining model weights for dynamic chat turn information is computationally infeasible and introduces catastrophic latency. Forcing users to supply structured JSON metadata degrades user experience and defeats the purpose of conversational AI. |
Native Cloud Firestore feature that automates document deletion based on a retention timestamp: The question specifies two primary constraints: storing sensitive conversational or agent memory in Cloud Firestore, and automatically deleting this data thirty days after the last interaction to satisfy privacy regulations. | Configure a Time-to-Live (TTL) policy on the Cloud Firestore collection containing session records. A built-in Time-to-Live (TTL) policy in Cloud Firestore automatically purges expired documents based on a designated timestamp field. | Annual manual deletion allows sensitive data to persist well past the 30-day requirement. Agent prompting controls interaction responses but does not delete underlying records from storage. |
Standard architectural pattern for persisting private, ephemeral calculations across: An agent orchestration scenario with two key requirements: The agent must retain and pass temporary numbers across three sequential tool calls within the same conversational turn. The intermediary numbers must remain hidden from the end user rather than being printed into the final chat output. | Store intermediate calculation variables in the agent internal execution state object. Internal execution state or session parameters store intermediate values across tool executions without exposing them to the user. | Browser storage exposes internal calculations to the client and requires unneeded round trips between tool invocations. Printing values directly exposes intermediate calculations to the user, violating the prompt requirement. |
Checkpointing and persistent state management enable conversational agents to recover: A common failure mode in multi-agent and tool-augmented LLM architectures: an unhandled exception or network timeout mid-turn during a tool invocation. | Implement checkpointing and persistent state management in the ADK execution graph. Checkpointing saves the intermediate state after each tool step to durable storage, allowing recovery from the exact failure point without repeating completed actions. | Restarting the conversation from the initial turn repeats previously completed actions and loses turn context. Discarding session history removes all conversation state instead of resuming from the last known good step. |
Standard architecture pattern for managing persistent long-term and working memory: A multi-day, long-running workflow for an autonomous research agent. The agent generates dynamic intermediate artifacts including hypotheses, execution notes, and plans that must survive across days and execution pauses. The primary technical requirement is external, durable state persistence suited for agent frameworks. | Implement persistent working memory stored in Cloud Firestore using ADK memory interfaces. Cloud Firestore provides durable external persistence for agent working memory and state across multi-day lifecycles through ADK memory interfaces. | Volatile local memory fails if the machine reboots or disconnects, leading to unrecoverable data loss. Session cookies are size-constrained (4 KB) and tied to client browsers rather than autonomous backend workflows. |
Standard architecture pattern for managing bulky tool payloads in agent session states: A common scalability challenge in multi-turn agent systems: handling large intermediate tool outputs (such as bulk data extracts or generated artifacts) that exceed model context token limits. The core problem requires identifying an architectural pattern that maintains data integrity without exhausting prompt memory. | Store the large file in Cloud Storage and pass only the file URI reference in the session state. Externalizing large intermediate outputs to Cloud Storage and passing only the URI reference prevents context window overflow while preserving complete data fidelity. | A 50MB file drastically exceeds context token limits, incurring prohibitive latency and immediate request failures. Truncating to three rows drops the vast majority of the data, which corrupts any subsequent analysis that requires complete records. |
Proper storage and architectural pattern for maintaining persistent, interconnected user: Two essential requirements: maintaining a structured 'knowledge graph' of connected user preferences and past purchases, and ensuring this knowledge persists 'across multi-turn interactions'. The ideal solution must provide structural relationship modeling along with durable, multi-session persistence connected to the agent architecture. | Deploy a graph database or persistent entity memory store connected to the ADK memory subsystem. A graph database or persistent entity store explicitly models connected entities and preserves long-term user context across sessions. | Clearing memory removes all state, preventing any persistence across multi-turn interactions. Appending unbounded text to a system prompt increases token costs and lacks structured relational modeling. |
Recommended pattern for updating and maintaining conversational session state in ADK: The question evaluates how to handle dynamic, user-specific data during multi-turn agent interactions within the Agent Development Kit (ADK). | Use explicit state mutation methods in ADK callbacks to update structured session state keys. ADK provides explicit state management APIs within callbacks to reliably maintain and persist session variables across conversational turns. | Local storage on a virtual machine (VM) is non-persistent and fails in distributed or stateless cloud runtime environments. Relying on model memory alone leads to hallucinations and data loss when context windows shift. |
Head-to-Head Architectural Trade-Off Clinic (Subsection 3.1)
State / Memory Requirement | Correct Google Cloud Architecture | Why the Common Distractor Fails |
|---|---|---|
Persist active multi-turn checkpoints for an ADK agent running on autoscaled Cloud Run | External Checkpointer backed by Cloud Firestore or Memorystore for Redis (or host on Agent Runtime) | In-memory Python dict + Cloud Run Session Affinity (containers scale down/restart, wiping local memory). |
Remember a user's long-term preferences and past resolved issues across sessions months apart | Agent Platform Memory Bank with asynchronous fact distillation and semantic retrieval | Appending every past session's full raw transcript into the system prompt (exhausts token limits and degrades recall). |
Pass a 100MB generated CSV report from Agent A to Agent B in a multi-agent workflow | Claim-Check Pattern: Write the file to Cloud Storage and pass the gs:// URI in shared session state | Serializing the 100MB file directly into the Firestore session state JSON or prompt context. |
Prevent concurrent sub-agents from overwriting each other's updates to the same session state key | Use Firestore transactional updates / optimistic locking or ADK reducer functions / isolated state keys | Blindly performing uncoordinated last-write-wins JSON overwrites across parallel workers. |
Repeatedly query the same 500-page regulatory PDF across 50 turns of a legal discovery session | Gemini 1.5/2.5/3 Pro Long Context combined with Vertex AI Context Caching | Re-sending 500 pages of un-cached tokens on every turn (10x higher cost and latency). |
Rapid Pattern-Trigger Cheat Sheet (Subsection 3.1)
If the Exam Scenario Mentions... | Choose This Architecture / Configuration | Reject This Common Distractor Trap |
|---|---|---|
"High-volume intent routing requires sub-200ms latency and minimal cost, while complex queries need deep reasoning" | Tiered Model Routing: Use an SLM ( Gemini Flash-Lite) as router/classifier and escalate complex queries to LLM (Gemini Pro) | Routing 100% of simple traffic through Gemini Pro |
"Strict defense/banking policy forbids data leaving a private GKE cluster or using multi-tenant SaaS APIs" | Deploy Self-Hosted Open-Weight Models ( Gemma / Llama) from Model Garden on private GKE GPU/TPU nodes | Using public SaaS endpoints with prompt-level anonymization |
"Consecutive user turns on Cloud Run lose conversation history when traffic scales" | Configure an external checkpointer in Cloud Firestore or Memorystore for Redis | Enabling Cloud Run sticky session affinity with local container memory or Cloud Storage FUSE |
"Conversations reach 300+ turns, causing token limit errors and rising latency" | Implement sliding-window history with rolling conversation summarization | Truncating the system prompt or dropping all turns older than 2 messages without summarization |
"Two CLI-registered OpenAPI plugins both define a tool named update_record" | Configure explicit namespace prefixes (e.g., crm_update_record, erp_update_record) and distinct tool descriptions | Merging both OpenAPI specs into a single endpoint or relying on random ordering |
Curated Official Google Cloud Documentation (Subsection 3.1)
- Vertex AI Agent Builder Overview — Overview of building generative AI agents and programmatic extensions using Google Cloud tooling and frameworks.
- Gemma Open Models Overview — Details lightweight, state-of-the-art open models built from the same research and technology used to create Gemini models, ideal for resource-constrained environments.
- Select a Foundation Model in Vertex AI — Covers criteria for choosing appropriate Gemini and open-source models based on latency, cost, and task complexity requirements.
- Generative AI on Vertex AI overview — Provides detailed information about consuming foundation models as a service through managed APIs in Vertex AI.
- Google Cloud service models and shared responsibility — Explains the shared responsibility model across SaaS, PaaS, and IaaS architectures in Google Cloud.
- Vertex AI Agent Builder Overview — Provides architectural details and capabilities for building enterprise search and conversational agents with managed memory and grounding.
- Vertex AI Agent Builder Sessions Overview — Explains how sessions represent conversations between end users and conversational agents to manage multi-turn state and parameters.
- Explore AI models in Model Garden — Official Google Cloud documentation explaining how to discover, test, and deploy first-party, third-party, and open-source models in Vertex AI Model Garden.
- Agent Registry overview — Centralized catalog to store, discover, and govern tools, skills, MCP servers, and agents.
- Memorystore for Redis Overview — Provides comprehensive architectural details on Memorystore for Redis, emphasizing sub-millisecond latency and in-memory key-value persistence.
- Firestore Overview — Provides an overview of Firestore as a serverless, document-oriented NoSQL database.
- Firestore for LangChain Chat Message History — Details how to persist conversation history and memory in custom GenAI agents using Firestore.
Book TOC · Previous · Chapter 3 of 8 · Next
AwesomeGCP.com Learning
The approach taken is a question-led learning approach: you explore realistic project scenarios where you need to make decisions or take actions to achieve business goals within specific constraints. Instead of passive learning, you are challenged to think and work through the options to master the Professional Agentic Architect (PAA) certification!