Generative AI on Vertex AI in Google Cloud
A friendly, complete guide to building with large AI models on Google Cloud: how the models work, how to talk to them, how to connect them to your own data and tools, and how to keep them safe, accurate and affordable in production.
A few years ago, a computer program could add numbers, sort lists and search databases, but it could not write a friendly email, summarize a forty-page report, describe a photograph or explain a piece of code in plain words. Today, it can do all of these. The change came from generative AI: computer models that produce new text, images, audio, video and code in response to instructions written in ordinary language.
Using such a model in a real business is more than typing a question into a chat box. You need to connect it to your data, make it follow your rules, keep it from saying harmful things, measure whether it is right, control the bill and protect private information. Vertex AI is Google Cloud’s platform for doing all of this. This guide explains Generative AI on Vertex AI from zero. Every new word is explained when it first appears, so you can follow along even if you have never built an AI application.
WWhat Is Generative AI on Vertex AI?
Start with the big picture: what generative AI is and what Google’s platform gives you.
Artificial intelligence (AI) is the field of making computers do tasks that normally need human thinking. Machine learning is the part of AI where computers learn patterns from examples instead of following hand-written rules. Generative AI is the part of machine learning where the computer does not just sort or label things, it creates new content: sentences, pictures, speech, video clips or program code.
The engines behind generative AI are called foundation models. A foundation model is a very large model trained on enormous amounts of data, so it learns general skills such as language, reasoning and image understanding. A large language model, or LLM, is a foundation model that works mainly with text. Many modern models are multimodal, which means they can understand and produce more than one kind of content, such as text, images, audio, video and documents.
Vertex AI is Google Cloud’s unified, managed platform for building and running AI. “Managed” means Google operates the machines, scaling and updates. Generative AI on Vertex AI is the part of the platform that gives you access to foundation models and the tools around them. You can call Google’s Gemini models, image and video models, embedding models, and also a catalog of partner and open models, all inside your own Google Cloud project, with Google Cloud’s identity, security, networking and billing.
Think of a huge, very well-read assistant who has read a large part of the world’s libraries but has never met your company. Vertex AI is the office building that gives this assistant a desk, a phone line, a security badge, a filing cabinet with your documents, supervisors who check the assistant’s work and a monthly invoice. The assistant is clever, but the building is what makes the assistant safe and useful at work.
What you can build
- Chat and question answering over your own company documents.
- Summaries and drafts of emails, reports, meeting notes and product descriptions.
- Data extraction from text, images and documents into neat structured fields.
- Code help such as explaining, writing and reviewing programs.
- Image and video creation for marketing and design ideas.
- Agents, which are programs that plan steps, use tools and complete tasks for you.
- Search by meaning, using embeddings to find related content.
Generative AI changes faster than almost any other technology. Model names, versions, limits and prices change often. Always confirm the current model list, features and rules in Google’s official documentation before you design a system around this guide.
TThe Problem Generative AI on Vertex AI Solves
Every good tool begins with a pain. Here are the pains of building with AI models on your own.
Pain 1: Training a large model is out of reach
Building a foundation model from scratch needs vast amounts of data, thousands of specialized chips and teams of researchers, costing a fortune. Almost no company can or should do this. Renting access to a ready-made model through an API is far more practical.
Pain 2: Hosting models is hard
Even when you have a model, running it quickly and reliably for many users takes special hardware, careful engineering and constant tuning. A managed platform hides all of that and lets you pay for what you use.
Pain 3: Models do not know your business
A foundation model knows a great deal about the general world, but nothing about your private price list, your internal policies or yesterday’s orders. To be useful at work, it must be connected to your information safely and accurately.
Pain 4: Models make mistakes confidently
Generative models can state wrong things in a smooth, convincing voice. This is called hallucination. In a business setting, a wrong answer about a refund policy or a medicine dose can cause real harm. Teams need ways to ground answers in facts, measure accuracy and add safety checks.
Pain 5: Safety, privacy and compliance
Companies must stop harmful content, protect private data, meet legal rules about where data lives, and be able to explain who did what. Consumer chat tools were not built with these needs in mind.
Pain 6: Experiments do not become products
Many teams build an impressive demo in a week, then struggle for months to make it reliable, fast, safe and affordable. They need testing tools, monitoring, quotas, version control and cost control that fit real production work.
Anyone can cook a good meal at home for friends. Running a restaurant needs a licensed kitchen, trained staff, hygiene checks, supplier contracts and a way to serve hundreds of customers at once. Vertex AI turns the “home cooking” of a clever AI demo into a “restaurant kitchen” that can serve the public safely.
CCore Concepts You Must Know
Eight ideas explain most of what you will meet in the console and the documentation.
Foundation Model
A large pretrained model with broad skills. You use it as it is, guide it with instructions, connect it to data or customize it.
Prompt
Everything you send to the model: instructions, examples, questions, documents, images. The quality of the prompt strongly shapes the quality of the answer.
Token
A small piece of text, often part of a word, that models read and write. Limits and prices are counted in tokens.
Context Window
The maximum amount of material, in tokens, that the model can consider at one time, including your prompt and its answer.
Embedding
A list of numbers that captures the meaning of text or images, so similar things have similar numbers. It powers search by meaning.
Grounding
Connecting the model’s answer to trusted sources, such as your documents or Google Search, so it relies on real information.
Tuning
Adjusting a model with your own examples so it behaves in a specific style or does a specific task better.
Agent
A system where a model plans steps and uses tools, such as searching, calling your APIs or running code, to complete a goal.
Handy words
| Term | What it means | Everyday picture |
|---|---|---|
| Inference | Using a trained model to produce an answer | A student taking an exam, not studying |
| Temperature | A setting that controls how adventurous or predictable the output is | A dial from “strictly by the book” to “very creative” |
| System instruction | Standing rules that tell the model its role and limits | A job description |
| Few-shot prompting | Giving a few examples inside the prompt | Showing a new worker three finished samples |
| RAG | Retrieval-augmented generation: fetch facts first, then write an answer using them | An open-book exam |
| Function calling | Letting the model ask your program to run a defined action | An assistant who asks you to place a phone call |
| Latency | The time you wait for a response | How long the waiter takes |
| Throughput | How much work can be handled per minute | How many tables the restaurant can serve |
AArchitecture and the Platform Map
See the whole toolbox at a glance and how your application sits around it.
Your application never runs the model itself. It sends requests over a secure connection to Vertex AI, which routes them to the right model, applies safety checks and returns the answer. Around the models are many supporting tools for data, safety, testing and operations.
flowchart TB
App["Your Application or Agent"] --> API["Vertex AI Generative AI API"]
API --> Models["Models"]
API --> Tools["Tools and Grounding"]
API --> Controls["Controls and Quality"]
Models --> M1["Gemini Models - Text, Image, Audio, Video, Code"]
Models --> M2["Image and Video Generation Models"]
Models --> M3["Embedding Models"]
Models --> M4["Model Garden - Partner and Open Models"]
Tools --> T1["Function Calling"]
Tools --> T2["Grounding with Search or Your Data"]
Tools --> T3["RAG Engine and Vector Search"]
Tools --> T4["Code Execution"]
Controls --> C1["Safety Settings and Filters"]
Controls --> C2["Evaluation Service"]
Controls --> C3["Monitoring, Quotas and IAM"]
Walking through the picture
Your application talks to a single API. Behind it sit the models, which create content or meaning. Next to the models sit tools that give them abilities, such as looking up facts or calling your systems. Around everything sit controls: safety filters, quality testing, access rules, quotas and monitoring. You choose which parts you need.
The main components
- Gemini models: Google’s family of multimodal models, offered in different sizes. Larger ones are more capable, and smaller ones are faster and cheaper.
- Image and video generation models: models that create pictures and video clips from text descriptions.
- Embedding models: models that turn text or images into meaning-carrying numbers for search and recommendations.
- Model Garden: a catalog where you can find Google models, open models and partner models, and use or deploy them.
- Vertex AI Studio: a console workspace to try prompts, compare models, adjust settings and start tuning without writing code.
- RAG and search tools: services to connect models to your documents, including a RAG engine, vector search and enterprise search products.
- Agent tools: kits and managed runtimes for building and running agents.
- Evaluation, safety and operations tools: services to measure quality, filter content, track usage and manage access.
A big film studio has actors (models), props and locations (tools and data), a safety officer and a script supervisor (controls), and a booking office (quotas and billing). You, the director, ask for what you need through one production office, and the studio takes care of the rest.
Google offers Gemini models through more than one route. Vertex AI is the enterprise route with Google Cloud security, governance and billing. A separate developer route exists for quick experiments. Be careful to read the terms and features of the route you actually use.
HHow a Request Works Inside
Follow one question from your application, through the model and back, including a tool call.
sequenceDiagram
participant App as Your Application
participant V as Vertex AI Endpoint
participant M as Model
participant T as Your Tool or API
App->>V: Send prompt, system instructions and settings
V->>M: Turn text into tokens and run the model
M-->>V: Ask to call a function with arguments
V-->>App: Return the function call request
App->>T: Run the function in your own system
T-->>App: Function result
App->>V: Send the result back to the model
V->>M: Continue generating with the new information
M-->>V: Final answer
V-->>App: Answer with safety and usage details
Step 1: Prove who you are
Your application runs under a service account, a special identity for programs, and receives a short-lived credential. Identity and Access Management (IAM) decides what that identity may do.
Step 2: Build and send the request
The request contains the prompt, any images or files, optional system instructions, available tools and settings such as temperature and the maximum length of the answer.
Step 3: Tokenize
The text is broken into tokens. A token might be a whole short word or a piece of a longer word. Images, audio and video are also converted into internal pieces the model can read. The total number of tokens in your input and output counts toward limits and price.
Step 4: Generate, one piece at a time
The model works out which token is most likely to come next, picks one, adds it to the text and repeats. This is why long answers take longer than short ones, and why answers can be streamed to the user as they are written. Settings such as temperature decide how much randomness goes into the choice. A low temperature gives steadier, more predictable output. A high temperature gives more varied, creative output.
Step 5: Use tools if needed
If you defined functions, the model may decide that it needs one, for example “get order status for order 123”. It sends back a structured request. Your application runs the function in your own system, returns the result, and the model continues. The model never runs your code directly. Your application stays in control.
Step 6: Safety checks and the response
Safety filters check the prompt and the answer against configured categories. The final response comes back with the content, usage information such as token counts, and details about any blocked content.
Writing a story one word at a time, always choosing a sensible next word based on everything written so far, is how the model works. If the story needs a fact it does not have, the writer calls out, “Could someone check the train timetable?”, waits for your answer and carries on.
A model does not remember earlier conversations on its own. Each request must include the history that matters. Long chat histories use more tokens, cost more and may need trimming or summarizing.
DData Flow and Application Lifecycle
An AI feature is not finished when the demo works. Here is the full life of a generative AI application.
Define the goal
Write down the task, the users, what a good answer looks like and what must never happen. Decide how success will be measured.
Explore with prompts
Use Vertex AI Studio to try different models and prompts on real examples. Many problems are solved here, with no further engineering.
Add knowledge and tools
Connect the model to your documents through grounding or RAG, and to your systems through function calling, when it needs facts or actions.
Build the application
Write the service around the model: input handling, prompt templates, tool code, safety settings, logging and error handling.
Evaluate
Test on a fixed set of realistic questions with known good answers, and measure accuracy, safety, tone, speed and cost.
Customize if needed
If quality is still short, consider tuning, a different model, or a better retrieval approach.
Launch carefully
Release to a small group first. Set quotas, budgets, alerts and human escalation paths.
Monitor and improve
Watch usage, quality and user feedback. Update prompts, data and model versions through the same testing steps used before launch.
Why this order matters
A common mistake is to jump to the most expensive step, such as tuning a model, before trying simple prompt improvements and retrieval. Prompting and grounding are quick, cheap and reversible. Tuning needs data, time and care. Follow the ladder from simple to complex, and climb only as high as your quality goals demand.
Create your evaluation set at the very start, from real user questions. Every change you make, whether prompt, model or data, can then be judged against the same yardstick instead of by gut feeling.
TThe Models: Gemini, Image, Video, Embeddings and Model Garden
Choosing the right model is the biggest lever on quality, speed and cost.
Gemini models
Gemini is Google’s family of multimodal models. A single Gemini model can read text, images, audio, video and documents together, and write text and code, and some versions can also produce other media. Gemini models come in tiers. A larger, more capable tier handles complex reasoning, long documents and difficult coding. Smaller, faster tiers handle everyday tasks, such as classification, extraction and chat, at lower cost and delay. Some recent models can “think” before answering, spending extra effort on hard problems. The exact names, versions and abilities change often, so check the current model list.
Image and video generation
Separate models turn written descriptions into pictures, edit existing pictures and produce short video clips. They are useful for marketing drafts, product mockups, storyboards and creative exploration. Generated media may carry an invisible digital watermark to help identify it as AI-made. Always review generated media for quality, rights issues and suitability before publishing.
Embedding models
An embedding model reads text, and sometimes images, and produces a list of numbers capturing its meaning. Texts with similar meaning get similar numbers. This enables semantic search, which finds results by meaning instead of exact words, and also recommendations, grouping and duplicate detection. Embeddings are a key building block of RAG systems.
Model Garden: partner and open models
Model Garden is a catalog inside Vertex AI where you can discover many models: Google’s own, open models such as the Gemma and Llama families, and models from partner companies. Some can be used as ready-made services that you simply call. Others can be deployed onto your own dedicated machines, which gives more control but needs more setup and cost. Terms and licenses differ by model, so read them.
How to choose
| Need | Good starting choice | Why |
|---|---|---|
| Simple, high-volume tasks such as labeling or short extraction | A small, fast Gemini tier | Low cost and low delay |
| General chat, summaries and writing | A mid-size Gemini tier | Good balance of quality and cost |
| Difficult reasoning, long documents, complex code | The most capable Gemini tier or a thinking model | Higher accuracy on hard problems |
| Understanding images, audio, video and PDFs | A multimodal Gemini model | Reads several media types in one request |
| Search by meaning | An embedding model | Turns content into comparable numbers |
| Picture or video creation | Image or video generation models | Built for creating media |
| Special licensing, custom hosting or open weights | Open models from Model Garden | More control over where and how models run |
Model versions and retirement
Models receive new versions and older ones are eventually retired. Preview and experimental models are not meant for critical production use and may change or disappear. Pin the version you tested, watch for retirement notices, and plan time to retest on newer versions.
Choosing a vehicle: you would not use a heavy truck to deliver a letter, nor a bicycle to move furniture. Small models are bicycles and scooters, large models are trucks. Pick by the load and the distance, not by the size of the engine.
Do not choose a model only from leaderboards or marketing. Test two or three candidates on your own evaluation set. A smaller model often performs just as well on your specific task at a fraction of the cost.
PPrompt Design and Model Settings
The cheapest way to improve results is to ask better.
A prompt is the full set of instructions and material you send to the model. Writing good prompts is called prompt design or prompt engineering. It is a practical skill, closer to writing a clear brief for a colleague than to programming.
Parts of a strong prompt
- Role: who the model should act as, such as a careful customer support agent for a bank.
- Task: exactly what to do, stated clearly and positively.
- Context: the facts, documents or conversation the model needs.
- Rules and limits: what to avoid, what tone to use, what to do when unsure.
- Examples: one to a few sample inputs with ideal outputs. This is few-shot prompting, and it is one of the most powerful techniques.
- Output format: exactly how the answer should look, such as three bullet points or a particular set of fields.
Practical techniques
- Be specific. “Summarize in three bullet points for a busy manager” beats “summarize”.
- Break big tasks into steps. Several small, clear prompts often beat one giant request.
- Show, do not only tell. Examples reduce confusion about style and format.
- Allow “I don’t know”. Tell the model it is acceptable to say when the information is missing. This reduces invented answers.
- Separate instructions from data. Clearly mark where the user’s text or document begins and ends.
- Ask for reasoning when useful. For tricky problems, asking the model to work step by step can improve results, though newer thinking models do much of this themselves.
- Test and revise. Treat prompts like code: version them, test them and review changes.
Model settings
| Setting | What it does | Typical use |
|---|---|---|
| Temperature | Controls randomness in word choice | Low for facts and extraction, higher for brainstorming |
| Top-p and top-k | Limit which candidate words are considered | Fine-tuning variety, usually left near defaults |
| Maximum output tokens | Caps the length of the answer | Controls cost and prevents rambling |
| Stop sequences | Text that makes the model stop | Ending at a known marker |
| System instructions | Standing rules for the whole conversation | Role, tone, safety rules |
| Safety settings | Thresholds for blocking harmful categories | Matching your audience and policy |
Giving instructions to a talented new intern: “Write something about our product” gets a vague result. “Write a three-sentence product blurb for teenagers, friendly tone, avoid technical words, here are two examples we liked” gets something useful on the first try.
Treat text from users and documents as untrusted. People can write instructions inside their text, such as “ignore your rules”, which is called prompt injection. Keep your own rules in system instructions, and add checks outside the model.
MMultimodal Abilities and Long Context
Models that can see, hear and read very long material.
Understanding more than text
A multimodal model accepts several kinds of input in one request. This opens many practical uses.
- Images: describe a photo, read a chart, check a damaged product picture, or compare two designs.
- Documents and PDFs: read a contract, an invoice or a scientific paper directly, including its tables and figures.
- Audio: transcribe and summarize a meeting or a call, and answer questions about it.
- Video: describe what happens in a clip, find moments, or summarize a long recording.
- Mixed input: ask a question about a diagram together with a written specification.
Long context
Some models can consider a very large amount of material at once, equal to many books or hours of video. This allows tasks such as “find every inconsistency across these twenty contracts” or “summarize this entire code repository”. Long context is powerful, but it has trade-offs:
- Cost: you pay for every token you send, every time, unless you use caching.
- Speed: more input usually means slower responses.
- Attention: models can still miss details buried in the middle of enormous inputs, so test on your own data.
Context caching
If you send the same large material again and again, such as a long manual with many different questions, context caching lets you store it once and reuse it at a lower cost and often faster speed. Check the current rules for how long caches last and how they are billed.
Real-time and streaming
Some models support live, two-way streaming of audio and video, enabling natural voice assistants that you can interrupt. Responses can also be streamed as they are generated, so users see text appear immediately instead of waiting for the full answer.
A multimodal model is like an expert who can look at photographs, listen to recordings and read documents all at once. Long context is like letting that expert read an entire filing cabinet before answering. It is impressive, but it takes longer and costs more than reading a single page.
For large collections of documents, retrieving only the relevant passages (RAG) is usually cheaper and more accurate than putting everything into the prompt each time. Use long context for tasks that truly need a whole document at once.
SStructured Output, Function Calling and Tools
Making the model produce data your programs can use, and take actions in the real world.
Structured output
Programs prefer data in a predictable format. Instead of a free-form paragraph, you can ask the model to answer in a fixed structure, such as a set of named fields with allowed values. Vertex AI lets you provide a schema, which is a description of the exact shape you want, and the model’s output will follow it. This is invaluable for extraction tasks, classification and feeding results into databases. You should still validate the output in your code, since a valid shape does not guarantee that the content is correct.
Function calling
Function calling lets the model request that your application perform an action. You describe the available functions, such as “look up order status” or “create support ticket”, with their names and parameters. When the user asks something that needs them, the model replies with a structured request naming the function and the arguments. Your application runs the function and returns the result to the model, which then writes the final answer. This is how a chat assistant can check real stock levels or book a real appointment.
Built-in tools
- Grounding with Google Search: lets the model use fresh public information from the web and show its sources.
- Grounding with your data: lets the model use your private documents through search and RAG services.
- Code execution: lets the model write and run small programs in a safe sandbox to do accurate calculations and data analysis.
- Other tool connections: options to connect to extensions, APIs and protocol-based tool servers, depending on current features.
Safety around actions
When a model can take actions, mistakes matter more. Good practice includes:
- Least privilege: give each function only the permissions it truly needs.
- Confirmation steps: ask the user to confirm actions that spend money, delete data or send messages.
- Validation: check every argument the model provides before running anything.
- Limits: cap how many actions or how much money one conversation may involve.
- Logging: record which actions were requested and executed, and by whom.
A personal assistant can draft a travel plan, but should ask, “Shall I book this flight for 480 dollars?” before using your credit card. Function calling lets the model prepare the request, and your confirmation rules decide whether it is carried out.
Never let a model act with more power than the user who is talking to it. If a user is not allowed to see another customer’s records, the functions the model calls on that user’s behalf must not allow it either.
GGrounding and RAG: Answers From Your Own Data
The most important pattern for business applications: make the model read before it answers.
A model’s built-in knowledge stops at the time of its training and never included your private documents. If you ask about your company’s leave policy, it can only guess. Retrieval-augmented generation (RAG) solves this. First, the system retrieves the most relevant passages from your documents. Then it gives those passages to the model, together with the question, and asks the model to answer using them. The model writes the answer, but the facts come from your data.
flowchart LR
subgraph PREP["Preparation Stage"]
Docs["Your Documents"] --> Parse["Parse and Split into Chunks"]
Parse --> Emb["Create Embeddings"]
Emb --> Index["Store in Vector Index"]
end
subgraph ANS["Answering Stage"]
Q["User Question"] --> QE["Embed the Question"]
QE --> Find["Find Most Similar Chunks"]
Index --> Find
Find --> Prompt["Build Prompt with Question and Chunks"]
Prompt --> LLM["Generative Model"]
LLM --> Ans["Answer with Source References"]
end
The preparation stage
- Collect and clean documents: manuals, policies, web pages, tickets and records. Document AI’s layout parsing can help turn PDFs and scans into clean structured text.
- Chunk: split documents into passages of sensible size that keep related ideas together, with some overlap so ideas are not cut in half.
- Embed: turn each chunk into an embedding using an embedding model.
- Index: store the embeddings in a vector database or search service, along with the original text and details such as the source and date.
The answering stage
- Embed the question in the same way.
- Search for the nearest chunks, often combined with keyword search and filters such as department or date.
- Rerank if useful, so the best passages come first.
- Prompt the model with the question, the passages and clear rules such as “answer only from these passages and cite them”.
- Return the answer with links to sources, so the user can check.
Ways to build it on Google Cloud
Google offers several routes. Some are fully managed search products that handle parsing, indexing and retrieval for you, which is fastest to launch. Others give you building blocks, such as a RAG engine, embedding models and a vector search service, for more control. Choose managed products when speed matters and requirements are standard, and building blocks when you need custom ranking, special data types or deep control. Check the current product lineup before deciding.
Common causes of poor RAG answers
- Bad chunks: pieces that are too small lose meaning, and too large pieces bury the answer.
- Missing or out-of-date documents: the model cannot use what is not in the index.
- Weak retrieval: the right passage exists but is not found. Try better chunking, hybrid search, filters or reranking.
- No permission checks: users must only retrieve documents they are allowed to see.
- Loose instructions: if the prompt does not require sticking to sources, the model may add its own guesses.
An open-book exam. The student (model) is clever but may not remember the details of your company’s rulebook. Before answering, a librarian (retrieval) hands over the three most relevant pages. The student writes the answer and points to the page numbers. If the librarian brings the wrong pages, even the cleverest student gives a poor answer.
Measure retrieval separately from generation. First check whether the right passage appears in the top results. If it does not, fixing the prompt or the model will not help.
CCustomizing: Prompting, RAG, Tuning or Agents?
A simple ladder for deciding how far to go.
There are several ways to make a model fit your needs. They differ in effort, cost and what problems they fix. A helpful rule is to start at the bottom of the ladder and climb only if needed.
flowchart TD
Start["Model Answers Are Not Good Enough"] --> Q1{"Are instructions or examples unclear?"}
Q1 -->|"Yes"| A["Improve the Prompt and Add Examples"]
Q1 -->|"No"| Q2{"Does it lack your private or fresh facts?"}
Q2 -->|"Yes"| B["Add Grounding or RAG"]
Q2 -->|"No"| Q3{"Does it need to take actions or use tools?"}
Q3 -->|"Yes"| C["Add Function Calling or Build an Agent"]
Q3 -->|"No"| Q4{"Need a special style, format or skill on many examples?"}
Q4 -->|"Yes"| D["Consider Tuning with Your Examples"]
Q4 -->|"No"| E["Try a More Capable Model"]
Fix 1: Better prompts
Cheap, instant and reversible. It fixes unclear tasks, wrong format and tone. Always try this first.
Fix 2: Grounding and RAG
Fixes missing or changing facts. Your knowledge stays in your documents, where you can update, delete and control access to it, instead of being baked into a model.
Fix 3: Tools and agents
Fixes the need to act or to calculate exactly. Function calling and agents connect the model to real systems.
Fix 4: Tuning
Tuning adjusts a model using your own examples of inputs and ideal outputs. It is best for teaching a consistent style, a specialized format or a narrow skill that is hard to describe in a prompt, especially at high volume where a smaller tuned model can replace a bigger one. Common approaches include supervised fine-tuning, which learns from example pairs, and preference-based methods that learn from which of two answers is better. It requires good-quality examples, often hundreds or more, testing, and a plan to retune when the base model changes. Tuning is not a good way to add fast-changing facts, because those are better kept in retrievable documents.
Fix 5: A bigger or different model
If all else fails, a more capable model may reason better. This costs more, so try it after cheaper options.
| Method | Fixes | Effort | Main caution |
|---|---|---|---|
| Prompt design | Unclear tasks, format, tone | Low | Needs testing for each change |
| Grounding and RAG | Missing, private or changing facts | Medium | Retrieval quality and access control |
| Function calling and agents | Actions, calculations, live data | Medium to high | Safety of actions |
| Tuning | Consistent style or specialized skill | High | Needs good data and retuning later |
| Larger model | Hard reasoning | Low effort, higher running cost | Cost and delay |
If a new employee makes mistakes, you first give clearer instructions (prompt), then hand over the reference manual (RAG), then give access to the company systems (tools), and only if needed send them on a long specialized training course (tuning). Hiring a more senior person (bigger model) is the costly last resort.
AAgents and Orchestration
When one answer is not enough, models can plan, use tools and work through many steps.
A plain model call takes a prompt and returns an answer. An agent is a larger design where the model works in a loop: it looks at the goal, decides the next step, uses a tool, reads the result, and repeats until the goal is reached or it must ask a person. Agents can search, read documents, call business systems, write and run code, and coordinate with other agents.
The parts of an agent
- The model: the reasoning engine that decides what to do next.
- Instructions: the role, goals and rules.
- Tools: functions, search, databases and other services the agent may call.
- Memory: short-term notes for the current task and sometimes long-term facts about users or past work.
- Guardrails: limits on what the agent may do, how long it may run, and when it must stop and ask a human.
Google Cloud support
Google Cloud provides open-source kits for building agents, managed runtimes to host and scale them, session and memory features, and ways for agents to talk to tools and to each other using open protocols. These options evolve quickly, so check the current documentation and choose the level of abstraction that fits your team: a low-code builder, a code framework or a fully custom design.
Workflows versus agents
Not every task needs an agent. If the steps are fixed and known, such as “extract fields, validate, save”, a plain workflow that calls the model at set points is simpler, cheaper and more predictable. Agents shine when the path is not known in advance and the system must decide what to do. Start with a workflow, and add agent-style flexibility only where it is truly needed.
Risks of agents
- Compounding errors: a small mistake early in a long chain can grow.
- Cost and time: many model calls add up.
- Unwanted actions: an agent with powerful tools can do real damage if misled.
- Hard testing: behavior can vary between runs, so test many scenarios.
A simple model call is like asking a colleague a quick question. An agent is like giving a colleague a project: “Plan our team offsite.” They research venues, check calendars, compare prices, ask you questions when stuck and return with a plan. You still want them to ask before signing any contract.
Put hard limits on agents: maximum steps, maximum spending, and a list of actions that always need human approval. An agent stuck in a loop can burn through a large budget quickly.
SSafety, Responsible AI and Guardrails
A helpful system must also be a safe one.
Generative models can produce harmful, biased, private or simply wrong content. Responsible use means building several layers of protection.
Layer 1: Built-in safety filters
Vertex AI checks prompts and responses against categories of harm, such as hate, harassment, sexually explicit content and dangerous content. You can adjust thresholds within allowed limits to suit your audience. A children’s education app should be stricter than an internal research tool. Some content is always blocked.
Layer 2: Your own instructions
System instructions define your assistant’s role, topics it should avoid, tone and what to do when asked something out of scope, such as “politely decline and suggest contacting support”.
Layer 3: Screening services
Additional services can screen prompts and answers for risks such as prompt injection, jailbreak attempts, leaked sensitive data and unsafe content. Sensitive Data Protection can find and mask private details such as card numbers in prompts and outputs.
Layer 4: Grounding and citations
Requiring answers to cite sources lets users verify claims and reduces invented facts.
Layer 5: Human oversight
For high-stakes uses such as medical, legal, financial or hiring decisions, keep a qualified person responsible for the final decision, and make it easy for them to see the evidence and override the model.
Fairness and bias
Models learn from human-written data and can reflect its biases. Test your application with varied examples, names, dialects and viewpoints. Look for patterns of unfair behavior, and avoid using model output alone for decisions that seriously affect people.
Transparency
Tell users when they are talking to an AI, explain its limits, label AI-generated media where appropriate and offer a way to report problems.
A swimming pool has a lifeguard, a fence, depth markings, rules on the wall and a first-aid kit. No single safeguard is enough, but together they make swimming safe. AI safety also works in layers.
Run “red team” tests before launch, where people deliberately try to break your assistant with tricky, rude and sneaky inputs. Record what works against it and fix those gaps.
EEvaluation: Knowing If It Works
Without measurement, every change is a guess.
Testing generative AI is different from testing normal software. The same input can give slightly different outputs, and “correct” is often a matter of degree. Still, you can and must measure quality.
Build an evaluation set
Collect a few dozen to a few hundred realistic inputs, including easy, hard and tricky ones, and include the answers or qualities you want. Keep it fixed so results are comparable over time. Add new failures as you discover them.
What to measure
- Correctness and groundedness: are the facts right, and supported by the sources?
- Relevance and completeness: does the answer address the question fully?
- Format and instruction following: does it respect length, structure and rules?
- Safety: does it avoid harmful or private content?
- Tone and style: does it sound right for your brand?
- Latency and cost: is it fast and cheap enough?
- Retrieval quality for RAG: did the right passages come back?
Ways to score
- Computed metrics: exact matching or overlap scores, useful for extraction and classification with clear right answers.
- Model-based judging: a strong model grades answers against criteria you write. This scales well but needs checking against human opinions.
- Human review: experts rate samples. It is the most trusted, but slowest and most costly.
- Side-by-side comparison: raters or judge models choose which of two versions is better.
Vertex AI includes an evaluation service to run such tests, and Vertex AI Studio can compare prompts and models. Check the current tools and metrics in the documentation.
Keep evaluating after launch
Use thumbs up and down, user comments and sampled reviews of real conversations to find new failures. Re-run your evaluation whenever you change the prompt, the data, the retrieval settings or the model version.
A teacher uses a standard exam to compare students fairly and tracks progress term by term. An evaluation set is the standard exam for your AI application. If you change the teaching method, you check the exam results before declaring victory.
Judging a model from three impressive examples is how bad launches happen. A model that handles your favorite examples well can fail on many ordinary ones. Test on volume and variety.
PPerformance, Quotas and Scalability
How to make AI features fast, reliable and ready for many users.
Where the time goes
Response time depends on the model size, the length of the input, the length of the output and current load. Generating tokens is sequential, so longer answers take longer. Reduce delay by choosing smaller models where adequate, trimming prompts, limiting output length, streaming responses and caching repeated context.
Quotas and rate limits
Vertex AI applies limits on requests and tokens per minute for each model and region. If you exceed them, you receive a “too many requests” error. A shared pool may allocate capacity dynamically, but heavy production use needs planning. Request quota increases early, and design your application to cope with limits.
Provisioned throughput
For critical applications that need guaranteed capacity and steady performance, you can reserve capacity, often called provisioned throughput, for a fixed fee over a committed period. This reduces the risk of throttling at peak times, but you pay whether or not you use it all.
Batch processing
For large jobs that are not urgent, such as classifying a million support tickets overnight, batch prediction runs many requests together at a lower price and without worrying about interactive speed. Check the current discounts and limits.
Techniques for scale
- Retry with backoff: when throttled or facing temporary errors, wait and retry, waiting longer each time.
- Queue work: use Pub/Sub or Cloud Tasks to smooth bursts and control the rate.
- Cache answers: identical or very similar questions can reuse earlier answers where freshness allows.
- Route by difficulty: send easy tasks to small models and hard ones to larger models.
- Use regional endpoints near users and data, and consider fallback to another region or model for resilience.
- Set timeouts: do not let a user wait forever for a slow answer.
- Reduce prompt size: remove unnecessary history, repeated instructions and irrelevant retrieved text.
A busy restaurant can keep tables ready for regular guests (provisioned throughput), take walk-ins as space allows (shared capacity), cook big catering orders in the quiet afternoon (batch), and send simple dishes to the quick counter while complex ones go to the main chef (routing).
Measure the whole user journey, not just the model call. Retrieval, validation, tool calls and network time often add as much delay as the model itself.
SSecurity and Privacy
Prompts and answers often hold sensitive business and personal information. Protect them.
Controlling access
Use Identity and Access Management (IAM) to decide who and what may call models, manage tuned models and view data. Give each application its own service account with only the roles it needs, which is the principle of least privilege. Avoid long-lived keys, and never place credentials in prompts or code.
Protecting data
- In transit and at rest: traffic to Google Cloud APIs is encrypted, and stored data is encrypted by default. You can use customer-managed keys for supported resources.
- Private connectivity: options such as Private Service Connect keep traffic off the public internet.
- Perimeters: VPC Service Controls can reduce the risk of data leaving a protected boundary, where supported.
- Data location: choose regional endpoints that meet your residency rules. Some models and features use global endpoints, so confirm where processing happens.
How Google handles your data
Google states that customer prompts and outputs on Vertex AI are not used to train its models without your permission. There may be short-term retention for features such as caching, and for abuse monitoring, with options that differ by feature and agreement. Read the current data governance and terms carefully, and confirm them with your legal and compliance teams before sending regulated data.
Reducing exposure
- Send only the data the task needs, and mask private details when possible.
- Apply access control in retrieval, so users only retrieve documents they may see.
- Do not paste secrets into prompts, and do not put sensitive data in system instructions that many users can influence.
- Treat model output as untrusted input. Validate it before using it in commands, queries or web pages.
- Set retention rules on logs, chat histories and tuning data.
Threats specific to generative AI
- Prompt injection: hidden instructions in user text, web pages or documents that try to hijack the model.
- Data leakage: the model revealing private information from its context.
- Excessive agency: an agent with too much power being tricked into harmful actions.
- Poisoned knowledge: malicious or wrong content planted in documents that feed RAG.
- Denial of wallet: abusive usage designed to run up costs.
Auditing
Cloud Audit Logs record administrative actions and, if enabled, data access. Record which model version, prompt version and data sources produced each important answer, so that you can investigate problems later.
An office where the receptionist is helpful to everyone has rules: visitors cannot enter the records room, the receptionist never gives out staff home addresses even if asked nicely, and anything slipped under the door is checked before being acted on.
Content fetched from the web, emails or shared documents can contain instructions aimed at your model. Never give an AI that reads untrusted content the power to take sensitive actions without a human check.
MMonitoring, Logging and Metrics
Watch both the health of the system and the quality of its answers.
There are two kinds of monitoring. Operational monitoring asks whether the system is running well. Quality monitoring asks whether the answers are still good, safe and useful.
Operational signals
| Signal | Why it matters | A warning sign |
|---|---|---|
| Request count and token usage | Drives cost and shows demand | Sudden jumps without a business reason |
| Latency, including time to first token | Shows how fast users see answers | Rising delay at the same traffic |
| Error and throttling rate | Shows quota problems and failures | Frequent “too many requests” responses |
| Quota usage | Shows distance to limits | Regularly near the maximum |
| Blocked-response rate | Shows safety filter activity | Sudden rise, perhaps from abuse or a prompt change |
| Tool call success rate | Shows whether actions work | Failing functions or repeated retries |
| Cost per conversation or per task | Shows unit economics | Costs rising faster than value |
Quality signals
- User feedback: thumbs up and down, ratings, and the share of conversations escalated to humans.
- Groundedness checks: how often answers are supported by retrieved sources.
- Sampled reviews: people read random conversations weekly and score them.
- Drift: changes in the questions people ask, in your documents or in model behavior after a version change.
- Safety incidents: reports of harmful or inappropriate output, with the details needed to reproduce them.
- Evaluation set results: scheduled re-runs to catch silent regressions.
Logging with care
Logging prompts and answers helps debugging and improvement, but they may hold private information. Decide what to log, mask sensitive details, restrict access, set retention limits and tell users when conversations are recorded.
A call center tracks how many calls arrive and how long they take (operations), and also listens to a sample of calls to check courtesy and correctness (quality). Both are needed to run a good service.
CCost: Understanding the Bill
Generative AI is billed mostly by the amount of text and media processed. Know the units and avoid surprises.
Pricing on Vertex AI is usage-based and set by Google. It differs by model, by input and output, and by features. It changes often, so always use Google’s official pricing page and calculator for current numbers. The general shape is stable and useful for planning.
Input Tokens
Everything you send: instructions, history, documents, retrieved passages and media. Long prompts cost more.
Output Tokens
Everything the model writes, including any hidden thinking in some models. Output is usually priced higher than input.
Images, Audio and Video
Billed by size, duration or tokens, and generation models may be billed per image or per second of video.
Grounding, Caching and Tools
Some features, such as search grounding or storing cached context, carry their own charges.
Provisioned Throughput
A fixed fee for reserved capacity over a committed period, whether or not you use it fully.
Tuning and Hosting
Charges for training runs and for serving tuned or self-deployed models, which may accrue while deployed.
Supporting Services
Vector search, storage, compute, networking, logging and human review costs all add to the total.
Batch Discounts
Non-urgent bulk jobs may be priced lower than interactive calls. Check the current terms.
Ways to keep spending sensible
- Pick the smallest model that meets your quality bar. Use an evaluation set to prove it.
- Trim the prompt. Remove repeated instructions, trim chat history and send only the most relevant passages.
- Cap output length. Ask for concise answers and set a maximum.
- Use context caching for large, repeated material.
- Use batch mode for non-urgent bulk work.
- Cache whole answers for repeated questions where freshness allows.
- Route by difficulty, sending easy tasks to cheap models.
- Limit agent steps and retries so loops cannot run wild.
- Set budgets, quotas and alerts, and label resources by team and application.
- Measure cost per successful task, not just per request. A cheaper model that fails often can cost more overall.
A taxi meter counts distance and waiting time. A long detour (a huge prompt) and a slow, rambling driver (long output) both increase the fare. Giving the driver clear directions and choosing a small car for a short trip keeps the fare low.
A bug that retries endlessly, an agent stuck in a loop, or an abusive user sending huge inputs can create a very large bill in hours. Add rate limits, input size limits, budgets and alerts before going live.
AAdvantages, Disadvantages and Trade-offs
No tool is perfect. A good architect weighs both sides before choosing.
Advantages
- Access to powerful models without training or hosting them yourself
- Many models in one place, including Google, partner and open options
- Multimodal input for text, images, audio, video and documents
- Grounding, RAG, function calling and agent tools for connecting to real data and systems
- Enterprise controls: IAM, private networking, encryption, audit logs
- Tools for prompt testing, evaluation, tuning and monitoring
- Scales with managed infrastructure, with options for reserved capacity and batch
- Fits naturally with BigQuery, Cloud Storage, Cloud Run, Pub/Sub and other services
- Pay-as-you-go pricing allows small starts
Disadvantages
- Models can hallucinate, so important answers need grounding and checks
- Outputs can vary between runs, which complicates testing
- Costs scale with usage and can surprise teams without limits
- Models and features change quickly, with versions retired on a schedule
- Quotas and capacity limits need planning for large launches
- Security risks such as prompt injection need dedicated defenses
- Quality depends heavily on your prompts, data and evaluation effort
- Tied to Google Cloud for the managed platform
How it compares with other routes
| Question | Generative AI on Vertex AI | Classic task APIs, such as language or vision APIs | Self-hosted open models |
|---|---|---|---|
| Flexibility | Very high, follows instructions across many tasks | Fixed features with consistent output | High, with full control |
| Setup effort | Low to medium | Very low | High, you run the models and hardware |
| Predictability of output | Can vary, needs guard rails | High | Varies by model and setup |
| Cost pattern | By tokens and media, can be high at scale | Per unit, usually low | Hardware and engineering cost |
| Control over data location and weights | Good, within Google’s options | Good, within Google’s options | Maximum |
| Best for | Chat, summaries, extraction with custom fields, agents, creative work | Standard analysis at large scale | Special licensing or full control needs |
The main trade-offs, in plain words
- Flexibility versus predictability: a model that can do anything can also do unexpected things. Guard rails and tests restore control.
- Quality versus cost and speed: larger models are smarter but slower and pricier.
- Knowledge in the model versus knowledge in documents: retrieval keeps facts fresh and controllable, while tuning bakes in style and skill.
- Autonomy versus control: agents save effort but need strict limits and human checks.
- Speed to launch versus durability: quick prototypes are easy, but production needs evaluation, safety and monitoring.
DDesign Patterns and Anti-patterns
A pattern is a proven way to solve a common problem. An anti-pattern is a tempting mistake that causes pain later.
Helpful patterns
Grounded Assistant
Retrieve relevant passages first, instruct the model to answer only from them, and show citations.
Model Router
Send easy requests to a small, cheap model and escalate hard ones to a stronger model.
Structured Extraction
Use a schema so output is always in a predictable shape, then validate it in code before saving.
Human in the Loop
Let the model draft and a person approve, especially for messages, decisions and actions with real consequences.
Evaluate Before You Ship
Keep a fixed test set and run it for every change to prompt, data, retrieval or model.
Layered Guardrails
Combine safety filters, system rules, input and output screening, grounding and human review.
Workflow First, Agent Later
Use fixed steps wherever the path is known, and apply agent flexibility only to the uncertain parts.
Cache and Batch
Cache repeated context and answers, and move non-urgent bulk jobs to batch mode.
Anti-patterns to avoid
What people do
They ship a demo after trying a handful of friendly questions, with no evaluation set.
Why it hurts
Hidden failures appear in front of real users, and nobody can tell whether later changes made things better or worse.
Better approach
Build an evaluation set from real questions, include hard cases, and test every change against it.
What people do
They tune a model to teach it company facts, such as prices and policies.
Why it hurts
Facts go stale, cannot be easily corrected or removed, and the model may still invent details.
Better approach
Keep facts in documents and retrieve them with RAG. Use tuning for style and skill, not for changing facts.
What people do
They always use the biggest model and paste huge amounts of text into every prompt.
Why it hurts
Costs and delays are far higher than needed, and quality may not improve.
Better approach
Test smaller models, retrieve only relevant passages, cache repeated material and cap output length.
What people do
They give an agent broad powers and trust whatever the model decides, including after reading untrusted web pages or emails.
Why it hurts
A hidden instruction in untrusted content can trigger harmful actions or data leaks.
Better approach
Use least privilege, validate every argument, require human approval for sensitive actions and separate untrusted content from instructions.
What people do
They depend on a preview or auto-updating model name in production, and never plan for model retirement.
Why it hurts
Behavior changes suddenly, or the model disappears, breaking features and downstream rules.
Better approach
Pin tested versions, watch retirement notices, and rerun your evaluation before moving to a new version.
What people do
They treat model output as trusted and insert it directly into databases, commands or web pages.
Why it hurts
Wrong or manipulated output can corrupt data or create security holes.
Better approach
Validate and sanitize all model output, as you would any input from an outside source.
BBest Practices and Common Mistakes
A checklist you can follow from the first day.
Best practices
- Start with a clear use case and success measures. Know what good looks like before building.
- Build an evaluation set first. Use real questions, including hard ones.
- Climb the ladder. Prompts, then RAG, then tools, then tuning, then a bigger model.
- Write prompts like briefs. Role, task, context, rules, examples and output format.
- Ground important answers. Require citations and allow “I don’t know”.
- Use structured output where programs consume the result, and validate it.
- Choose the smallest model that passes your tests.
- Layer your safety. Filters, system rules, screening, grounding and human review.
- Apply least privilege to service accounts, tools and retrieval.
- Pin model versions and plan for retirement.
- Plan capacity. Check quotas, use retry with backoff, queue work and consider reserved capacity for critical loads.
- Monitor quality and cost, not only uptime, and sample real conversations regularly.
- Set budgets, limits and alerts before launch.
- Launch gradually to a small group, with a feedback channel and a human fallback.
- Check the latest documentation. Models, limits, features and prices change often.
Common mistakes
Believing the first impressive answer
A great demo answer hides the many ordinary failures. Measure across many cases before trusting.
Vague prompts
“Make it better” gives random results. Say who the audience is, what length and style you want, and what to avoid.
Ignoring permissions in retrieval
Users get answers drawn from documents they should not see. Filter retrieval by the user’s access rights.
Poor chunking and stale data
RAG fails quietly when passages are cut badly or documents are out of date. Review chunks and refresh the index regularly.
Sending the whole chat history every time
Costs and delays grow with every turn. Summarize or trim old history.
No plan for throttling
At launch, traffic hits the quota and users see errors. Plan capacity, queues and graceful messages.
Changing several things at once
When prompt, model and data all change together, nobody knows what helped or hurt. Change one thing at a time and re-test.
Leaving out the human fallback
When the AI cannot help, users get stuck. Always offer a way to reach a person.
RReal-World Usage Scenarios
Four illustrative stories show where generative AI on Vertex AI fits. The companies below are imaginary examples to teach the ideas.
Scenario 1: A bank’s internal policy assistant
Employees waste hours searching long policy manuals. The bank indexes its documents, chunks them with layout parsing, and builds a RAG assistant. Every answer cites the policy page, retrieval respects each employee’s access rights, and the assistant says “I could not find this” when the answer is missing. A compliance team samples conversations weekly. Search time drops sharply, and mistakes in policy interpretation fall.
Scenario 2: A retailer’s product description engine
A retailer has two hundred thousand products with thin descriptions. A small, fast model drafts descriptions from product attributes using a schema and a few approved examples. Output is validated for length and banned claims, and a sample is reviewed by editors. Batch mode runs overnight at lower cost. Writers move from typing every description to editing the best drafts.
Scenario 3: A support team’s reply assistant
A software company uses a model to read incoming tickets, retrieve matching help articles and past solutions, and draft a reply for agents. Function calling checks the customer’s plan and order status. The agent reviews and sends. A router sends simple, repeated questions to a small model and complex ones to a stronger model, keeping costs steady. Customer satisfaction rises while handling time falls.
Scenario 4: A media company analyzing video archives
A broadcaster has thousands of hours of footage. A multimodal model summarizes clips, tags topics and finds key moments, with timestamps stored in a database. Embeddings let producers search by meaning, such as “crowd celebrating in the rain”. Editors verify tags before archiving, and the company adds a review step for sensitive or copyrighted content.
When Generative AI on Vertex AI is a strong choice
- You want to add language, vision or reasoning abilities without training your own models.
- You need enterprise security, governance and billing within Google Cloud.
- You need to connect models to your own data and systems.
- You want to compare several models, including partner and open ones, in one place.
- You have a plan to evaluate, monitor and control quality and cost.
When to think twice
- A fixed, standard task is already well served by a cheaper classic API.
- The decision is high-stakes and no human review is possible.
- You cannot send the data to a managed service because of strict rules.
- You have no way to test quality, so you could not tell if it works.
- Exact, repeatable output is essential, and ordinary software logic would do the job.
FFrequently Asked Questions
Quick answers to questions that beginners ask most often.
SSummary and Key Takeaways
Remember These Points
- What it is: Generative AI on Vertex AI is Google Cloud’s managed way to use foundation models such as Gemini, image and video models, embeddings and many partner and open models, with enterprise security, governance and billing.
- How requests work: prompts are broken into tokens, the model generates the answer piece by piece, and it can ask your application to run functions. Limits and prices are counted in tokens.
- Climb the ladder: improve prompts first, then ground the model with RAG, add tools and agents when actions are needed, tune only for style or specialized skill, and use a larger model last.
- Ground and structure: use your own documents to supply facts, require citations, and use schemas so that output is predictable and validated before use.
- Measure everything: build an evaluation set from real questions, test every change, and keep sampling real conversations for quality, safety, speed and cost.
- Layer your protection: safety filters, clear rules, input and output screening, least-privilege access, protection against prompt injection and human review for high-stakes decisions.
- Plan for production: pin model versions, plan for retirement, manage quotas with retries and queues, consider reserved capacity and batch mode, and monitor operations and answer quality together.
- Control cost and stay current: choose the smallest model that passes your tests, trim prompts, cache and batch, set budgets and limits, and always check Google’s latest documentation, because models, features, limits and prices change often.