
Gemini API and Model Garden on Vertex AIAuthorCloudBrum editorial teamLast reviewedReading time~12 minLevelBeginner to advanced
Google Cloud · Generative AI on Vertex AI (now the Gemini Enterprise Agent Platform) · Gemini, partner and open models
On Google Cloud, the service that does the job of Amazon Bedrock and Microsoft Foundry is the Gemini API and Model Garden on Vertex AI. Google renamed Vertex AI the Gemini Enterprise Agent Platform in April 2026, yet the API host is still aiplatform.googleapis.com, the IAM roles still say aiplatform, and people still call it Vertex AI. This page covers the hosted-model side: calling Gemini, and partner and open models such as Claude and Llama from Model Garden, then grounding, safety, quotas and cost. Training and serving your own models is the job of the machine learning platform page. The surprise for most teams is a 429 error on a pay-as-you-go call at low traffic, because that capacity is shared.
On this page (17 sections)
Mind map: Gemini API and Model Garden at a glance
Free to share. The downloaded image includes the CloudBrum link.
Key features (summary)
- A catalogue with three kinds of modelModel Garden lists Google’s Gemini and other Google models, partner models such as Claude, Llama and Mistral, and open models. You try them in the console, call them, tune some of them or deploy some to your own endpoint.
- The Gemini API on Google CloudSend text, images, audio, video or documents to generateContent, stream the answer, and count tokens before you send. It looks like the Gemini Developer API, but you sign in with IAM instead of an API key and you choose the Region.
- Managed calls or your own machinesPartner and some open models run as managed APIs that bill per token. You can also deploy an open model to an endpoint on GPUs you choose, which bills by the node-hour and makes you the operator.
- Grounding in search or in your dataGround an answer in Google Search, or in your own documents through Vertex AI Search or RAG Engine. Each grounded request is metered, and the answer can carry its sources.
- Safety settings and Model ArmorBuilt-in safety settings block harmful output by category. Model Armor screens prompts and answers for injection, jailbreak attempts, harmful content and sensitive data, and works with the Gemini API.
- Agents with ADK and Agent EngineThe Agent Development Kit is the open framework for writing agents with tools. Agent Engine is the managed runtime that hosts them, with sessions and memory.
- Shared capacity or reserved capacityPay-as-you-go calls draw on a shared pool with no fixed limit, so a busy pool means 429 errors. Provisioned Throughput reserves capacity in GSUs for a week up to a year, and Batch and Flex trade speed for a lower price.
- Caching and tuningContext caching bills a repeated long prompt at a fraction of the normal input rate. Supervised tuning adapts a Gemini model to your examples without running training machines yourself.
Basic concepts
- Gemini API on Vertex AI
- The generateContent family of calls on aiplatform.googleapis.com, used with IAM credentials and a Region. The Gemini Developer API is a separate service with API keys.
- Model Garden
- The catalogue of Google, partner and open models, with a card for each that shows how to call, tune or deploy it.
- Publisher model
- A model offered by Google or a partner, named in the URL, as in publishers/google/models/gemini-2.5-flash.
- Managed API (model as a service)
- A partner or open model that Google runs for you and bills per token, with nothing to deploy.
- Self-deployed model
- An open model you deploy from Model Garden to your own endpoint on chosen machines, billed by the node-hour.
- Google Gen AI SDK
- The google-genai library. Setting vertexai=True with a project and location points it at Vertex AI instead of the Developer API.
- Global and regional endpoints
- A regional endpoint such as asia-south1 keeps processing in that Region. The global endpoint gives more capacity but doesn’t say where the request runs.
- Dynamic shared quota
- Pay-as-you-go capacity shared by all customers. There is no per-project cap, and a 429 means the pool is busy.
- Provisioned Throughput
- Reserved capacity measured in GSUs, bought for a period from a week to a year.
- Context caching
- Storing a long, repeated part of the prompt once, so later calls pay a lower rate for it and finish sooner.
- Grounding
- Tying an answer to Google Search results or to your own data, and returning the sources.
- Safety settings
- Per-category thresholds that block harmful prompts or answers. A blocked answer ends with the finish reason SAFETY.
- Model Armor
- A screening service for prompts and answers, set up as a template and attached to calls.
- Agent Engine
- The managed runtime for agents built with the Agent Development Kit or other frameworks.
How to create & configure it
Call Gemini on Vertex AI as a service account, then add safeguards, with gcloud and curl
- Pick a project and turn on the APIUse a project with billing attached and enable aiplatform.googleapis.com. Add modelarmor.googleapis.com if you plan to screen prompts.
- Choose where requests runA regional endpoint such as Mumbai (asia-south1) keeps processing in that Region, if the model is offered there. Delhi (asia-south2) is a listed Region for machine learning services, but check the model’s page before relying on it for Gemini. The global endpoint has more capacity and no location promise.
- Create an identity with the least it needsMake a service account and give it roles/aiplatform.user. The application runs as that account, so there is no key to store.
- Enable partner models if you want themModels such as Claude are switched on for a project from their Model Garden card, which accepts the provider’s terms. The person who enables one needs a role that can purchase from Marketplace, and callers need the Vertex AI user role. Gemini needs no such step.
- Make a first callUse curl or the Python SDK with a small maxOutputTokens. Read the finish reason and the usage numbers, so you see why it ended and what it used.
- Add safeguardsSet safety thresholds for your use, create a Model Armor template for injection and sensitive data, and add grounding only where answers must cite sources.
- Plan for 429 responsesRetry with truncated exponential backoff and jitter, ramp traffic up gradually, try the global endpoint, ask for a quota increase where the model has quotas, and buy Provisioned Throughput if you need a firm level.
- Watch and cap spendSet a budget alert, chart invocation counts and errors in Cloud Monitoring, and turn on request-response logging only if you need it and have somewhere safe to keep it.
- Add your data and agents lastBring in Vertex AI Search or RAG Engine and the Agent Development Kit after the plain call works. Both bring extra cost, new permissions and new ways to break.
Tip: keep one set of real questions with the answers you expect, and run it each time you change the model, the prompt or the endpoint. Model names change often, so make the model a setting, not a constant. See the code references for the same setup as Terraform.
Common issues after configuration
| Symptom | Likely cause | What to check / fix |
|---|---|---|
| 403 PERMISSION_DENIED on aiplatform.endpoints.predict | The caller lacks the Vertex AI user role, the API isn’t enabled, or the client points at another project | Grant roles/aiplatform.user to the account that makes the call, enable the API, and check the project in the client. |
| 404: publisher model not found, or you don’t have access | The model name is wrong, the model isn’t offered in that Region, or a partner model isn’t enabled for the project | Copy the model ID from its Model Garden card, try the global endpoint, and enable partner models from their card. |
| 429 RESOURCE_EXHAUSTED at low traffic | The shared pay-as-you-go pool is busy, or traffic rose too sharply | Retry with backoff and jitter, ramp up gradually, use the global endpoint, request quota if the model has one, or move to Provisioned Throughput. |
| The answer ends with finish reason MAX_TOKENS, sometimes with no text | The limit is small, and models that think before they answer spend part of it on thinking | Raise maxOutputTokens, or lower the thinking budget where the model allows it, so the answer has room. |
| The answer is empty with finish reason SAFETY | A safety setting or the prompt’s content triggered a block | Read the safety ratings in the response, change the prompt, or adjust thresholds you are allowed to change, and test again. |
| A sample from a tutorial fails on import | Samples use the retired vertexai.generative_models module or the product’s earlier name | Use google-genai with vertexai=True, and match names in the docs, which now say Agent Platform in many places. |
| It works in AI Studio but not on Vertex AI | The two services have different hosts, sign-in and quotas | Switch the client to vertexai=True with a project and location, replace the API key with ADC or a service account, and check IAM. |
| The model is missing in your Region | Not every model is served from every Region | Check the model’s Regions, use the global endpoint, or pick a model that your Region offers. |
| Data location doesn’t match your policy | The call used the global endpoint, or a feature in preview isn’t covered by the Region commitment | Use a regional endpoint, read the data residency page for your model and feature, and keep preview features out of regulated flows. |
| The bill is higher than expected | Long prompts and histories, grounded requests, a self-deployed endpoint left running, or Provisioned Throughput not in use | Chart token counts, cache repeated prompt starts, count grounded queries, undeploy test endpoints and review your commitments. |
| Calls fail only from a private network | Private Google Access or Private Service Connect isn’t set up for the API host | Route aiplatform.googleapis.com through Private Service Connect or Private Google Access and check DNS. |
Use cases: when and where to use it
Good fit
- Applications that call Gemini and want IAM, Regions and billing under one Google Cloud project
- Teams that want Gemini and also Claude, Llama or Mistral behind one project and one set of controls
- Multimodal tasks such as reading documents, images, audio or video
- Answers that must cite Google Search or company documents
- Prototypes that grow into production without changing the SDK
- Overnight batch work at a lower price
Consider something else
- Training and serving your own models, pipelines and MLOps → the Gemini Enterprise Agent Platform (Vertex AI) machine learning page
- Predicting from tables that already sit in BigQuery → BigQuery ML, which trains inside the warehouse
- A fixed task such as reading forms or transcribing calls → the Google Cloud AI APIs, which suit it better than a general model
- Searching your documents without writing model code → Vertex AI Search
- A quick prototype with an API key and a free tier → the Gemini Developer API in AI Studio, then move to Vertex AI for production controls
- The same job on other clouds → compare Amazon Bedrock and Microsoft Foundry
Pros: why consider it?
Why teams choose it
- IAM, VPC controls, Regions and billing are the Google Cloud ones you already use
- Gemini, partner models and open models are reachable from one project
- Multimodal input and long context are first-class
- The same SDK serves the Developer API and Vertex AI, so a prototype moves over easily
- Grounding in Google Search and in your data is built in
- Several price modes: shared pay as you go, Provisioned Throughput, Batch, Flex and Priority
Trade-offs to weigh
- The platform was renamed in 2026, so docs, consoles and blog posts disagree on what to call things
- Pay-as-you-go capacity is shared, and 429 errors can appear at low use
- The global endpoint gives no promise about where a request runs
- Model names, versions and Regions change quickly, and older ones are retired
- Preview features may sit outside data residency commitments
- Grounding, caching and tiers add meters, so the bill has several parts
Common threats, vulnerabilities & risks
| Risk | Severity | Why it matters | Mitigation |
|---|---|---|---|
| Prompt injection through documents and web results | High | Grounded web results and uploaded files can hide instructions that the model may follow. | Screen with Model Armor, keep tools narrow, and ask a person to approve actions that change things. |
| An overpowered service account | High | An app account with the Editor role can reach far more than the model. | Give the app roles/aiplatform.user only, with other roles scoped to the data it needs. |
| API keys or user credentials used in production | High | Keys leak, and user credentials stop working when people leave. | Use service accounts with workload identity, and keep keys for prototypes. |
| Sensitive data in prompts, caches and logs | Medium | Prompts hold personal details, and request-response logs and caches keep copies. | Screen sensitive data, use a short retention period, restrict log access and read the data governance page. |
| Requests leave the Region you expected | Medium | The global endpoint and some preview features don’t carry a location commitment. | Use a regional endpoint for regulated data and check each feature’s residency status. |
| No spending limit | Medium | A runaway retry loop or an open endpoint can burn through a month of budget in one night. | Set budgets and alerts, cap maxOutputTokens, rate-limit users and watch invocation metrics. |
| Confident wrong answers | Medium | A model can say something false in a calm tone. | Ground answers, show sources, test with questions whose answers you know and keep a person in the loop for decisions. |
| Self-deployed endpoints left running | Low–Med | A GPU endpoint bills by the node-hour whether or not anyone calls it. | Label endpoints with an owner, undeploy test ones the same day and review the list weekly. |
| A model is retired or changed | Low–Med | Google retires older model versions on a schedule, and the replacement can behave differently. | Make the model a setting, keep your test questions and plan the move early. |
Performance optimisation
- Start from a Flash-class model and move up only when your own tests demand it. It answers sooner and costs less.
- Stream the answer so people see text at once.
- Put the long, unchanging part of a prompt first and use context caching for it.
- Set maxOutputTokens to what you need, and allow for thinking tokens on models that think.
- Use the global endpoint when capacity matters more than location, and a regional one when it doesn’t.
- Send offline work to Batch.
- Spread traffic evenly, since sharp rises can trigger limits that a steady ramp avoids.
- Ground with fewer, better sources, and test retrieval on its own.
Reduce monthly cost
FinOps is the habit of managing cloud spend together with engineering. These are the FinOps checks that matter most for Gemini API and Model Garden.
- Try a Flash-class model before a larger one, and measure cost per correct answer.
- Use Batch or Flex for work that can wait, at about half the standard price.
- Turn on context caching for long repeated prompts, where cached input costs a fraction of normal input.
- Shorten chat history and grounded context. Whatever you send again is billed again.
- Cap output length, and count tokens before sending large inputs.
- Count grounded requests. Each search query used for grounding is metered separately.
- Compare Provisioned Throughput with your measured tokens before committing, since it bills whether or not you call.
- Undeploy self-deployed endpoints the same day, because they bill by the node-hour.
- Watch model price changes and introductory rates, which can end on a published date.
- Set a budget alert, label resources by team and review spend weekly.
Google's rates depend on the model, the input type, the prompt length and the mode, and several sources disagreed, so the numbers are left to the live price list (see Pricing).
Security optimisation
- Run apps as service accounts with roles/aiplatform.user, and avoid keys.
- Use Private Service Connect or Private Google Access so calls stay off the public internet, and add VPC Service Controls where data rules demand it.
- Screen prompts and answers with Model Armor, and set safety thresholds that fit your use.
- Use regional endpoints for regulated data, and read the data residency page for each model and feature.
- Use customer-managed encryption keys for tuning data and stored artifacts where you need them.
- Keep request-response logging off unless needed, and protect and expire what it writes.
- Send Cloud Audit Logs to a protected project and alert on changes to IAM, endpoints and Model Armor templates.
- Run each agent and tool under a narrow service account of its own, and validate the inputs a tool gets.
- Use organisation policy to limit locations and who may enable partner models.
- Read the license and data terms of any partner or open model before a project turns it on.
Governance & compliance
Guardrails
- A shared Terraform module that enables the APIs, creates the service account with one role, a Model Armor template, a budget and an alert
- An organisation policy that limits locations and the partner models a project may enable
- A short register of allowed models, each with an owner, a data class and a review date
- A regression set of questions kept beside the code and replayed whenever the model, the endpoint or the prompt changes
Continuous checks (Cloud Audit Logs, Cloud Monitoring and your own scripts)
- A scheduled script that lists projects calling models without Model Armor or from the global endpoint
- An alert on failed model calls and on sharp rises in invocation counts
- An audit log alert for IAM changes, new endpoints and partner model enablement
- A weekly report of spend by model and by team
- A list of models in use that Google has scheduled for retirement
Cloud Audit Logs show who changed a project and, once you turn on Data Access logs, who called the APIs. Cloud Monitoring holds the invocation metrics, and Assured Workloads and the compliance reports describe the controls Google offers. Google runs the hosting of its models. What stays with you: the model you pick, what goes into prompts, who has access, the safety thresholds and the testing.
Reduce carbon footprint
- Try a Flash-class model before a larger one: it needs less hardware for each answer.
- Cache a long repeated prefix so later calls skip that work.
- Run bulk work through Batch, so each request is not a separate call.
- Undeploy idle endpoints and delete unused Provisioned Throughput.
- Google publishes carbon data for its Regions, so use it to choose when location rules leave you a choice.
- Google publishes no per-request energy figure for hosted models that we could verify, so none appears here.
Pricing
Purchase options
Pay as you go Per token
Input and output tokens at a rate set for each model, with different rates by input type and sometimes by prompt length. It draws on shared capacity with no fixed limit.
Batch and Flex About half the standard price
Batch jobs and latency-tolerant Flex calls cost roughly half of standard on models that offer them. Priority costs more and gives faster, steadier service.
Provisioned Throughput Per GSU, for a term
Reserved capacity in GSUs for a period from a week to a year. You pay for the term whether or not you call.
Caching and grounding Cached input is cheaper
Cached input bills at a fraction of the normal input rate. On newer Gemini models each Google Search grounding query is charged on top, and older ones bill per grounded prompt.
Partner and open models Set by the model
Managed partner models bill per token at their provider’s rate, and self-deployed open models bill by the node-hour for the machines.
What you actually pay for
- Input and output tokens for every call, including thinking tokens on models that think
- Provisioned Throughput for its whole term
- Grounding queries, caching storage and tuning jobs
- Node-hours for self-deployed endpoints, and a partner model’s own fee
- Cloud Logging, BigQuery for request logs, Model Armor and data transfer
Google lists the rates for each model and mode on its pricing page, and some introductory rates end on a set date. See the official Vertex AI generative AI pricing page and the Google Cloud Pricing Calculator.
Important code references
A first Gemini setup on Vertex AI: turn on the API, create a service account with one role, list models in Model Garden, send a question and count tokens with curl, create a Model Armor template and set a budget alert. The gcloud tab walks through it in order. Terraform builds the same resources plus an alert on failed calls. The Python tab uses the Google Gen AI SDK with retries for 429 responses, streaming and token counting, and the C# tab sends a counted, limited question and exits with 1 when a safety setting blocks the answer. Replace the project, the Region and the model with your own.
# Placeholders: use your own project, and a Gemini model that the Region offers (check the Model Garden card for the exact ID).
PROJECT_ID=my-project
LOCATION=asia-south1 # Mumbai. Use "global" for the most capacity, but then Google picks where the request runs.
MODEL=gemini-2.5-flash
API=https://$LOCATION-aiplatform.googleapis.com
[ "$LOCATION" = global ] && API=https://aiplatform.googleapis.com
# 1. Turn on the API, and Model Armor if you want prompt screening.
gcloud services enable aiplatform.googleapis.com modelarmor.googleapis.com --project $PROJECT_ID
# 2. An identity for the app with only the Vertex AI user role. No keys: the app runs as this service account.
gcloud iam service-accounts create gemini-app --project $PROJECT_ID --display-name "Gemini caller"
gcloud projects add-iam-policy-binding $PROJECT_ID --member "serviceAccount:gemini-app@$PROJECT_ID.iam.gserviceaccount.com" --role roles/aiplatform.user
# 3. What does Model Garden offer? Narrow the list with a filter on the name.
gcloud ai model-garden models list --model-filter gemini --limit 20
# 4. Ask Gemini a question. The model name is part of the URL, and maxOutputTokens limits the answer.
curl -s -X POST "$API/v1/projects/$PROJECT_ID/locations/$LOCATION/publishers/google/models/$MODEL:generateContent" \
-H "Authorization: Bearer $(gcloud auth print-access-token)" -H "Content-Type: application/json" \
-d '{"systemInstruction":{"parts":[{"text":"Answer in at most three sentences."}]},
"contents":[{"role":"user","parts":[{"text":"What is the difference between the Gemini API and Model Garden?"}]}],
"generationConfig":{"maxOutputTokens":400,"temperature":0.2}}' \
| jq '{answer: .candidates[0].content.parts[0].text, finish: .candidates[0].finishReason, tokens: .usageMetadata}'
# 5. Count the tokens of a prompt before you send it, to check cost and the context window.
curl -s -X POST "$API/v1/projects/$PROJECT_ID/locations/$LOCATION/publishers/google/models/$MODEL:countTokens" \
-H "Authorization: Bearer $(gcloud auth print-access-token)" -H "Content-Type: application/json" \
-d '{"contents":[{"role":"user","parts":[{"text":"A long prompt you want to measure."}]}]}' | jq .totalTokens
# 6. A Model Armor template that screens for prompt injection and jailbreaks, and for harmful content. Attach it to calls from your app.
gcloud model-armor templates create gemini-guard --project $PROJECT_ID --location $LOCATION \
--pi-and-jailbreak-filter-settings-enforcement enabled --pi-and-jailbreak-filter-settings-confidence-level medium-and-above \
--rai-settings-filters '[{"filterType":"HATE_SPEECH","confidenceLevel":"MEDIUM_AND_ABOVE"},{"filterType":"DANGEROUS","confidenceLevel":"MEDIUM_AND_ABOVE"}]' \
--basic-config-filter-enforcement enabled
# 7. A budget alert on the billing account, so a loop or a leaked credential shows up at 50 and 90 percent.
gcloud billing budgets create --billing-account 000000-AAAAAA-BBBBBB --display-name "Gemini spend" \
--filter-projects "projects/$PROJECT_ID" --budget-amount 100USD --threshold-rule percent=0.5 --threshold-rule percent=0.9
# Placeholders: set your project and billing account. This enables the APIs, creates an identity for the app with only the Vertex AI user role,
# a Model Armor template, a budget alert and an alert on failed model calls.
variable "project_id" {
type = string
}
variable "billing_account" {
type = string
description = "Billing account ID, for example 000000-AAAAAA-BBBBBB"
}
variable "region" {
type = string
default = "asia-south1"
}
provider "google" {
project = var.project_id
region = var.region
}
resource "google_project_service" "apis" {
for_each = toset(["aiplatform.googleapis.com", "modelarmor.googleapis.com", "monitoring.googleapis.com"])
service = each.key
disable_on_destroy = false
}
# The app runs as this service account. There are no keys to leak.
resource "google_service_account" "gemini_app" {
account_id = "gemini-app"
display_name = "Gemini caller"
}
resource "google_project_iam_member" "can_call_models" {
project = var.project_id
role = "roles/aiplatform.user"
member = "serviceAccount:${google_service_account.gemini_app.email}"
}
# Screens prompts and answers for injection and jailbreak attempts and for harmful content. The app names this template in its calls.
resource "google_model_armor_template" "guard" {
location = var.region
template_id = "gemini-guard"
filter_config {
pi_and_jailbreak_filter_settings {
filter_enforcement = "ENABLED"
confidence_level = "MEDIUM_AND_ABOVE"
}
rai_settings {
rai_filters {
filter_type = "HATE_SPEECH"
confidence_level = "MEDIUM_AND_ABOVE"
}
rai_filters {
filter_type = "DANGEROUS"
confidence_level = "MEDIUM_AND_ABOVE"
}
}
}
depends_on = [google_project_service.apis]
}
data "google_project" "this" {
project_id = var.project_id
}
resource "google_billing_budget" "gemini" {
billing_account = var.billing_account
display_name = "Gemini spend"
budget_filter {
projects = ["projects/${data.google_project.this.number}"]
}
amount {
specified_amount {
currency_code = "USD"
units = "100"
}
}
threshold_rules {
threshold_percent = 0.5
}
threshold_rules {
threshold_percent = 0.9
}
}
# Model calls that did not return 200. The metric and its labels are as in Metrics Explorer; check them there for your model.
resource "google_monitoring_alert_policy" "failed_calls" {
display_name = "Gemini calls failing"
combiner = "OR"
conditions {
display_name = "More than 20 failed calls in 5 minutes"
condition_threshold {
filter = "resource.type = \"aiplatform.googleapis.com/PublisherModel\" AND metric.type = \"aiplatform.googleapis.com/publisher/online_serving/model_invocation_count\" AND metric.labels.response_code != \"200\""
comparison = "COMPARISON_GT"
threshold_value = 20
duration = "300s"
aggregations {
alignment_period = "300s"
per_series_aligner = "ALIGN_SUM"
}
}
}
depends_on = [google_project_service.apis]
}
output "service_account" {
value = google_service_account.gemini_app.email
}
# pip install google-genai
# Calls Gemini on Vertex AI as the identity you are logged in with (no API key), retries when the shared pool is busy,
# streams an answer, and counts tokens before sending. Run `gcloud auth application-default login` first, or run on Google Cloud with a service account.
import os
import random
import time
from google import genai
from google.genai import errors, types
PROJECT = os.environ["GOOGLE_CLOUD_PROJECT"]
LOCATION = os.environ.get("GOOGLE_CLOUD_LOCATION", "asia-south1") # "global" gives the most capacity but no promise about where requests run
MODEL = os.environ.get("GEMINI_MODEL", "gemini-2.5-flash")
client = genai.Client(vertexai=True, project=PROJECT, location=LOCATION)
def ask(question, system="Answer in at most three sentences.", max_output_tokens=400, attempts=6):
"""Returns (text, finish_reason, usage). Retries 429, 500 and 503 with truncated exponential backoff and jitter, as Google advises for a busy shared pool."""
config = types.GenerateContentConfig(system_instruction=system, max_output_tokens=max_output_tokens, temperature=0.2)
for attempt in range(attempts):
try:
reply = client.models.generate_content(model=MODEL, contents=question, config=config)
finish = reply.candidates[0].finish_reason if reply.candidates else None
return reply.text, finish, reply.usage_metadata
except errors.APIError as error:
if error.code not in (429, 500, 503) or attempt == attempts - 1:
raise
time.sleep(min(2 ** attempt, 32) + random.random())
def ask_streaming(question, max_output_tokens=400):
"""Streams the answer to the console and returns it as one string."""
pieces = []
config = types.GenerateContentConfig(max_output_tokens=max_output_tokens)
for chunk in client.models.generate_content_stream(model=MODEL, contents=question, config=config):
if chunk.text:
print(chunk.text, end="", flush=True)
pieces.append(chunk.text)
print()
return "".join(pieces)
def tokens(question):
"""How many tokens the prompt uses, before you pay for an answer."""
return client.models.count_tokens(model=MODEL, contents=question).total_tokens
if __name__ == "__main__":
text, finish, usage = ask("What is the difference between the Gemini API and Model Garden?")
print(text)
print("finish:", finish, "| tokens in/out:", usage.prompt_token_count, usage.candidates_token_count)
if str(finish).endswith("MAX_TOKENS"):
print("The answer was cut off. Models that think first spend part of the limit on thinking, so raise max_output_tokens.")
elif str(finish).endswith("SAFETY"):
print("A safety setting stopped this answer.")
// dotnet add package Google.Cloud.AIPlatform.V1
// Sends one question to Gemini on Vertex AI as the identity from Application Default Credentials, counts the tokens first,
// and reports why the answer ended. Exits with 1 when a safety setting blocked it, so a pipeline can notice.
using Google.Cloud.AIPlatform.V1;
string project = Environment.GetEnvironmentVariable("GOOGLE_CLOUD_PROJECT") ?? throw new InvalidOperationException("Set GOOGLE_CLOUD_PROJECT");
string location = Environment.GetEnvironmentVariable("GOOGLE_CLOUD_LOCATION") ?? "asia-south1";
string model = Environment.GetEnvironmentVariable("GEMINI_MODEL") ?? "gemini-2.5-flash";
string modelName = $"projects/{project}/locations/{location}/publishers/google/models/{model}";
// A regional endpoint keeps the call in that Region. For the "global" location the host is plain aiplatform.googleapis.com.
string host = location == "global" ? "aiplatform.googleapis.com" : $"{location}-aiplatform.googleapis.com";
PredictionServiceClient client = new PredictionServiceClientBuilder { Endpoint = host }.Build();
LlmUtilityServiceClient utility = new LlmUtilityServiceClientBuilder { Endpoint = host }.Build();
var contents = new List<Content>
{
new Content { Role = "USER", Parts = { new Part { Text = "What is the difference between the Gemini API and Model Garden?" } } }
};
CountTokensResponse counted = await utility.CountTokensAsync(new CountTokensRequest { Endpoint = modelName, Model = modelName, Contents = { contents } });
Console.WriteLine($"prompt tokens: {counted.TotalTokens}");
GenerateContentResponse reply = await client.GenerateContentAsync(new GenerateContentRequest
{
Model = modelName,
SystemInstruction = new Content { Parts = { new Part { Text = "Answer in at most three sentences." } } },
Contents = { contents },
GenerationConfig = new GenerationConfig { MaxOutputTokens = 400, Temperature = 0.2f }
});
Candidate? first = reply.Candidates.FirstOrDefault();
Console.WriteLine(first?.Content?.Parts.FirstOrDefault()?.Text ?? "(no text)");
Console.WriteLine($"finish: {first?.FinishReason} | tokens in/out: {reply.UsageMetadata?.PromptTokenCount}/{reply.UsageMetadata?.CandidatesTokenCount}");
if (first?.FinishReason == Candidate.Types.FinishReason.Safety)
{
Console.WriteLine("A safety setting blocked this answer.");
return 1;
}
if (first?.FinishReason == Candidate.Types.FinishReason.MaxTokens)
{
Console.WriteLine("The answer was cut off. Models that think first spend part of the limit on thinking, so raise MaxOutputTokens.");
}
return 0;
Best videos to explore
Videos picked for this service. Each one is labelled with its source, opens on YouTube if you prefer, and loads only when you press play.
Interview questions
BasicWhat is the Gemini API on Vertex AI?
It’s Google Cloud’s way to call Gemini models from your own applications. You send text, images, audio or documents to the generateContent call on aiplatform.googleapis.com, sign in with IAM instead of an API key, and pick the Region. It is the same family of models as in Google AI Studio, with enterprise controls around it.
BasicWhat is Model Garden?
It’s the catalogue of models on the platform. It lists Google’s Gemini and other Google models, partner models such as Claude, Llama and Mistral, and open models. Each card shows how to try the model, call it, tune it or deploy it.
BasicDid Google rename Vertex AI?
Yes. Google announced the new name in April 2026 and added agent tooling on top, while the earlier features carried on. The API host, the IAM roles and the Python package names still say Vertex AI or aiplatform, so older and newer material describes the same service.
IntermediateHow does this compare with the Gemini Developer API?
The Developer API uses generativelanguage.googleapis.com, an API key and a free tier, and suits prototypes. The Vertex AI version uses aiplatform.googleapis.com, IAM, Regions, VPC controls and enterprise commitments. The same Google Gen AI SDK serves both, so a prototype moves over by changing how the client is created.
IntermediateWhy does Gemini return 429 RESOURCE_EXHAUSTED when I am barely using it?
Pay-as-you-go calls use a shared pool with no per-project limit. When many customers call at once the pool is busy and you can see 429 RESOURCE_EXHAUSTED even at low use. Retry with exponential backoff and jitter, ramp traffic up gradually, try the global endpoint, and buy Provisioned Throughput if you need a firm level.
IntermediateRegional or global endpoint?
A regional endpoint such as asia-south1 keeps processing in that Region for models and features that support it. The global endpoint gives more capacity but makes no promise about where the request runs. Use regional for regulated data, and global when capacity matters and the data rules allow it.
AdvancedHow would you design a safe, grounded assistant on Google Cloud?
Put the model behind your own API with authentication and per-user limits, call Gemini as a service account from a regional endpoint, and screen prompts and answers with Model Armor. Ground answers in Vertex AI Search or RAG Engine with citations, give agents narrow tools under their own identities, cap output, alert on failed calls and spend, and keep a test set you rerun after every change.
AdvancedWhen is Provisioned Throughput worth it?
When traffic is steady and heavy enough that the reserved capacity costs less than tokens, or when you need a firm service level that shared capacity can’t give. Measure real tokens per minute first, size the GSUs from that, remember it bills for the whole term, and keep pay-as-you-go as an overflow path.
AdvancedWhat drives the Gemini bill, and how do you bring it down?
Tokens in and out dominate, then grounded requests, Provisioned Throughput and any self-deployed GPU endpoint. Start by sending less: shorter history, cached prefixes, a smaller model. Move bulk work to Batch or Flex, undeploy test endpoints, and chart spend by feature so you can see which one grew.
AdvancedWhat is a safe way to move from one Gemini model to the next?
Because model names are a setting, you can run the new one beside the old. Replay a saved question set against both, compare accuracy, refusals, safety blocks, length and cost, then send a small share of live traffic to the new model while you watch errors and safety metrics. Keep the previous model name in config so you can switch back.
Similar or alternative services on other clouds
| Capability | AWS | Azure | Google Cloud |
|---|---|---|---|
| Service | Amazon Bedrock | Microsoft Foundry (formerly Azure AI Foundry), with Foundry Models | Gemini API and Model Garden on Vertex AI (now the Gemini Enterprise Agent Platform) |
| Chat model API | Converse and InvokeModel | Responses and chat completions APIs on a deployment | Gemini API (generateContent) through the Google Gen AI SDK |
| Model choice | Amazon, Anthropic, Meta, Mistral AI, DeepSeek, OpenAI and others | Models sold by Azure, plus partner and community models | Gemini, partner models such as Claude, and open models |
| Your own data (RAG) | Knowledge Bases | Foundry IQ and Azure AI Search | RAG Engine and Vertex AI Search |
| Safety filters | Guardrails and ApplyGuardrail | Content filters and Prompt Shields | Safety settings and Model Armor |
| Agents | Agents and AgentCore | Foundry Agent Service | Agent Engine and the Agent Development Kit |
| Reserved capacity | Provisioned Throughput (model units) | Provisioned throughput (PTUs) | Provisioned Throughput (GSUs) |
| Spread over Regions | Inference profiles, geographic or global | Global Standard and Data Zone deployments | Global endpoint or a regional endpoint |
| Typical identity | IAM roles | Microsoft Entra ID roles | IAM service accounts |
Typical companions are Cloud Storage for documents, Cloud Run functions for glue code, Cloud Monitoring for metrics and alerts and Cloud KMS for keys. To train, tune with your own code or host a model of your own, look at the Gemini Enterprise Agent Platform (Vertex AI) machine learning page.
Did you find this article helpful?
Your answer helps us improve this page for the next reader.
Sources and further reading
CloudBrum wrote this page in its own words, using the provider’s public documentation listed below as the reference. Features, limits, names and prices change, so confirm anything that matters on the provider’s own pages before you decide.
- Generative AI on Vertex AI: documentation overviewGoogle Cloud
- Model Garden on the Gemini Enterprise Agent PlatformGoogle Cloud
- Get started with the Gemini API in Vertex AIGoogle Cloud
- Google Gen AI SDKGoogle Cloud
- Migrate from the Gemini Developer API to the Gemini API in Vertex AIGoogle Cloud
- Throughput quota and dynamic shared quotaGoogle Cloud
- Error code 429Google Cloud
- Data residency for generative AIGoogle Cloud
- Locations for machine learning servicesGoogle Cloud
- Generative AI pricingGoogle Cloud
