Generative AI on Vertex AI in Google Cloud: From First Prompt to Production-Grade AI Systems

Generative AI on Vertex AI in Google Cloud: From First Prompt to Production-Grade AI Systems

A deep, plain-English guide to Google Cloud's generative AI platform: models, prompts, grounding, retrieval, agents, tuning, evaluation, safety, security, capacity, and the patterns that keep real applications reliable.

Imagine a huge library staffed by an extraordinarily well-read assistant. This assistant has read more books than any human could in a thousand lifetimes, can write, summarize, translate, explain, and reason about pictures, audio, and video, and answers any question within seconds. Now imagine that same assistant needs to work inside your company: it must know your private documents, obey your safety rules, never leak confidential data, handle ten thousand visitors at once, and send a bill your finance team can predict. A brilliant assistant alone is not enough. You also need a building around it, with doors, locks, shelves, phone lines, and supervisors. Generative AI on Vertex AI is Google Cloud’s building around the assistant.

1Why Generative AI Needs a Platform

A clever demo and a dependable product are separated by a surprising amount of engineering.

The demo trap

Anyone can type a question into a chat box and be amazed. The trouble starts when a team tries to turn that moment of magic into a feature that thousands of customers rely on every day. Suddenly there are questions that the demo never asked. What happens when the model invents a fact? How do we let it read our policy manuals but not our payroll files? How do we measure whether version two is really better than version one? What if traffic triples on a holiday? Who is allowed to call the model, and how do we prove it later to an auditor?

A generative AI platform answers these questions once, centrally, so that every team does not have to solve them again. It provides access to models, tools to design and test prompts, ways to connect models to trustworthy data, safety controls, security boundaries, monitoring, and capacity options. Without such a platform, each project grows its own fragile collection of scripts and workarounds.

Simple Analogy

A model is like a powerful engine. A platform is the whole car: steering, brakes, seat belts, a fuel gauge, and a dashboard. Nobody would send an engine alone onto a motorway, however impressive it is.

The five gaps a platform must close

Gap 1

Truthfulness

Models can state wrong things confidently, so answers need grounding in real sources.

Gap 2

Knowledge

Models do not know your private, recent, or internal information unless you connect it.

Gap 3

Safety and security

Outputs must be filtered, and access to data and models must be controlled and audited.

Gap 4

Quality measurement

Teams need repeatable ways to compare prompts, models, and versions.

Gap 5

Operations

Capacity, cost, latency, retries, and monitoring must be planned like any production service.

!
Common Misconception

A bigger or newer model is not a cure for every problem. Many failures come from missing context, weak prompts, or absent evaluation rather than from model size. A platform helps you diagnose which of these is actually the cause.

2What Generative AI on Vertex AI Actually Is

Vertex AI is Google Cloud’s managed platform for building, deploying, and operating AI, including generative AI.

The one-sentence definition

Generative AI on Vertex AI is the set of Google Cloud services that give you access to foundation models, such as Google’s Gemini family, along with the tools to prompt, ground, tune, evaluate, secure, deploy, and monitor applications built on them. Its documentation covers a wide range of model types: text and multimodal models, image models, video models, music models, speech models, embedding models, and open models that you can deploy yourself.

A note on names that change

Cloud product names move over time, and this one moved recently. In April 2026, at its Cloud Next event, Google announced the Gemini Enterprise Agent Platform as an evolution of Vertex AI, adding a larger focus on building, governing, and running agents. Reports on the change describe many products being renamed: for example, Vertex AI Studio became Agent Studio, and Vertex AI Agent Engine became Agent Runtime. The same reports say that the underlying service name used in API calls stayed the same and that existing resources continued to work. Because documentation, consoles, and third-party articles may show either set of names, this tutorial uses “Vertex AI” for the platform and mentions new names where helpful. Always confirm current names and details in the official documentation.

i
Reading Tip

When you search for help and find two names for the same thing, do not panic. Match features, not labels. A capability such as grounding, tuning, or evaluation keeps its purpose even when its product label changes.

What you can do with it

1

Choose a model

Browse a catalogue of Google, open, and partner models and pick the best fit for quality, speed, and cost.

2

Design prompts

Experiment in a studio-style interface, then save and version what works.

3

Connect knowledge

Ground answers with web search, maps data, or your own enterprise content through retrieval.

4

Customize

Tune models on your own examples when prompting and retrieval are not enough.

5

Evaluate and protect

Measure quality, apply safety filters, and enforce security controls.

6

Deploy and operate

Pick a capacity model, monitor usage, control cost, and improve continuously.

“The model is the brain. The platform is everything that lets the brain do safe, useful work.”

3Core Concepts You Must Know

A dozen words explain almost every generative AI conversation.

Term 1

Foundation model

A very large model trained on huge amounts of data that can perform many tasks without being built for each one.

Term 2

Prompt

The input you give a model: instructions, questions, examples, and any supporting material.

Term 3

Token

A small piece of text or media that the model reads and writes. Costs and limits are usually counted in tokens.

Term 4

Context window

The maximum amount of input and output a model can handle in one request.

Term 5

Multimodal

Able to understand more than one kind of input, such as text, images, audio, and video.

Term 6

Temperature

A setting that controls how adventurous or predictable the answers are.

Term 7

Embedding

A list of numbers that captures the meaning of text or media so similar things sit close together.

Term 8

Grounding

Connecting answers to trustworthy sources so they can be checked and cited.

Term 9

RAG

Retrieval-augmented generation: finding relevant material first, then letting the model answer using it.

Term 10

Tuning

Adjusting a model on your own examples so it behaves in a more specialized way.

Term 11

Agent

A system where a model plans steps, calls tools, and works toward a goal with some independence.

Term 12

Hallucination

A confident-sounding answer that is not supported by facts or by the supplied sources.

Tokens: the currency of generative AI

Models do not read whole words the way people do. They read tokens, which may be a whole short word, part of a long word, a punctuation mark, or a small chunk of an image or sound. Providers count tokens for limits and pricing, so understanding them helps you predict both. A long document pasted into a prompt consumes many tokens, and so does a long answer. Efficient prompts keep only what the model needs.

Simple Analogy

Tokens are like postage stamps. Every word you send and every word you receive needs stamps. A short postcard is cheap, a thick parcel costs more, and the post office has a maximum parcel size, which is the context window.

Temperature: dial between careful and creative

Low temperature makes answers more consistent and predictable, which suits extraction, classification, and factual tasks. Higher temperature adds variety, which suits brainstorming and creative writing. Many production systems use low values for tasks that must be repeatable and reserve high values for ideation.

!
Common Mistake

Believing that a lower temperature guarantees truth. It only makes outputs steadier. A model can be consistently wrong, which is why grounding and evaluation matter.

4Architecture and Components

A bird’s-eye view of how the pieces of a generative AI application fit together on Google Cloud.

The layers of a typical application

Most applications built on Vertex AI have five layers. The experience layer is what users touch: a chat window, a mobile app, an internal tool, or a back-end process. The orchestration layer decides what happens for each request, assembling prompts, calling tools, and handling errors. The knowledge layer supplies trustworthy information through search, retrieval, and databases. The model layer holds the foundation models. The governance layer wraps everything with safety, security, evaluation, and monitoring.

flowchart TD
  U["Users and applications"] --> O["Orchestration service"]
  O --> G1["Safety checks on input"]
  G1 --> K["Knowledge layer: search, retrieval, databases"]
  K --> P["Prompt assembly with context"]
  P --> M["Foundation model"]
  M --> G2["Safety checks on output"]
  G2 --> O
  O --> U
  O --> L["Logging, monitoring, evaluation"]
        
FIG 1 — Layers of a typical generative AI application

Components at a glance

ComponentRoleTypical partner services
Model catalogueFind and use Google, open, and partner modelsModel Garden
Prompt studioDesign, test, and save promptsStudio interface and prompt tools
Knowledge and retrievalSupply trustworthy contextSearch, vector search, RAG tools, databases
AgentsPlan steps and call toolsAgent development kit and runtime
TuningSpecialize a model on your examplesCloud Storage datasets, tuning jobs
EvaluationMeasure and compare qualityEvaluation datasets, judge models
Safety and securityFilter content and protect dataSafety filters, IAM, Model Armor, key management
OperationsCapacity, logging, cost controlProvisioned capacity, monitoring tools, billing alerts
Models
Google, open, and partner options
Context
Grounding and retrieval for trust
Controls
Safety, security, and evaluation
i
Design Tip

Keep orchestration in your own code, separate from any single model. When models improve or retire, you change one configuration instead of rewriting the application.

5Model Garden and the Model Families

Choosing the right model is the first and most influential decision.

A catalogue, not a single model

Model Garden is the place to browse, test, and use models. The documentation lists several families. Gemini is Google’s flagship family, including larger models for deeper reasoning and lighter, faster models for high-volume work, along with variants for live conversation, speech, translation, and embeddings. Other families cover image generation, video generation, and music. Open models such as the Gemma family can be deployed on your own endpoints. Partner models from other companies are also offered through the catalogue. Announcements around the platform’s 2026 evolution described a catalogue of more than two hundred models, so the choice is broad and changes often.

Simple Analogy

Choosing a model is like choosing a vehicle. A heavy truck, a family car, and a scooter can all move you from A to B. The right one depends on the load, the distance, the road, and the budget.

How to choose

NeedLean towardWhy
Complex reasoning, long documents, coding helpLarger, more capable modelsHigher quality on hard tasks
High volume, low latency, simple tasksLighter, faster modelsLower cost and quicker responses
Images, audio, or video understandingMultimodal modelsAccept more than text
Image, video, or music creationSpecialized generation modelsBuilt for media output
Strict control over hostingOpen models on your endpointsYou manage deployment and data location
Semantic search and clusteringEmbedding modelsProduce meaning vectors

Test before you commit

Public benchmarks describe general ability, not your task. The only fair comparison is a trial on your own examples. Take fifty to a few hundred real inputs, run them through two or three candidate models, and score the results. Teams are often surprised that a smaller, cheaper model matches a larger one on their specific task.

!
Common Mistake

Starting with the biggest model by default and never revisiting the choice. Cost and latency at scale are driven by model size, so a small quality gain may not justify a large bill.

Advantages

  • One catalogue for many models and providers
  • Easy side-by-side testing before building
  • Mix models by task inside one application
  • Open models available for self-hosting needs

Disadvantages / Trade-offs

  • Many options can slow decisions without a test plan
  • Model versions retire and need migration
  • Regional availability varies by model
  • Partner and open models have different terms and features

6Gemini and Multimodal Understanding

Modern models read pictures, sound, and video, not only text.

What multimodal really means

A multimodal model can accept mixed input in a single request. You can show a photograph of a damaged package and ask whether it qualifies for a refund. You can supply a recording of a meeting and ask for decisions and action items. You can provide a chart and ask for the trend in plain language. The model reasons across the modes together, so a question can depend on both the picture and the words.

Simple Analogy

A text-only model is like a colleague who can only read emails. A multimodal model is a colleague who can also look at your screen, listen to the call, and watch the training video, then give one combined answer.

Practical uses

Document understanding

Read scanned forms, receipts, and diagrams directly, then answer questions or extract structured fields.

Customer support with images

Let customers upload photos of faulty products and receive guided troubleshooting based on what the image shows.

Meeting and media summaries

Turn long recordings into summaries, timestamps, and decision lists for people who could not attend.

Live conversation

Real-time voice and video interactions use specialized live variants designed for low delay.

Long context: handling big inputs

Some models accept very large amounts of input at once, which allows analysis of long reports, many documents, or lengthy transcripts in a single request. Long context is powerful, but it is not free. More input means more cost and often more delay, and models can still overlook details buried in the middle of enormous inputs. Careful structure, such as labelled sections and clear questions, improves results.

i
Practical Advice

For repeated questions over the same large document, use context caching, covered later, so you do not pay to resend the same material every time.

!
Common Mistake

Dumping everything into the prompt “just in case”. Irrelevant material distracts the model, raises cost, and can reduce accuracy. Select what matters.

7Prompt Design and the Studio

The prompt is the steering wheel. Small changes in wording can change results dramatically.

Anatomy of a strong prompt

A strong prompt usually has several parts. It states the role or context, such as “you are a support assistant for a travel company”. It gives a clear task. It supplies the input material. It describes the desired format, such as a short list or a structured record. It may add examples that show good answers. And it lists constraints, such as tone, length, or topics to avoid.

1

Set the context

Say who the model is helping and what the situation is.

2

State the task

Use a precise verb: classify, extract, summarize, compare, draft.

3

Provide the material

Include the text, data, or media the model should work on, clearly separated from instructions.

4

Define the format

Describe the shape of the answer so downstream systems can use it.

5

Show examples

One to five good examples often teach more than a paragraph of rules.

Simple Analogy

Writing a prompt is like briefing a smart new intern. If you say only “handle this”, you get guesses. If you explain the goal, show a sample, and describe what a good result looks like, you get what you wanted.

Zero-shot, few-shot, and step-by-step prompting

Zero-shot prompting gives instructions with no examples. Few-shot prompting adds a handful of sample inputs and outputs, which helps with unusual formats and judgement calls. Step-by-step prompting asks the model to reason through intermediate steps before the final answer, which can help on logic and calculation tasks. The right technique depends on task difficulty, and each should be tested rather than assumed.

Studio tools and prompt management

The studio interface lets you try prompts against different models, adjust settings, and compare outputs. Prompt optimization tools can suggest improvements, and prompt templates let you save a prompt with named placeholders so that applications fill in only the changing parts. Treat saved prompts like code: version them, review changes, and link each version to evaluation results.

ANTI-PATTERN-01 Avoid
Problem

Editing production prompts directly in an application file or a console without records.

Why It’s Harmful

Nobody knows which wording produced which behavior, regressions go unnoticed, and rollback is impossible.

Correct Approach

Store prompts as versioned templates, run an evaluation set before each change, and keep a changelog tied to results.

8System Instructions, Structured Output, and Function Calling

Three features turn a chatty model into a dependable component of a larger system.

System instructions: the standing rules

System instructions are rules that apply to the whole conversation, separate from the user’s messages. They define persona, tone, boundaries, and safety behavior, for example “answer only from the supplied policy text” or “never give legal advice”. Because they are separate from user input, they are the right place for rules that must hold in every turn. They also contribute to safety, since clear instructions reduce the chance of off-topic or risky replies, although they are not a complete defense on their own.

Structured output: answers machines can read

Applications often need predictable data, not free prose. Structured output lets you ask the model to return answers in a defined shape, with named fields and allowed values. A support triage system might need a category, an urgency level, and a short summary. When the format is enforced, downstream code can read the result reliably, and fewer errors slip through.

Function calling: letting the model use tools

Models know a lot, but they cannot check today’s stock level or create a ticket by themselves. Function calling lets you describe tools to the model. When a question needs one, the model responds with a request to call a specific tool and the arguments to use. Your application runs the tool, returns the result, and the model uses it to write the final answer. The model never touches your systems directly; your code stays in control of what actually runs.

sequenceDiagram
  participant User
  participant App as Your application
  participant Model as Foundation model
  participant Tool as Business system
  User->>App: Where is my order?
  App->>Model: Question plus tool descriptions
  Model-->>App: Request to call order lookup tool
  App->>Tool: Look up order status
  Tool-->>App: Order shipped, arrives Friday
  App->>Model: Tool result
  Model-->>App: Friendly final answer
  App-->>User: Your order arrives Friday
        
FIG 2 — Function calling keeps your code in control
Simple Analogy

Function calling is like a manager who writes a note saying “please check the warehouse system for order 1234”. An assistant carries out the check and brings back the result. The manager never needs access to the warehouse keys.

!
Common Mistake

Giving tools broad power, such as “run any database command”. Treat tool requests from a model as untrusted suggestions. Validate arguments, restrict what each tool can do, and require human approval for risky actions like payments or deletions.

i
Practical Advice

Describe each tool clearly, with a purpose, inputs, and limits. Clear tool descriptions are the single best way to help the model choose the right tool at the right time.

9Embeddings and Vector Search

Embeddings let computers search by meaning instead of by exact words.

Meaning as numbers

An embedding model converts a piece of text, an image, or other content into a long list of numbers. The key property is that content with similar meaning receives similar numbers. “How do I reset my password?” and “I forgot my login” share almost no words, yet their embeddings sit close together. This makes it possible to find relevant material even when the wording differs completely.

Simple Analogy

Imagine a huge map where every sentence has a location, and sentences about the same idea live in the same neighborhood. A question is simply a new pin on that map. Searching means looking at which pins are nearby.

Vector search: finding the neighbors fast

A vector index stores embeddings and answers one question quickly: which stored items are closest to this one? Specialized vector search services can handle huge collections with low delay, and databases increasingly offer vector features as well. The index is the engine behind semantic search, recommendations, duplicate detection, and retrieval for question answering.

1

Prepare content

Clean and split documents into meaningful chunks with titles and metadata.

2

Create embeddings

Use an embedding model to turn each chunk into numbers.

3

Store in an index

Save vectors with the original text and metadata such as source, date, and access rights.

4

Embed the question

Use the same embedding model for the user’s query, so both live on the same map.

5

Retrieve neighbors

Fetch the closest chunks and pass them onward as evidence.

Hybrid search often wins

Pure meaning-based search can miss exact identifiers such as part numbers, error codes, or names. Classic keyword search handles those well but misses paraphrases. Combining both, often called hybrid search, usually gives the best results, especially in enterprise settings full of codes and jargon.

!
Common Mistake

Mixing embeddings from different models in one index. Vectors from different models do not share a map, so comparisons become meaningless. If you change embedding models, re-embed everything.

i
Design Tip

Store access-control information as metadata with each chunk, and filter by it during search. Retrieval should never return documents the user is not allowed to see.

10Grounding: Answers You Can Check

Grounding connects what a model says to sources that can be verified.

Why grounding exists

A model’s built-in knowledge comes from training and has a cutoff date. It may be outdated, incomplete, or simply wrong, and it will often sound equally confident in all three cases. Grounding addresses this by giving the model trustworthy material at question time and, ideally, by returning references so users can check where the answer came from.

Sources you can ground on

Source 1

Web search

Brings in fresh public information for questions about recent events and changing facts.

Source 2

Maps and places

Supplies location data such as places, hours, and distances for travel and local questions.

Source 3

Enterprise search

Draws on your own indexed company content with access controls.

Source 4

Retrieval stores

Uses your own vector or RAG corpus built from documents and databases.

Source 5

Third-party search

Uses outside search providers where the platform supports them.

Simple Analogy

An ungrounded answer is a confident friend recalling something from memory. A grounded answer is the same friend opening the reference book, reading the page, and showing you the page number.

Citations build trust

The best grounded systems return references alongside the answer. Users can click through to the source, auditors can verify claims, and your team can spot when the model stretched beyond its evidence. Make citation display a standard part of your interface rather than an optional extra.

Advantages

  • Fewer invented facts and more traceable answers
  • Fresh information beyond the model’s training date
  • Access to private knowledge without retraining
  • Easier audits and user trust

Disadvantages / Trade-offs

  • Extra latency from retrieval or search steps
  • Answers are only as good as the sources
  • Additional cost and configuration
  • Models can still misread or over-extend sources
!
Common Misconception

Grounding does not make a system perfectly truthful. Sources can be wrong, retrieval can miss the best passage, and models can still draw poor conclusions. Grounding reduces risk, and evaluation measures what remains.

11Retrieval-Augmented Generation on the Platform

RAG is the most common way to make a general model useful on private knowledge.

The core loop

RAG works in two stages. First, retrieve: find the passages most relevant to the question. Second, generate: give those passages to the model along with the question and instruct it to answer using them. The model’s language ability does the writing, while your knowledge base supplies the facts. Updating knowledge becomes as simple as updating documents, with no retraining.

flowchart LR
  A["Company documents"] --> B["Parse and chunk"]
  B --> C["Embed and index"]
  Q["User question"] --> D["Retrieve top passages"]
  C --> D
  D --> E["Rerank and filter by access"]
  E --> F["Prompt with question and passages"]
  F --> G["Model writes grounded answer"]
  G --> H["Answer with citations"]
        
FIG 3 — The retrieval-augmented generation loop

Managed versus build-your-own

Google Cloud offers both managed and do-it-yourself paths. Managed search and RAG services handle parsing, chunking, embedding, indexing, and retrieval behind a simpler interface, which speeds up delivery. Building your own pipeline from lower-level parts, such as embedding models and a vector index, gives more control over every step. Many teams begin managed to prove value, then customize the parts that matter most.

ApproachStrengthWatch out for
Managed search and RAG servicesFast to launch, less plumbingLess control over internals
Custom pipeline with vector indexFull control over chunking, ranking, and filtersMore engineering and upkeep
Database with vector featuresKeeps data and vectors togetherScale and tuning vary by product

What decides RAG quality

Most RAG failures are retrieval failures. If the right passage never reaches the model, no prompt can rescue the answer. Quality depends on how documents are parsed, how they are chunked, how queries are interpreted, and whether results are reranked. Clean parsing of tables, headings, and lists matters more than people expect. Document processing tools, such as a layout-aware parser, produce chunks that respect sections and tables and carry heading context, which improves retrieval.

Lever

Parsing

Preserve headings, tables, and lists so meaning survives.

Lever

Chunking

Split along natural boundaries and keep enough context in each chunk.

Lever

Metadata

Attach source, date, type, and permissions for filtering and citation.

Lever

Reranking

Reorder candidates with a stronger relevance check before generation.

Lever

Prompt rules

Tell the model to answer only from the passages and to say when evidence is missing.

i
Practical Advice

Evaluate retrieval separately from generation. Check whether the correct passage appears in the top results before judging the final answer, so you know which stage to fix.

ANTI-PATTERN-02 Avoid
Problem

Splitting documents into fixed-size pieces without regard for structure.

Why It’s Harmful

Tables are cut in half, headings are separated from their text, and retrieved passages become confusing fragments.

Correct Approach

Use structure-aware parsing and chunking, include headings in each chunk, and test retrieval on real questions.

12Agents: Models That Plan and Act

An agent goes beyond answering. It decides what to do next, uses tools, and works toward a goal.

From chatbot to agent

A chatbot answers a question and stops. An agent loops: it looks at the goal, decides on a step, calls a tool, reads the result, and decides again until the goal is reached or it needs help. The 2026 evolution of the platform put agents at the center, describing tools for building agents that call interfaces, reach data sources, and run multi-step workflows, with support for several agents cooperating on one task.

Simple Analogy

A chatbot is a receptionist who answers questions from a script. An agent is a project coordinator who reads the request, books the room, emails the team, checks the budget, and reports back, asking you only when something needs approval.

The building blocks

Block 1

Instructions

The agent’s goal, rules, and style.

Block 2

Tools

Functions and services the agent may call, each with a clear description.

Block 3

Memory

Short-term conversation context and long-term facts kept across sessions.

Block 4

Planning loop

The cycle of deciding, acting, observing, and adjusting.

Block 5

Runtime

A managed place to run agents reliably, with scaling and sessions.

Block 6

Governance

Identity, approved tool lists, monitoring, and risk controls.

flowchart TD
  A["Goal from user"] --> B["Agent plans next step"]
  B --> C{"Needs a tool?"}
  C -->|Yes| D["Call approved tool"]
  D --> E["Read result"]
  E --> B
  C -->|No| F{"Needs human approval?"}
  F -->|Yes| G["Ask a person"]
  G --> B
  F -->|No| H["Final answer or action"]
        
FIG 4 — The agent loop with human approval

Single agent or many

A single agent with a handful of well-described tools handles most business tasks. Multi-agent designs divide work among specialists, for example a research agent, a drafting agent, and a review agent, coordinated by a supervisor. They add power and also add complexity, cost, and new failure modes, so introduce them only when one agent clearly struggles.

!
Common Mistake

Giving agents broad permissions and unlimited steps. Limit tools to the minimum, cap the number of steps and the spending per task, log every action, and require approval for irreversible operations.

i
Design Tip

Start with a workflow where the steps are fixed by your code and the model fills in language tasks. Move toward agent autonomy only where flexibility truly pays off.

13Prompting, RAG, or Tuning: Choosing How to Customize

Three tools change a model’s behavior, and each solves a different problem.

The decision ladder

Customization works best as a ladder. Start with better prompts and system instructions, because they are free and fast. If the model lacks knowledge, add grounding or retrieval. If it still behaves wrongly in style, format, or specialized judgement, consider tuning. Tuning is powerful, yet it requires data, time, evaluation, and maintenance, so it belongs near the top of the ladder, not the bottom.

ProblemBest first toolWhy
Wrong tone or formatPrompts, examples, system instructionsCheap and instantly testable
Missing or outdated factsGrounding or RAGKnowledge changes without retraining
Needs private data at answer timeRAG with access controlKeeps data current and permissioned
Consistent specialized behavior across many casesTuningTeaches patterns that are hard to describe
High volume where a small model must match a large oneTuning a smaller modelCan cut cost and latency
Simple Analogy

Prompting is giving an employee written instructions for today’s job. RAG is handing them the latest reference binder. Tuning is sending them on a training course so the skill becomes second nature.

Kinds of tuning

The platform documentation lists several approaches for Gemini models. Supervised tuning teaches the model from examples of inputs and desired outputs. Preference tuning uses pairs of better and worse answers to nudge behavior. Reinforcement-style tuning uses reward signals. Tuning is also described for embedding models and some other model types. Which options are available depends on the model, so check the current documentation before planning.

1

Define success

Write measurable targets and build an evaluation set before touching training.

2

Prepare examples

Collect high-quality, consistent, representative input and output pairs.

3

Train

Run a tuning job on the training data and keep a separate validation set.

4

Evaluate against baseline

Compare with the original model plus a good prompt, not with a weak prompt.

5

Deploy and monitor

Release gradually and plan to retune when base models change.

!
Common Mistake

Tuning to inject facts. Tuning shapes behavior and style, but it is a poor and expensive way to store knowledge that changes. Use retrieval for facts and tuning for habits.

ANTI-PATTERN-03 Avoid
Problem

Jumping straight to tuning because it sounds advanced.

Why It’s Harmful

Weeks are spent on data and training for a problem that a clearer prompt or retrieval would have solved in an afternoon.

Correct Approach

Climb the ladder in order: prompt, ground, then tune only when evaluation shows a gap that remains.

14Evaluation: Measuring What Matters

If you cannot measure quality, every change is a guess.

Why evaluation is hard for generative AI

Traditional software has exact answers. Generative AI produces open-ended text, so two different answers can both be correct. Evaluation therefore blends several methods. Computation-based metrics compare output to reference answers, useful for tasks with clear targets such as extraction or classification. Model-based evaluation uses a strong judge model to score answers against criteria such as helpfulness, correctness, and tone. Pairwise comparison shows two outputs to a judge and asks which is better. Human review remains the gold standard for sensitive or subjective tasks.

Method 1

Computed metrics

Compare outputs with reference answers, best for structured tasks.

Method 2

Judge models

A strong model scores answers on defined criteria at scale.

Method 3

Side-by-side comparison

Two candidates are compared directly to pick the better one.

Method 4

Human review

Experts check samples, especially for safety, nuance, and high stakes.

Method 5

Agent traces

Inspect the steps and tool calls an agent took, not only its final answer.

Simple Analogy

Evaluating a model is like grading essays. Some questions have one right answer, like a maths test. Others need a rubric and a careful reader, and for important exams, a second marker checks the first.

Build your evaluation set first

A good evaluation set contains realistic questions, including difficult and unusual ones, with expected answers or scoring criteria. Include cases where the right behavior is to refuse or to say “I do not know”. Keep the set stable so that results can be compared over time, and add new cases whenever production reveals a failure.

Offline
Test sets before release
Online
Monitor live quality signals
Human
Expert review of samples
i
Practical Advice

Calibrate judge models against human scores on a small sample. If the judge and your experts disagree often, refine the criteria before trusting automated scores at scale.

!
Common Mistake

Judging quality by trying five prompts by hand and trusting the feeling. Small samples hide failures. Use a real evaluation set and compare numbers.

15Internal Working: The Life of One Request

What happens between a user pressing send and the answer appearing.

Step by step

Behind a single question there is a chain of stages. The application authenticates the caller and checks quotas. Input safety checks examine the prompt. The orchestration layer retrieves context and assembles the final prompt. The model reads the tokens and generates the answer token by token, often streamed so users see text appear progressively. Output safety checks examine the result. Finally the response is returned, and logs and metrics are recorded.

sequenceDiagram
  participant User
  participant App as Application
  participant Guard as Safety and policy checks
  participant Know as Knowledge layer
  participant Model as Foundation model
  User->>App: Question
  App->>Guard: Check input
  Guard-->>App: Allowed
  App->>Know: Retrieve relevant context
  Know-->>App: Passages with sources
  App->>Model: Prompt with instructions and context
  Model-->>App: Streamed answer
  App->>Guard: Check output
  Guard-->>App: Allowed
  App-->>User: Answer with citations
        
FIG 5 — Lifecycle of a grounded request

Where time and money go

StageLatency impactCost impactHow to improve
RetrievalSmall to moderateSmallIndex tuning, caching popular queries
Prompt sizeGrows with input lengthGrows with input tokensSend only relevant context, use caching
Model generationLargest share, grows with output lengthGrows with output tokensChoose smaller models, limit output length, stream
Safety checksSmallSmallRun checks in parallel where possible
Tool callsDepends on tool speedDepends on toolParallelize independent calls
Simple Analogy

A request is like ordering at a restaurant. Checking your reservation, fetching ingredients from the pantry, cooking, and plating all take time. Cooking is usually the longest step, and bigger meals take longer and cost more.

Streaming for better experience

Because answers are generated gradually, streaming shows the first words quickly even when the full answer takes several seconds. Users perceive a much faster system, which is often more valuable than a small improvement in total time.

i
Design Tip

Measure time to first token separately from total time. Users judge responsiveness by the first, while batch jobs care about the second.

16Capacity, Pricing Models, and Context Caching

Choosing how you buy capacity affects reliability and cost as much as choosing the model.

Ways to consume models

The documentation describes several consumption options. Standard pay-as-you-go charges for what you use and suits unpredictable or early-stage workloads. Additional pay-as-you-go tiers, named Priority and Flex in the documentation, trade price against priority and delay. Provisioned Throughput reserves dedicated capacity for steady, high-volume, latency-sensitive workloads. Batch inference processes large sets of requests asynchronously at lower urgency, which suits overnight jobs. Open models you deploy yourself are billed through the compute you use.

OptionBest forTrade-off
Standard pay-as-you-goVariable traffic, pilotsShared capacity, quotas apply
Priority or flexible tiersBalancing urgency and priceCheck current behavior and terms
Provisioned ThroughputPredictable heavy traffic, strict latencyCommitment, paid whether used or not
Batch inferenceLarge offline jobsResults are not immediate
Self-deployed open modelControl over hosting and customizationYou manage infrastructure and scaling
Simple Analogy

Pay-as-you-go is hailing a taxi each time. Provisioned capacity is leasing a car with a driver on standby. Batch is booking a freight truck for tomorrow. Each is right for a different journey.

Context caching: do not pay twice for the same pages

Many applications send the same large material with every request, such as a long policy, a codebase, or a lengthy document. Context caching stores that repeated input so later requests can reuse it at lower cost and often lower delay. It is most valuable when a big, stable block of context is queried many times, for example a support assistant that always consults the same manual. Caching works with some tuned models as well, as documentation notes.

Document question answering

A long contract is cached once, and dozens of questions reuse it, cutting repeated input cost.

Assistant with a large instruction set

A big, stable block of rules and examples is cached so each conversation turn stays cheap.

!
Common Mistake

Reserving capacity before measuring traffic. Provisioned commitments make sense only after you know your steady baseline. Start on pay-as-you-go, measure for several weeks, and commit to the portion that is reliably used.

i
Check Current Terms

Prices, tier names, minimum sizes for caching, and expiry rules change over time. Treat the official pricing and caching pages as the final authority when you plan a budget.

17Safety and Responsible AI

A powerful model can produce harmful, biased, or misleading content unless the system around it is designed carefully.

Layers of protection

No single control makes a generative system safe. Responsible design stacks several layers. The platform provides configurable content filters that screen inputs and outputs for categories of harmful content, with adjustable sensitivity. System instructions set behavior boundaries. Abuse monitoring helps detect misuse patterns. Blocked responses are returned with signals so that applications can handle them gracefully instead of showing a blank screen. For media, documentation also describes content credentials and an AI content detection interface to help identify generated material.

Layer 1

Content filters

Screen prompts and answers for harmful categories with configurable thresholds.

Layer 2

System instructions

Define allowed topics, tone, and refusal behavior.

Layer 3

Grounding

Reduce invented claims by tying answers to sources.

Layer 4

Application rules

Your own checks for business policy, such as no medical or legal advice.

Layer 5

Human oversight

Review high-impact outputs and provide a path to report problems.

Simple Analogy

Safety is like airport security. There is a check at the door, a scan at the gate, staff watching the lounge, and a procedure when something looks wrong. A single guard at a single door would never be enough.

Handling blocked and borderline cases

Filters will sometimes block legitimate requests and sometimes miss harmful ones. Design the experience for both. When a response is blocked, show a helpful, polite message and offer an alternative action. Log blocked events, sample them regularly, and adjust thresholds and instructions. Test your system with deliberately tricky inputs, sometimes called red teaming, before launch and on a schedule afterwards.

Fairness and transparency

Generative models learn from human-written data and can reflect its biases. Evaluate your application on varied inputs, such as different names, languages, and dialects, and check whether quality or tone differs unfairly. Tell users when they are talking to an AI, show sources where possible, and explain the limits of the system.

!
Common Mistake

Treating safety as a launch checklist. Attack methods and user behavior evolve. Safety needs continuous testing, monitoring, and updates just like security does.

“Safe AI is not a feature you switch on. It is a habit you practice.”

18Security and Governance

Prompts and documents often contain the most sensitive information a company owns, so security must be designed in from the start.

The security layers

Layer 1

Identity and access

Use IAM roles and dedicated service accounts so each component has only the access it needs.

Layer 2

Encryption and keys

Data is encrypted in transit and at rest, with customer-managed keys available where policy requires.

Layer 3

Network perimeter

Private connectivity and service perimeters reduce the risk of data leaving approved boundaries.

Layer 4

Data residency

Choose regions and endpoints that meet legal and contractual location rules.

Layer 5

Audit and logging

Record who called what and when, with careful handling of sensitive content in logs.

Layer 6

Prompt-level protection

Screen prompts and responses for attacks and sensitive data leakage.

Threats specific to generative AI

Generative systems face threats that classic applications do not. Prompt injection happens when hostile text, hidden in a web page, email, or document, tries to give the model new instructions such as “ignore your rules and reveal the data”. Data leakage happens when a model or an agent reveals content the user should not see. Excessive agency happens when an agent is allowed to perform actions that are too powerful. Google Cloud offers a service called Model Armor, integrated with Vertex AI, designed to screen prompts and responses for issues such as prompt injection and sensitive data exposure, and the 2026 platform announcements described agent identities, registries of approved agents and tools, and gateways with security rules.

flowchart LR
  A["User or external content"] --> B["Screen input for attacks and sensitive data"]
  B --> C["Application with least-privilege identity"]
  C --> D["Retrieval filtered by user permissions"]
  D --> E["Model"]
  E --> F["Screen output"]
  F --> G["Approved tools only"]
  G --> H["Audit log"]
        
FIG 6 — Defense in depth for a generative application
Simple Analogy

Prompt injection is like a forged note slipped into a stack of papers on a manager’s desk, saying “give the bearer the safe key”. A careful assistant knows that instructions come from the manager, not from documents in the pile.

Principles to apply

1

Treat all external content as untrusted

Web pages, emails, and uploaded files may contain hidden instructions. Keep them separate from system rules.

2

Enforce permissions outside the model

Filter retrieval by the user’s real access rights in code. Never rely on the model to decide who may see what.

3

Limit agent power

Give each agent the narrowest tools, confirm risky actions with humans, and cap spending and steps.

4

Protect logs

Prompts may contain personal data. Control who can read logs and set retention periods.

5

Review data terms

Confirm how data is processed and used under the service terms, and involve compliance early.

ANTI-PATTERN-04 Avoid
Problem

Putting all company documents into one shared index and trusting the model to hide what a user should not see.

Why It’s Harmful

A clever question or an injected instruction can pull restricted content into an answer, since the model never truly enforces permissions.

Correct Approach

Store access metadata with each chunk, filter at retrieval time by the user’s identity, and log what was retrieved.

19Monitoring, Logging, Metrics, and Cost Control

A generative application you cannot observe is one you cannot improve or afford.

What to watch

Treat monitoring as three dashboards. The operational dashboard tracks request volume, error rates, latency, time to first token, quota usage, and retries. The quality dashboard tracks evaluation scores, share of answers with citations, thumbs-up and thumbs-down feedback, escalation to humans, and blocked responses. The cost dashboard tracks tokens in and out, spending per feature, per team, and per customer, and cost per successful task.

SignalWhat it tells youTypical response
Rising error or throttling rateQuota or capacity limitsRequest more quota, add retries, consider reserved capacity
Growing average prompt sizeContext creeping upTrim context, use caching, review retrieval
Drop in feedback scoresQuality regression or new question typesSample failures, update prompts, extend evaluation set
More blocked responsesMisuse or over-strict filtersReview samples, adjust thresholds and instructions
Cost per task risingLonger outputs or retriesLimit output, reduce retries, choose a smaller model for easy steps
Simple Analogy

Running a generative app without monitoring is like driving at night without a dashboard. You may be fine for a while, but you will not see the fuel running out or the engine overheating until it is too late.

Practical ways to reduce cost

1

Right-size the model

Use lighter models for simple steps like classification and routing, and larger ones only where needed.

2

Shorten prompts and outputs

Send only relevant context and set sensible output limits.

3

Cache and reuse

Use context caching for repeated large inputs, and cache answers to frequent identical questions where safe.

4

Batch the non-urgent

Send overnight or bulk jobs through batch inference.

5

Set budgets and alerts

Create billing alerts and per-project limits so a runaway loop cannot surprise finance.

!
Common Mistake

Logging full prompts and answers forever. They may contain personal or confidential data. Log what you need for debugging and evaluation, mask sensitive values, and delete on a schedule.

i
Practical Advice

Track cost per successful outcome, such as per resolved support case, rather than only cost per call. It connects spending to business value and reveals when a cheaper design is actually more expensive overall because of retries and failures.

20Design Patterns That Work

Proven shapes keep generative systems understandable, testable, and affordable.

Grounded answer with citations

Retrieve evidence, answer only from it, show references, and say “I could not find this” when evidence is missing.

Router and specialists

A small, fast model classifies each request and sends it to the right prompt, tool, or larger model, keeping cost low and quality high.

Draft, critique, revise

One call writes a draft, a second checks it against rules or sources, and a third fixes problems, improving reliability on important outputs.

Structured extraction pipeline

Messy text or documents are converted into validated records through structured output, then checked by business rules before being saved.

Human in the loop for high impact

Low-risk answers go straight out, while high-risk ones wait for approval, with feedback captured for improvement.

Fallback chain

If the primary model is slow or unavailable, a secondary model or a graceful message takes over so users are never left staring at an error.

Evaluation gate in delivery

Every prompt, model, or retrieval change must pass the evaluation set before release, just like automated tests for code.

flowchart TD
  A["Incoming request"] --> B["Small model: classify intent"]
  B -->|FAQ| C["Grounded answer with retrieval"]
  B -->|Account action| D["Agent with approved tools"]
  B -->|Sensitive or unclear| E["Human agent queue"]
  B -->|Creative or complex| F["Larger model with extended context"]
  C --> G["Safety check and response"]
  D --> G
  F --> G
        
FIG 7 — Router pattern sending work to the right path
Simple Analogy

The router pattern is a hospital triage desk. A quick check decides whether you go to the pharmacy, a nurse, or a specialist, so scarce expert time is spent where it matters.

i
Practical Advice

Combine only as many patterns as the problem needs. Each added step adds latency, cost, and a new place for errors, so prefer the simplest design that meets your quality target.

21Anti-Patterns to Avoid

These tempting shortcuts cause the most pain in real projects.

ANTI-PATTERN-05 Avoid
Problem

Shipping on the strength of a few impressive demo conversations.

Why It’s Harmful

Rare failures, edge cases, and unusual users appear only at scale, and without measurements nobody knows how bad things are.

Correct Approach

Build an evaluation set from real examples before launch, set quality thresholds, and monitor live signals afterwards.

ANTI-PATTERN-06 Avoid
Problem

Hard-coding one model name and version throughout the application.

Why It’s Harmful

When the model is retired or replaced, every call site needs changes, and comparing alternatives becomes painful.

Correct Approach

Keep model identifiers in configuration behind a thin internal interface, and rehearse switching models on the evaluation set.

ANTI-PATTERN-07 Avoid
Problem

Letting an agent take irreversible actions, such as sending money or deleting records, without a human check.

Why It’s Harmful

One misunderstanding or one injected instruction can cause real damage that cannot be undone.

Correct Approach

Require approval for high-impact actions, restrict tools to the minimum, and log every step for review.

ANTI-PATTERN-08 Avoid
Problem

Stuffing the whole knowledge base into every prompt instead of retrieving what is relevant.

Why It’s Harmful

Costs and delays balloon, important details get lost among irrelevant text, and access control becomes impossible.

Correct Approach

Retrieve a small set of relevant, permitted passages, and use caching only for genuinely repeated stable context.

ANTI-PATTERN-09 Avoid
Problem

Treating model output as a trusted fact and writing it straight into a system of record.

Why It’s Harmful

Occasional plausible but wrong values slip into financial, medical, or legal records and may remain hidden for months.

Correct Approach

Validate against rules and sources, use confidence or check steps, and send uncertain cases to a person.

!
Pattern Behind the Patterns

Nearly every anti-pattern comes from trusting the model more than its measured performance justifies. Replace trust with evidence: evaluation, validation, permissions enforced in code, and human checks where stakes are high.

22Best Practices and Common Mistakes

A checklist distilled from the earlier chapters, written as habits.

Best Practices

  • Define the user problem and a measurable success target before choosing technology
  • Build an evaluation set from real examples and keep it stable
  • Climb the ladder: prompt, then ground, then tune
  • Show sources and let users give feedback
  • Enforce permissions in code, not in prompts
  • Use the smallest model that meets the quality bar
  • Keep model names and prompts in versioned configuration
  • Monitor quality, cost, and safety signals together
  • Plan for model retirement and SDK changes from day one

Common Mistakes

  • Choosing the largest model for every task
  • Skipping grounding for questions about facts
  • Tuning to store changing knowledge
  • Ignoring prompt injection from documents and web content
  • Logging sensitive prompts without controls
  • Committing to reserved capacity before measuring usage
  • Launching without a human fallback path
  • Never re-running evaluations after model updates
  • Giving agents wide permissions and unlimited steps

Choosing the right approach quickly

Your goalStart withRemember
Write, summarize, or transform textPrompted model with clear formatTest several models on your examples
Answer questions on company documentsRAG with citationsEvaluate retrieval separately
Answer about recent public factsGrounding with searchShow sources
Get machine-readable outputStructured outputValidate with business rules
Let AI use business systemsFunction calling or an agentLeast privilege and approvals
Consistent specialized behaviorTuning after prompts and RAGCompare with a strong prompted baseline
Understand images, audio, videoMultimodal modelMind input size and cost
Heavy steady trafficProvisioned capacityMeasure before committing
“Measure first, customize second, and keep a human path for the uncertain cases.”

23Reference Architectures

Three blueprints cover a large share of real projects.

Blueprint 1: the enterprise knowledge assistant

Employees ask natural questions about policies, products, and procedures. Documents flow through parsing, chunking, and embedding into a permission-aware index. Each question retrieves relevant passages filtered by the user’s access, which the model uses to answer with citations. A feedback button feeds an evaluation set, and unanswered questions highlight gaps in documentation.

flowchart LR
  A["Policy and product documents"] --> B["Structure-aware parsing"]
  B --> C["Chunks with metadata and permissions"]
  C --> D["Embedding and index"]
  U["Employee question"] --> E["Identity check"]
  E --> F["Filtered retrieval"]
  D --> F
  F --> G["Model answers using passages"]
  G --> H["Answer with citations"]
  H --> I["Feedback into evaluation set"]
        
FIG 8 — Enterprise knowledge assistant

Blueprint 2: the customer service agent

A virtual agent greets customers, classifies intent, answers common questions from grounded knowledge, and uses tools to check orders or update details. Sensitive or angry conversations route to human staff with a generated summary so the customer never repeats the story. Safety filters run on every turn, and all actions are logged.

Blueprint 3: the document and media processing pipeline

Files land in storage, a document processor extracts text and structure, a model summarizes or classifies, structured output produces validated records, and results flow into a data warehouse. Low-confidence or rule-breaking cases go to a review queue. Batch inference handles large backlogs at lower urgency.

flowchart TD
  A["Files arrive in storage"] --> B["Document and media processing"]
  B --> C["Model: classify and summarize"]
  C --> D["Structured output"]
  D --> E{"Passes validation?"}
  E -->|Yes| F["Data warehouse"]
  E -->|No| G["Human review queue"]
  G --> F
  F --> H["Analytics and search"]
        
FIG 9 — Document and media processing pipeline
BlueprintCore servicesKey risk to manage
Knowledge assistantRetrieval, embeddings, model, identityLeaking restricted content
Customer service agentModel, tools, safety filters, human handoffWrong actions and harmful replies
Processing pipelineStorage, document processing, model, warehouseWrong values entering records
i
Design Tip

Use the same evaluation, safety, and logging foundations across all your blueprints. Shared building blocks make every later project faster and safer.

24Real-World and Industry Examples

The same building blocks, arranged differently for different industries.

Retail: shopping assistants and product content

Assistants answer product questions grounded in catalogue data, while generation models draft descriptions and imagery for thousands of items, reviewed by merchandisers before publishing.

Banking: advisor support and document review

Staff query policy libraries with citations, and models summarize long reports and extract fields from forms, with strict access control and human sign-off on decisions.

Healthcare: documentation and patient communication

Models draft visit summaries and plain-language instructions for clinician review, under tight privacy, residency, and oversight requirements.

Telecom and utilities: contact centers

Agents summarize calls, suggest answers during live chats, and automate routine requests, handing complex cases to humans with full context.

Software teams: coding and operations help

Developers use assistants for code explanation, test drafting, and incident summaries, with evaluation and review preventing silent mistakes from reaching production.

Media and marketing: creative production

Image, video, and music models speed up concept drafts, with brand guidelines in prompts, content credentials, and human editorial control.

Public sector and education: access to information

Multilingual assistants help citizens and students find answers in official documents, with citations and clear statements of limits.

i
Pattern Spotting

Every example uses retrieval or tools for facts, the model for language, validation for safety, and humans for the decisions that matter. Only the sources and the rules change.

25Model Lifecycle, Renames, and Migration

In generative AI, change is the normal state. Plan for it from the first day.

Models come and go

Foundation models are released, improved, and eventually retired on a published schedule. Third-party guides to the 2026 platform changes report that some older Gemini models and several preview and open-model endpoints were discontinued during the year. Whether or not a specific model on your list is affected, the lesson is the same: any application built on a named model version must expect that version to disappear and must be ready to move to a successor.

Simple Analogy

Model versions are like phone models. The one you bought is excellent today, but the manufacturer will stop supporting it at some point. Teams that plan upgrades enjoy the new features, while teams that ignore the notices face a sudden emergency.

Naming and SDK changes

The April 2026 move from Vertex AI toward the Gemini Enterprise Agent Platform brought renamed products and changes to developer tooling. A third-party migration guide reports that the underlying service name used by API calls was unchanged and that existing models, endpoints, pipelines, and agents kept working, while a major Python SDK release moved generative AI modules to the Google Gen AI SDK and moved agent features into a separate package, which is a breaking change. These details come from secondary sources, so verify them in the official release notes before acting.

Change typeTypical impactProtective habit
Product renamesConfusing documentation and console labelsMaintain an internal glossary mapping old and new names
Model retirementCalls fail or are redirected after the deadlineTrack retirement dates and migrate early
SDK major versionsCode changes needed, sometimes breakingPin versions and test upgrades in staging
New default behaviorsOutput style or quality shiftsRe-run the evaluation set on every change
Newly required APIsFirst-use prompts to enable additional servicesReview project settings during rollout

A safe migration routine

1

Watch announcements

Subscribe to release notes and review deprecation pages every month.

2

Test the successor

Run the frozen evaluation set against the new model and compare scores field by field or task by task.

3

Adjust prompts

Newer models may respond differently to the same wording, so refine instructions and examples.

4

Canary release

Send a small share of traffic to the new model and compare live quality, latency, and cost.

5

Promote and retire

Move all traffic, keep a quick rollback until you are confident, then remove the old setting.

!
Common Mistake

Forgetting that tuned models depend on a base model. When the base is retired, you will need to retune on a newer base, so keep your training data and evaluation set safe and reusable.

26Scaling and Reliability

An application that works for ten users must also work for ten thousand, including on its worst day.

Quotas and throttling

Every model has limits on requests and tokens per minute for your project and region. When demand exceeds those limits, requests are throttled and return errors that tell you to slow down. Plan ahead by estimating peak traffic, requesting quota increases in advance, and deciding whether reserved capacity is justified for steady heavy use.

Handling failure gracefully

FailureExampleRight response
ThrottlingToo many requests per minuteRetry with growing delays and add queueing
Timeout or transient errorSlow or briefly unavailable serviceRetry a limited number of times, then use a fallback
Blocked responseSafety filter triggeredShow a polite message and offer alternatives
Malformed outputAnswer not in the required shapeUse structured output, validate, and retry once with a correction note
Retrieval returned nothing usefulNo relevant passage foundSay so honestly and offer to escalate to a person
Tool failureBusiness system is downReport the problem and avoid inventing results
flowchart TD
  A["Request"] --> B["Primary model"]
  B -->|Success| C["Validate output"]
  B -->|Throttled or error| D["Retry with delay"]
  D -->|Still failing| E["Fallback model or cached answer"]
  E -->|Unavailable| F["Friendly message and human option"]
  C -->|Valid| G["Return answer"]
  C -->|Invalid| H["Retry once with correction"]
  H --> C
        
FIG 10 — Graceful degradation path
Simple Analogy

Reliability planning is like preparing for a power cut in a hospital. There is a generator, a backup procedure, and a clear message for patients, so critical care continues even when the main supply fails.

Regional choices and resilience

Model availability varies by region, and strict residency rules may restrict your choices. For high-availability needs, design for a second permitted region or a fallback model, and rehearse the failover rather than assuming it works. Keep prompts, evaluation sets, and configuration in version control so that a new environment can be rebuilt quickly.

i
Operational Tip

Load test with realistic prompts, including long ones, before launch. Measure latency distributions, throttling thresholds, and cost per thousand requests, and use the results to set alerts and budgets.

!
Common Mistake

Retrying instantly and endlessly when throttled. Hammering a limited service makes matters worse and multiplies cost. Use growing delays, limits on attempts, and a fallback.

27Troubleshooting Guide

When answers disappoint, an ordered investigation beats guessing.

Find which stage failed

Most problems come from one of four places: the prompt, the retrieved context, the model choice or settings, and the surrounding code. A simple method is to inspect the exact final prompt that the model received, including retrieved passages and instructions, then ask whether a thoughtful human could have given the right answer from that material alone. If not, the failure lies upstream of the model.

SymptomLikely causeFirst thing to try
Confident but wrong factsNo grounding or weak retrievalAdd grounding, instruct the model to answer only from sources, and check retrieval results
Answer ignores part of the questionPrompt unclear or too longSimplify instructions, separate tasks, add an example
Inconsistent output formatFormat not enforcedUse structured output and lower temperature
Correct passage exists but is not usedRetrieval missed it or chunking is poorImprove parsing and chunking, add keyword search, rerank
Slow responsesLarge prompts or long outputsTrim context, cap output length, stream, consider a lighter model
Bills higher than expectedContext growth, retries, or oversized modelReview token metrics, add caching, right-size model
Quality dropped after an updateModel or prompt behavior changedRe-run the evaluation set and compare with the previous version
Agent loops or wandersVague goal or unclear tool descriptionsTighten instructions, improve tool descriptions, cap steps
Legitimate requests blockedFilter thresholds too strictReview blocked samples and adjust settings carefully
Permission errors on callsMissing roles or perimeter rulesCheck service account roles and project settings
Simple Analogy

Debugging a generative answer is like checking why a student failed a question. Did they get the wrong textbook, misread the question, or truly not understand? Looking at what they were given tells you where to fix things.

A calm debugging routine

1

Capture the exact request

Record the final prompt, settings, model version, and retrieved context for a failing case.

2

Judge the inputs

Ask whether the material given to the model contained what was needed.

3

Find the pattern

Collect several similar failures and look for shared features before changing anything.

4

Change one thing

Adjust the prompt, retrieval, or model, then re-run the evaluation set to confirm improvement without regressions.

!
Common Mistake

Changing prompt, model, and retrieval settings all at once. Nobody then knows which change helped or hurt. Change one variable at a time and record results.

28Adoption Roadmap and Team Roles

Technology succeeds when the organization around it is ready.

A phased rollout

Organizations that try to transform everything at once usually end up with scattered pilots and no production value. A safer path starts with one valuable, well-bounded use case, proves it with measurements, and then reuses the same foundations for the next. Early wins build trust and teach the team where the real difficulties lie.

1

Discover

Pick a use case with clear users, measurable value, available data, and manageable risk. Record today’s baseline for time, cost, or quality.

2

Prototype

Test candidate models and prompts in the studio, using real examples rather than invented ones.

3

Evaluate and harden

Build the evaluation set, add grounding, safety, and security controls, and set quality thresholds.

4

Pilot

Release to a small group with human fallback and rich feedback capture.

5

Scale and govern

Expand access, monitor quality and cost, manage model lifecycle, and extend to new use cases through shared platforms.

Who does what

Role

Business owner

Defines the problem, success measures, and acceptable risk.

Role

Solution architect

Designs the application, data flows, security boundaries, and failure handling.

Role

AI engineer

Builds prompts, retrieval, tools, and evaluations.

Role

Platform engineer

Handles deployment, capacity, monitoring, and cost controls.

Role

Domain experts

Write and review evaluation cases and judge quality in their field.

Role

Security, legal, and compliance

Approve data handling, residency, retention, and responsible-use policies.

Simple Analogy

Adopting generative AI is like opening a new restaurant branch. You perfect one kitchen first, write down the recipes and hygiene rules, train the staff, and only then open the next location with the same playbook.

!
Common Mistake

Letting domain experts stay out of the process. They know what a good answer looks like. Without their examples and reviews, evaluation measures the wrong things and the product disappoints real users.

“Successful AI projects are mostly about data, evaluation, and people, with the model as one ingredient.”

29Glossary and Quick Reference

A compact reference of terms used throughout this tutorial.

Term

Agent

A system where a model plans, calls tools, and works toward a goal with some independence.

Term

Batch inference

Processing many requests asynchronously, usually at lower urgency and cost.

Term

Chunk

A meaningful piece of a document prepared for retrieval.

Term

Context caching

Storing repeated large input so later requests reuse it more cheaply.

Term

Context window

The maximum input plus output a model handles in one request.

Term

Embedding

A numeric representation of meaning used for similarity search.

Term

Evaluation set

A stable collection of test cases used to score quality over time.

Term

Few-shot

Guiding a model with a small number of examples in the prompt.

Term

Foundation model

A broadly trained model usable for many tasks.

Term

Function calling

A way for a model to request that your code run a described tool.

Term

Grounding

Tying answers to verifiable sources.

Term

Hallucination

A confident answer not supported by facts or provided sources.

Term

Judge model

A model used to score other models’ answers against criteria.

Term

Model Garden

The catalogue for browsing and using Google, open, and partner models.

Term

Multimodal

Able to handle text, images, audio, and video.

Term

Prompt injection

Hostile text trying to override a model’s instructions.

Term

Provisioned Throughput

Reserved model capacity for steady, high-volume, latency-sensitive use.

Term

RAG

Retrieving relevant material first, then generating an answer from it.

Term

System instruction

Standing rules that apply across a whole conversation.

Term

Temperature

A setting controlling randomness and variety in answers.

Term

Token

A small unit of text or media used for limits and pricing.

Term

Tuning

Adjusting a model with your own examples to change its behavior.

One-page decision summary

NeedUseRemember
Pick a modelModel Garden and a trial on your examplesSmallest model that meets the bar
Trustworthy answersGrounding and RAG with citationsEvaluate retrieval separately
Predictable outputStructured output and validationBusiness rules still apply
Actions in business systemsFunction calling or agentsLeast privilege and approvals
Specialized behaviorTuning after prompts and RAGCompare against a strong baseline
Quality assuranceEvaluation set, judge models, humansRe-run after every change
Safe operationFilters, security layers, monitoringEnforce permissions in code
Cost and capacityRight-sizing, caching, batch, reserved capacityMeasure before committing
i
Stay Current

This platform changes quickly. Model lists, product names, prices, quotas, and features move often, so treat the official documentation, release notes, and pricing pages as the final authority when making decisions.

30Frequently Asked Questions

Short answers to the questions beginners and architects ask most often.

Q1Is Vertex AI the same as Gemini?

No. Gemini is a family of models. Vertex AI is the platform that provides access to Gemini and many other models, along with tools for prompting, grounding, tuning, evaluation, security, and deployment.

Q2Did Vertex AI get renamed?

In April 2026 Google announced the Gemini Enterprise Agent Platform as an evolution of Vertex AI, with several products renamed. Secondary sources report that the core API service name and existing resources continued to work. Confirm specifics in current official documentation.

Q3Do I need to train my own model?

Almost never at the start. Use a foundation model with good prompts and grounding first. Consider tuning only when evaluation shows a persistent gap that those steps cannot close.

Q4What is the difference between RAG and tuning?

RAG supplies facts at question time from your documents, so knowledge stays current. Tuning changes the model’s behavior and style using examples. Use RAG for knowledge and tuning for habits.

Q5How do I reduce hallucinations?

Ground answers in sources, instruct the model to answer only from them and to admit uncertainty, show citations, validate outputs with rules, and measure with an evaluation set. Hallucinations can be reduced but not eliminated.

Q6Can the model see my private data?

Only what your application sends it. Retrieval should filter by the user’s permissions in code. Review the service’s data terms and your own policies, choose appropriate regions, and control logging.

Q7When should I use an agent instead of a simple workflow?

Use a workflow when steps are known in advance. Use an agent when the path depends on intermediate results and flexibility is valuable. Agents add cost and risk, so give them narrow tools and approval checkpoints.

Q8How do I choose between pay-as-you-go and reserved capacity?

Begin with pay-as-you-go while usage is uncertain. Move the steady, predictable part of heavy traffic to reserved capacity once you have weeks of measurements and need consistent latency.

Q9What happens when a model is retired?

Calls to the retired version eventually fail or are redirected. Keep model names in configuration, track retirement dates, test successors on your evaluation set, and retune any tuned models on a newer base.

Q10How do I keep costs predictable?

Right-size models, trim prompts, cap outputs, use context caching and batch inference, set budgets and alerts, and track cost per successful outcome rather than only per call.

Q11How do I protect against prompt injection?

Treat external content as untrusted, screen inputs and outputs, enforce permissions outside the model, limit tool power, require approvals for risky actions, and test with adversarial examples regularly.

Q12Can I use models from other providers on the same platform?

The model catalogue includes open and partner models alongside Google’s. Availability, features, regions, and terms differ by model, so check the catalogue entry before planning around one.

31Creating Images, Video, Music, and Speech

Generative AI is not only about text. The platform also offers models that create media.

The media families

The platform documentation lists models for several creative outputs. Image models create and edit pictures from descriptions, and some are part of the Gemini family so that they can follow detailed instructions and combine pictures with text. Video models create short clips from prompts, and the documentation names a Veo family for this purpose. Music models, including a Lyria family, compose audio. Speech models convert text to natural voices and transcribe spoken audio, and translation models handle language conversion. Each family has its own strengths, limits, and usage rules.

Media

Images

Marketing visuals, product mockups, concept art, and edits guided by text instructions.

Media

Video

Short clips for storyboards, social content, and training material drafts.

Media

Music

Background tracks and sound ideas for videos, games, and presentations.

Media

Speech

Voice output for assistants and accessibility, and transcription of meetings and calls.

Media

Translation

Language conversion for support content, documents, and live conversations.

Simple Analogy

A media model is like a creative studio that works at the speed of a thought. You describe the idea, and it produces a first draft within moments. The art director, which is your team, still decides what is good enough to publish.

Prompting for media

Good media prompts describe the subject, the setting, the style, the mood, the composition, and any constraints, such as colors or aspect ratio. Be specific and concrete. Instead of “a nice office”, describe the light, the furniture, the time of day, and the camera angle. Generate several variations, pick the best, and refine with edits rather than starting from nothing every time.

Responsible media creation

Generated media raises special questions. Check that outputs do not copy protected characters, brands, or styles. Avoid realistic depictions of real people without clear rights and consent. Label AI-generated material honestly. The documentation describes content credentials and an AI content detection interface to help signal and identify generated content, and your own policy should say when and how those tools are used.

!
Common Mistake

Publishing generated media straight from the model. Always include a human review step for brand fit, accuracy, taste, and legal risk, especially for anything customer-facing.

Marketing variations at scale

A team generates dozens of image concepts for a campaign, picks a handful, and has designers polish them, cutting early-stage creative time dramatically.

Training and explainer clips

Short video drafts illustrate procedures, with subject experts reviewing every clip for accuracy before release.

i
Practical Advice

Media generation is usually more expensive and slower than text. Use batch workflows for large jobs, set budgets, and keep a library of approved prompts so teams reuse what works.

32Real-Time and Conversational Experiences

Some applications must listen, think, and answer while a person is still talking.

Why live is different

Typing a question and waiting two seconds feels fine. Speaking to a voice assistant and waiting two seconds feels awkward. Real-time experiences demand low delay, the ability to handle interruptions, and continuous streams of audio and sometimes video. The documentation describes live variants of Gemini models and a Live interface designed for these conversations, including support from the agent development kit.

Simple Analogy

A text chat is exchanging letters. A live conversation is a phone call. In a phone call, long silences are rude, interruptions are normal, and tone of voice carries meaning, so the system must be built differently.

Design considerations for live systems

1

Minimize delay

Stream audio in and out, keep prompts short, and avoid slow tool calls in the middle of speech.

2

Handle interruptions

Let users cut in naturally, stop speaking when interrupted, and resume gracefully.

3

Confirm important details

Read back names, numbers, and addresses, because speech recognition can mishear them.

4

Offer a human exit

Make it easy to reach a person when the assistant struggles or the matter is sensitive.

5

Respect privacy

Tell callers that AI is involved, obtain consent for recording where required, and limit retention.

sequenceDiagram
  participant Caller
  participant Live as Live model session
  participant Tool as Business tool
  Caller->>Live: Speaks a request
  Live-->>Caller: Short acknowledgement while thinking
  Live->>Tool: Look up account details
  Tool-->>Live: Account information
  Live-->>Caller: Spoken answer
  Caller->>Live: Interrupts with a correction
  Live-->>Caller: Adjusts and continues
        
FIG 11 — A real-time voice conversation with a tool call

Advantages

  • Natural, hands-free interaction
  • Helpful for accessibility and mobile use
  • Can understand tone, pauses, and spoken context
  • Reduces wait times in contact centers

Disadvantages / Trade-offs

  • Strict delay requirements and harder testing
  • Speech recognition errors on noisy lines and accents
  • Higher privacy and consent obligations
  • Costs can add up with long sessions
!
Common Mistake

Testing a voice assistant only with clean, scripted recordings. Test with accents, background noise, interruptions, and hesitations. Real callers are rarely tidy.

33A Library of Reliable Prompt Patterns

A handful of reusable prompt shapes solve a large share of everyday tasks.

Patterns worth keeping on file

PatternUse it whenKey idea
Role and audienceTone and level of detail matterState who is speaking and who is listening
Extract to a schemaYou need records from messy textName each field, its type, and what to do when it is missing
Classify with definitionsRouting or labelingGive each category a short definition and one example, plus an “other” option
Answer only from sourcesGrounded question answeringInstruct the model to use the supplied passages and say when they are insufficient
Compare and decideChoosing between optionsList criteria first, score each option, then recommend with reasons
Draft, critique, reviseHigh-quality writingSeparate creating from checking, with explicit rules for the check
Step-by-step reasoningLogic and calculationAsk for intermediate steps, then verify the final result independently
Refuse and redirectOut-of-scope or risky requestsDescribe what is out of scope and what polite alternative to offer
Simple Analogy

Prompt patterns are like cooking techniques. Once you know how to sauté, roast, and braise, you can cook thousands of dishes by changing the ingredients. You do not need a new technique for every meal.

Habits that improve almost any prompt

Habit 1

Be specific

Replace vague words with concrete limits, audiences, and formats.

Habit 2

Separate instructions from data

Use clear labels or delimiters so the model does not mistake content for commands.

Habit 3

Show what good looks like

Add one or two examples that include tricky cases.

Habit 4

Allow “I do not know”

Give the model a safe way to decline instead of guessing.

Habit 5

Test on a set

Judge any new prompt on many examples, never on a single lucky try.

i
Practical Advice

Keep a shared library of approved prompts with owners, version numbers, and evaluation scores. It turns scattered personal tricks into a team asset and prevents everyone from reinventing the same wheel.

!
Common Mistake

Piling on rules until the prompt becomes a wall of text. Contradicting or excessive instructions confuse models. Prefer a short, clear prompt with a couple of strong examples, and add rules only when evaluation shows a specific failure.

34Summary and Key Takeaways

Generative AI on Vertex AI gives teams a single place to choose models, design prompts, ground answers in trustworthy sources, build agents, tune when truly needed, evaluate objectively, protect users and data, and run applications at scale with predictable cost. Its real value comes not from any one model but from the disciplined system around it: retrieval that finds the right facts, safety and security layers that hold under pressure, evaluation that turns opinions into numbers, and operations that survive growth and change. Teams that treat generative AI as an engineering discipline, with measurement, governance, and planned upgrades, build products that last beyond the demo.

Key Takeaways

  • Platform over model — The model is one ingredient. Grounding, safety, security, evaluation, and operations make a product dependable.
  • Climb the customization ladder — Improve prompts first, add grounding or retrieval for knowledge, and tune only when evaluation shows a remaining gap.
  • Ground and cite — Tie answers to sources, show citations, and instruct the model to admit when evidence is missing.
  • Enforce rules in code — Permissions, tool limits, and approvals belong in your application, not in a prompt the model might ignore.
  • Measure everything — Build an evaluation set from real examples, re-run it on every change, and monitor quality, safety, latency, and cost together.
  • Right-size and reuse — Use the smallest model that meets the bar, cache repeated context, batch non-urgent work, and reserve capacity only after measuring.
  • Expect change — Models retire, products are renamed, and SDKs evolve, so keep configuration flexible and confirm details in official documentation.