← All Google Cloud AI guidesGen AI · 1.2, 2.2, 3.2

The Google Cloud gen AI stack: Gemini, Model Garden and Agent Platform

How generative AI is built on Google Cloud in 2026: what Gemini Enterprise Agent Platform contains, choosing models in Model Garden (first-party, partner, open; serverless or self-deployed), prompt and context engineering, function calling and structured output, the adaptation ladder from prompting to tuning and distillation, agents (ADK, Agent Runtime, Memory Bank), and cost, latency and availability levers. Includes a token cost calculator.

1. The Agent Platform gen AI map

Gemini Enterprise Agent Platform (formerly Vertex AI) groups Google Cloud's gen AI pieces. Exam questions name the piece; you pick the one whose job matches.

PieceJobOld name
Model GardenCatalogue of Google, partner and open models; deploy or call themSame
Gemini API on Agent PlatformGenerate content: text, images, audio, video, code; function calling; structured outputVertex AI Gemini API
Agent StudioConsole playground: prompt design, compare, tune, save promptsVertex AI Studio
Agent Development Kit (ADK)Open-source framework for building agents and multi-agent systems in codeSame
Agent RuntimeManaged runtime to deploy and scale agents, with Sessions, Memory Bank and Code ExecutionAgent Engine
Agent SearchManaged enterprise search and RAG over your data storesVertex AI Search
RAG EngineManaged RAG pipeline: ingest, chunk, embed, index, retrieveSame
Agent RetrievalVector similarity search at scale (approximate nearest neighbour), hybrid searchVector Search
Agent Platform EvalsEvaluate models, prompts and agents (pointwise, pairwise, rubrics, trajectories)Gen AI evaluation service
Model ArmorScreens prompts and responses for injection, jailbreaks, sensitive data, harmful content, malicious URLsSame
TuningSupervised fine-tuning, preference tuning, distillationSame
SDKs and CLIs kept their names: google-cloud-aiplatform, the Google Gen AI SDK (google-genai), gcloud ai. Questions may use either the old or new product names.

2. Model Garden: which model, and how to run it

Model Garden is the catalogue of first-party (Gemini, Imagen, Veo, Gemma), partner (for example Anthropic Claude, Meta Llama, Mistral) and open models. Some are offered as models as a service (MaaS): a serverless API you pay per token. Others you deploy to your own endpoint with chosen hardware, paying for the nodes.

NeedPick
Hardest reasoning, long documents, complex multimodalGemini Pro tier
Low latency and cost at high volumeGemini Flash or Flash-Lite tier
Images / video generationImagen / Veo
Open weights, run in your VPC, customize freelyGemma or another open model deployed from Model Garden to an endpoint or GKE
A specific partner model the team standardized onThat model through MaaS
Text embeddings for search or RAGGemini embedding / text-embedding models

Three ways to run a model

How you run itWhat it meansPay forChoose when
Model as a service (MaaS)Serverless API managed by Google; nothing to deployTokens (or Provisioned Throughput)Fastest start, spiky traffic, no infrastructure team
Self-deploy to an Agent Platform endpointOne-click deploy of open weights onto GPUs/TPUs you chooseNode hours, even when idleOpen model, custom weights (LoRA), data in your VPC, steady high traffic
Deploy on GKERun the model yourself with vLLM, TGI or similarCluster nodesExisting Kubernetes platform, maximum control, multi-model serving

Choosing between Gemini tiers

3. Generation parameters

ParameterEffectTypical choice
temperatureRandomness of token choice; 0 is near-deterministic0 to 0.3 for extraction and classification; higher for creative writing
top_p (nucleus)Samples from the smallest set of tokens whose probability adds to pLeave default unless tuning diversity
top_kSamples from the k most likely tokensRarely changed
max_output_tokensCaps response length and costSet it; truncated output ends with finish reason MAX_TOKENS
stop_sequencesStop generating at given stringsDelimited formats
candidate_countSeveral responses per requestSelf-consistency or picking the best
Thinking controls (budget or level)How much internal reasoning the model does before answeringMore for multi-step problems; less for latency and cost
seedMore reproducible samplingTesting
Temperature 0 reduces variation but doesn't guarantee identical outputs. For reliability, combine low temperature with structured output and evaluation.

4. Prompt and context engineering

TechniqueWhat it does
System instructionsRole, rules, tone and constraints that apply to the whole conversation
Zero-shot vs few-shotInstructions alone vs instructions plus worked examples; few-shot fixes format and edge cases
Clear structureDelimit inputs (tags or headings), state the task, give the output format, say what to do when unsure
Chain-of-thought / thinkingLet the model reason step by step for multi-step problems (built-in thinking on newer models)
Decomposition and prompt chainingSplit a complex task into steps, each with its own prompt and checks
Self-consistencySample several answers and take the majority
GroundingSupply facts in context (RAG, Google Search) instead of relying on memory
Context engineeringDeciding what goes in the context window: instructions, retrieved chunks, tool results, conversation history, memory. Less but relevant beats more

Long context vs RAG

Put everything in a long contextRetrieve with RAG
Good forA few large documents analysed as a whole; one-off analysisLarge or changing corpora; many users; citations; access control
Cost and latencyEvery request pays for every token (context caching helps)Only the relevant chunks are sent
RiskDetails "lost in the middle" of very long inputsRetrieval misses the right chunk

5. Structured output and function calling

Structured output

Set response_mime_type="application/json" and a response_schema (OpenAPI-style or JSON Schema). The model is constrained to produce valid JSON matching the schema: enums for categories, required fields, types. This is the answer to "the app keeps failing to parse the model's JSON".

from google import genai
from google.genai import types

client = genai.Client(vertexai=True, project="PROJECT_ID", location="global")
resp = client.models.generate_content(
    model="gemini-flash-model-id",
    contents="Ticket: 'App crashes when I upload a photo.'",
    config=types.GenerateContentConfig(
        temperature=0,
        response_mime_type="application/json",
        response_schema={"type": "OBJECT",
                         "properties": {"category": {"type": "STRING", "enum": ["bug", "billing", "account", "other"]},
                                        "urgent": {"type": "BOOLEAN"}},
                         "required": ["category", "urgent"]}))
print(resp.text)   # {"category": "bug", "urgent": false}

Function calling (tool use)

  1. You declare functions (name, description, parameter schema).
  2. The model decides whether to call one and returns a function call with arguments. It doesn't execute anything.
  3. Your code runs the function (an API, a database query) and sends back the result as a function response.
  4. The model uses the result to answer, or calls another function.
Validate function arguments and enforce authorization in your code. The model can be manipulated (prompt injection) into requesting calls a user shouldn't make; least-privilege tool credentials limit the blast radius.

6. Adapting a foundation model: the tuning ladder

TechniqueWhat it changesUse when
Prompt engineeringInstructions, examples (few-shot), system instructions, output schemaAlways first: cheapest and fastest to iterate
Grounding / RAG (retrieval-augmented generation)Adds retrieved facts to the prompt: Grounding with Google Search, Agent Search, RAG Engine, Vector SearchThe model needs fresh or private facts, or must cite sources and hallucinate less
Supervised fine-tuning (parameter-efficient, adapter-based)Model behaviour: style, format, domain task, classification labelsPrompting can't reach the quality, or prompts are getting long and costly; you have hundreds or more labelled examples
Preference tuning / reinforcement learningAligns with human preferencesYou have preference pairs; quality judged by people
DistillationTeaches a small model to imitate a large oneNeed Pro-like quality at Flash-like cost and latency
Fine-tuning doesn't teach a model new facts reliably and doesn't keep them fresh. "The answers must reflect documents that change daily" is a grounding/RAG problem, not a tuning problem.

Supervised fine-tuning in practice

TopicWhat to know
DataJSONL of example conversations (user input, ideal model output), in Cloud Storage. Quality and consistency beat volume; start with ~100–500 good examples
MethodParameter-efficient (adapter, LoRA-style) tuning on Gemini; full or LoRA tuning for open models from Model Garden
HyperparametersEpochs, adapter size, learning-rate multiplier; watch validation loss for overfitting
OutputA tuned model served from its own endpoint; call it like the base model
EvaluateAgainst the base model with prompting, on a held-out set, with Agent Platform Evals
CostTuning job cost plus serving the tuned model; re-tune when the base model version retires
Decision: knowledge problem (facts, freshness, citations) → grounding/RAG. Behaviour problem (format, style, a narrow task's accuracy, shorter prompts) → tuning. Cost/latency problem with a big model working well → distillation or a smaller tier.

7. Agents: ADK, Agent Runtime, Sessions and Memory Bank

An agent is a model in a loop: it plans, calls tools, reads results and continues until the task is done. Use agents when the steps aren't known in advance; use a fixed workflow (a chain or pipeline) when they are.

PieceRole
ADKDefine agents, tools, sub-agents and workflow agents (sequential, parallel, loop) in Python or other languages; run locally
Agent RuntimeDeploy ADK (or LangGraph, LangChain and other framework) agents as a managed, autoscaling service with IAM, logging and tracing
SessionsStores conversation history and state for one interaction
Memory BankLong-term memory across sessions: extracts and recalls user facts and preferences
Code ExecutionSandboxed environment where an agent runs code it writes
Agent GardenSamples and templates to start from
Gemini EnterpriseEmployee-facing app where agents are shared and used across the company

Agent design choices the exam probes

8. Safety settings and responses

ControlWhat it does
Safety filtersHarm categories (harassment, hate speech, sexually explicit, dangerous content) with blocking thresholds; non-configurable filters for the most severe content (such as CSAM)
Finish reasonSTOP normal, MAX_TOKENS truncated, SAFETY blocked by filters, RECITATION too close to training data
Prompt feedbackA blocked prompt returns a block reason and no candidates
Model ArmorTemplates that screen prompts and responses: prompt injection and jailbreak, sensitive data (via Sensitive Data Protection), malicious URLs, responsible-AI categories
System instructionsScope and refusal rules ("only answer about our products")
Deeper coverage of security, responsible AI and monitoring is in Responsible AI and monitoring.

9. Cost, latency and availability

LeverEffect
Smaller model tier (Flash, Flash-Lite)Lower cost and latency; evaluate quality on your task first
Context cachingReuse a large, repeated prefix (a manual, a codebase) across requests at a discount, with lower latency
Batch inferenceAsynchronous jobs over BigQuery or Cloud Storage at roughly half the online price; minutes to hours of latency
Provisioned ThroughputReserved capacity for predictable, production traffic; avoids 429s under shared quota
Global endpointRoutes to available regions for higher availability (when data residency allows)
Retry with exponential backoffCorrect response to 429 Resource exhausted under dynamic shared quota
Streaming responsesBetter perceived latency (time to first token) for chat
Shorter prompts, max_output_tokens, structured outputFewer tokens billed; parseable JSON without retries
Discount sizes and quota behaviour are set by current pricing pages. Learn the direction (batch and caching cost less; provisioned throughput buys reliability), not the exact percentages.

Context caching in detail

10. Token cost calculator

Prices below are placeholders, not current list prices: enter the numbers from the pricing page. The point is how the levers compare.

11. Lab: a structured, tool-using Gemini app

  1. In Agent Studio, write a system instruction for a support triage assistant. Try zero-shot, then add three examples; note which edge cases improve.
  2. In a notebook with the Google Gen AI SDK, request structured output with an enum category and boolean urgent; run 50 tickets and count parse failures (should be zero).
  3. Declare a function get_order_status(order_id); implement it as a stub; confirm the model returns a function call and that your code executes it.
  4. Compare a Flash-Lite and a Flash tier on the same 50 tickets: accuracy, latency and token counts from usage metadata.
  5. Put a 30-page policy document first in the prompt and send 20 questions; compare cached token counts and latency between the first and later requests.
  6. Wrap the assistant as an ADK agent with the tool and deploy it to Agent Runtime; enable Sessions and check that a follow-up question uses earlier context.

Clean up: delete the Agent Runtime deployment, explicit caches and any tuned-model endpoints.

12. "Which gen AI option?" chooser

Pick an item to see what it means, why, and the tempting wrong choice.

Pick one above.

13. Sample outputs

What the tools return. Expand an item to see a typical result and what to read in it.

Illustrative output, not captured from a real project. IDs, numbers and some field names are invented or simplified, and formats change between releases. Learn the shape and the fields called out under each one.
Gemini response metadata (REST, simplified)Safety ratings and token usage
"candidates": [{
  "finishReason": "SAFETY",
  "safetyRatings": [
    {"category": "HARM_CATEGORY_DANGEROUS_CONTENT", "probability": "MEDIUM", "blocked": true},
    {"category": "HARM_CATEGORY_HARASSMENT", "probability": "NEGLIGIBLE"}
  ]
}],
"usageMetadata": {"promptTokenCount": 8123, "cachedContentTokenCount": 7900,
                  "candidatesTokenCount": 0, "totalTokenCount": 8123}

What to look at: finishReason: SAFETY means a safety filter blocked the output; adjust the threshold for that category only if policy allows, or change the prompt. Most prompt tokens came from the context cache, which is cheaper than uncached input.

generate_content with tools (response, simplified)A function call the model wants you to run
{
  "candidates": [{
    "content": {"role": "model", "parts": [{
      "functionCall": {"name": "get_order_status", "args": {"order_id": "A-10442"}}
    }]},
    "finishReason": "STOP"
  }],
  "usageMetadata": {"promptTokenCount": 212, "candidatesTokenCount": 18}
}

What to look at: The model didn't fetch anything: it returned a functionCall with arguments. Your code must validate order_id, check the user is allowed to see it, call the API, and send the result back as a functionResponse part in the next turn.

14. Scenarios

Exam-style situations: how to diagnose each one, the likely cause and the fix.

15. Searchable reference

ItemMeaning

16. Flashcards (click to flip)

17. Common gotchas in one list

  1. Tuning changes behaviour, not knowledge. Fresh or private facts need grounding.
  2. The model never executes functions; your code does, and must check authorization.
  3. Structured output beats "please return JSON" for reliable parsing.
  4. Start with the cheapest tier that passes evaluation, not the biggest model.
  5. MaaS for no-ops and spiky traffic; self-deploy for custom weights, VPC control or steady load.
  6. Pin model versions and re-run evaluations before upgrading.
  7. 429s mean quota pressure: exponential backoff, then Provisioned Throughput for steady load.
  8. Batch inference for big, non-urgent jobs: discounted and asynchronous.
  9. Context caching needs the shared content at the start of the prompt.
  10. Sessions are short-term; Memory Bank is long-term.
  11. Prefer one agent with tools before multi-agent designs.
  12. Temperature 0 isn't determinism; evaluate and constrain output.
  13. Long context isn't free: every request pays for all tokens unless cached.

18. Practice quiz (24 questions)

Score: 0 / 0
← BigQuery ML, AutoML and AI APIsNext: RAG and its failure modes →