Agent Platform Inference

Agent Platform Inference

Teaches an AI agent to authenticate and run inference against Gemini and open models on Google Cloud, and to fix 429, 400 and 404 errors.

Skill files10 files

references/

scripts/

SKILL.md851 lines
1
---
2
name: agent-platform-inference
3
metadata:
4
version: "1.0.2"
5
category: AiAndMachineLearning
6
description: >-
7
Connects to and performs inference with Google Cloud Agent Platform GenAI
8
models, including First-Party Gemini models and Third-Party OpenMaaS models
9
(Llama, DeepSeek, Qwen, etc.). Use when asked to perform inference, ask a
10
model a question, run a test prompt, execute chat completions, or generate
11
code for calling Gemini or OpenMaaS models, authenticate with GenAI SDK,
12
OpenAI SDK, or legacy Agent Platform SDK, configure base URLs and
13
global/regional endpoints, or troubleshoot 429 Resource Exhausted (DSQ), 400
14
User Validation, or 404 Not Found errors. Don't use for deploying models to
15
endpoints or for running model evaluations.
16
---
17
18
# Agent Platform GenAI Inference Skill
19
20
This skill provides instructions for authenticating and connecting to Google
21
Cloud Agent Platform to use Generative AI models. It covers:
22
23
* **First-Party publisher models** (Gemini) — section 2.
24
* **Third-Party publisher models** (OpenMaaS: Llama, DeepSeek, Qwen, etc.)
25
— section 3.
26
* **Custom endpoints** (any model on a numeric `projects/.../endpoints/<id>`
27
resource — tuned Gemini models, OSS LLMs self-deployed from Model Garden
28
via the `agent-platform-deploy` skill, and legacy custom models) —
29
section 4.
30
31
## Attribution
32
33
**MUST READ**: Before executing any `gcloud`, REST API, or MCP command, you MUST
34
read [Usage Attribution](references/attribution.md). For commands executed
35
directly in the terminal (never in generated scripts, Terraform, or user code),
36
prefix `gcloud` with `CLOUDSDK_METRICS_REQUEST_ATTRIBUTION` and append the
37
attribution suffix to `User-Agent` headers:
38
39
```text
40
CLOUDSDK_METRICS_REQUEST_ATTRIBUTION="agent-skills/1.0 (skill:agent-platform-inference)"
41
User-Agent: <existing_user_agent> agent-skills/1.0 (skill:agent-platform-inference)
42
```
43
44
## Safety & Confirmation Tiers (CRITICAL)
45
46
Before executing any commands or scripts on behalf of the user, you must adhere
47
to the following safety tiers based on the action requested. (The skill is
48
read-only; other safety tiers are omitted):
49
50
1. **Tier R: Read-only / Inference (`client.models.generate_content`,
51
`client.chat.completions.create`, `client.completions.create`,
52
`client.embeddings.create`)**
53
* Requires **interactive confirmation** with 'Yes'/ 'No' options before
54
executing model inference on behalf of the user, to prevent unexpected
55
cost or quota consumption.
56
* **Required Fields in Confirmation Card**: The confirmation prompt must
57
clearly explain the proposed inference execution and explicitly list all
58
of the following parameters:
59
* **Project ID**: The Google Cloud project ID or number (e.g.
60
`123456789012`, `my-project`).
61
* **Region / Location**: The target region (e.g. `us-central1`,
62
`global`).
63
* **Model ID**: The exact model ID (e.g. `gemini-3.8-flash`,
64
`deepseek-ai/deepseek-v3.2-maas`).
65
* **SDK**: The SDK choice (e.g. `Google GenAI SDK (google-genai)`,
66
`OpenAI SDK`).
67
* **Input Prompt** (or **Input Image** / **Input Media**): The prompt
68
text or media URI.
69
* Any additional generation parameters (e.g. `max_output_tokens`,
70
`response_schema`) if specified.
71
Natural-language paraphrases without explicitly listing these
72
parameters are NOT sufficient.
73
* **Same-turn restriction**: Do not execute the inference scripts or
74
commands in the same turn as presenting the confirmation prompt. Stop
75
and wait for the user's reply; only execute after explicit 'Yes' /
76
approval.
77
* **Gold Standard Example**:
78
> I will perform model inference with the following parameters. Please
79
> confirm this information before I proceed:
80
> * **Project ID**: `my-project`
81
> * **Region**: `global`
82
> * **Model ID**: `gemini-4-argon`
83
> * **SDK**: Google GenAI SDK (`google-genai`)
84
> * **Input Prompt**: "Summarize the plot of Hamlet in 3 sentences"
85
>
86
> Do you confirm? [Yes/No]
87
* **Post-Execution Response Grounding (CRITICAL)**:
88
After receiving explicit user approval and executing the inference call
89
via the SDK, the response returning the generated text **MUST
90
explicitly confirm the execution parameters** alongside the model's
91
output. Never return a bare model response alone. Always include:
92
* **Model ID**: The exact model ID used (e.g. `gemini-4-argon`
93
or `<MODEL_ID>`).
94
* **SDK**: The SDK used (e.g. `Google GenAI SDK (google-genai)`
95
or `OpenAI SDK`).
96
* **Project ID**: The Google Cloud project ID/number used.
97
* **Region**: The region or endpoint location used (e.g. `global`
98
or `us-central1`).
99
* **Generated Output**: The model's complete generated answer.
100
101
## Phase 0: Environment Setup
102
103
**CRITICAL**: Before running any of the Python sample scripts in the `scripts/`
104
directory (e.g., `scripts/openmaas_openai_sdk.py`), you MUST ensure the
105
environment is correctly initialized by following these steps:
106
107
1. **Google Cloud Authentication**: Authenticate with your Google Cloud
108
credentials and configure active Application Default Credentials (ADC) for
109
Agent Platform access:
110
111
```bash
112
gcloud auth login
113
gcloud auth application-default login
114
```
115
116
2. **Enable API** (if not already enabled):
117
118
```bash
119
gcloud services enable aiplatform.googleapis.com
120
```
121
122
3. **Python Dependencies**: The scripts import `vertexai` (from
123
`google-cloud-aiplatform`), `google-genai`, and `openai`. Do **not** create
124
a virtual environment — it starts empty and hides packages the environment
125
already provides, forcing a redundant install. Probe, and install only what
126
is missing:
127
128
```bash
129
python3 -c "import vertexai, google.genai, openai" \
130
|| pip install -r scripts/requirements.txt
131
```
132
133
`scripts/requirements.txt` is a fallback for an environment that does not
134
already provide these SDKs; do not install it on top of a working
135
environment.
136
137
4. **Verify Setup (Optional)**: Run all sample scripts at once to verify the
138
environment is working end-to-end:
139
140
```bash
141
./scripts/verify_all.sh
142
```
143
144
5. **Execution**: Run the scripts with a plain `python3 scripts/...`. There is
145
no environment to activate first.
146
147
148
149
> [!IMPORTANT] **CRITICAL: Model IDs & Availability** * **Gemini Models**: See
150
> [Gemini Models][gemini-models-docs] for valid Model IDs and Regions. *
151
> **OpenMaaS Models**: See
152
> [Use Open Models on Agent Platform](https://docs.cloud.google.com/gemini-enterprise-agent-platform/models/maas/use-open-models)
153
> for Llama, DeepSeek, Qwen, etc. * **Incomplete Lists**: The Model IDs listed
154
> in this skill are **examples only** and may be incomplete or outdated. *
155
> **Action**: Always verify the Model ID and Region using the links above before
156
> generating code.
157
>
158
> \[gemini-models-docs]:
159
> https://docs.cloud.google.com/gemini-enterprise-agent-platform/models/migrate
160
>
161
162
## Parameter Grounding & Clarification Protocol (CRITICAL)
163
164
Before preparing code or presenting a Tier R confirmation card, you MUST ensure
165
all necessary parameters are grounded:
166
167
1. **Missing Model ID, Model Family, or SDK (CRITICAL)**:
168
* If the user has **NOT** specified which model or model family to use
169
(e.g., "run a test prompt", "ask a generative AI model to...", "ask
170
DeepSeek a question" without model version), or has not specified the
171
SDK preference:
172
* **NEVER** guess, volunteer, or default to a model (such as
173
`gemini-3.8-flash`, `gemini-4-argon`, or `deepseek-v3.2-maas`).
174
Proposing a defaulted model in a confirmation card without asking
175
violates parameter grounding.
176
* **YOU MUST STOP AND ASK THE USER**: "Which model (or model family,
177
such as Gemini, Llama, DeepSeek, or Qwen) and SDK preference (such as
178
Google GenAI SDK or OpenAI SDK) would you like to use?" and ask for the
179
target region and project ID if not specified.
180
* Only after the user specifies the model (and any missing SDK preference)
181
should you proceed to prepare the execution and present the Tier R
182
confirmation prompt.
183
184
2. **Missing Project ID or Region**:
185
* If the user's project ID or region is not specified in the prompt or
186
conversation context, **ASK** the user for the project ID and region
187
(e.g. "Which project ID and region would you like to use?"). Do not
188
silently assume a project or region.
189
* **OpenMaaS Locations**: OpenMaaS publisher models are hosted on `global`
190
(e.g. `deepseek-ai/deepseek-v3.2-maas`,
191
`meta/llama-3.3-70b-instruct-maas`) or regional endpoints such as
192
`us-central1` (e.g. `deepseek-ai/deepseek-r1-0528-maas`).
193
When configuring inference for OpenMaaS models, use the appropriate
194
endpoint:
195
196
* Global: `https://aiplatform.googleapis.com/v1/projects/{PROJECT_ID}/locations/global/endpoints/openapi`
197
* Regional: `https://{REGION}-aiplatform.googleapis.com/v1/projects/{PROJECT_ID}/locations/{REGION}/endpoints/openapi`
198
199
and explicitly reflect the region in the confirmation card and final
200
response.
201
202
3. **SDK Choice**:
203
* If the user specifies a model but does not specify an SDK, use the
204
preferred SDK for that model family (GenAI SDK `google-genai` for
205
Gemini, OpenAI SDK `openai` for OpenMaaS).
206
207
4. **Sandbox Execution via Python (CRITICAL)**:
208
* When executing model inference in the sandbox via `run_command`,
209
**ALWAYS** run Python code using the official SDKs (e.g., writing and
210
running a Python script with `google-genai`, `openai`, or `vertexai`).
211
Do not use raw curl commands for final inference execution.
212
213
## Workflow Decision Tree
214
215
1. **Model Specified?**
216
* **No** (user omitted model name/family) -> **Ask the user** which model
217
or model family, target region, and SDK preference they want to use.
218
* **Underspecified** (e.g., user said "DeepSeek" or "Llama" without
219
version) -> **Ask the user** which specific model version they prefer
220
(e.g., `deepseek-ai/deepseek-r1-0528-maas`,
221
`deepseek-ai/deepseek-v3.2-maas`, `meta/llama-3.3-70b-instruct-maas`).
222
* **Yes** -> Proceed to Step 2.
223
224
2. **Model Family & SDK Selection**:
225
* **Gemini** (e.g., `gemini-4-argon`, `gemini-3.8-flash`) -> Preferred:
226
**GenAI SDK** (`google-genai`). Proceed to [1. Gemini Models].
227
* **OpenMaaS** (e.g., `deepseek-ai/*`, `meta/llama-*`, `qwen/*`) ->
228
Preferred: **OpenAI SDK** (`openai`). Proceed to [2. OpenMaaS Models].
229
* **Custom Endpoint** (numeric endpoint ID
230
`projects/.../endpoints/<id>`) -> Proceed to [4. Custom Endpoints].
231
232
3. **Troubleshooting**: Is the user reporting an error (429 Resource Exhausted,
233
400 User Validation, 404 Not Found, empty response due to token limits,
234
etc.)?
235
* **Yes** -> Proceed to [5. Troubleshooting & Common Error Codes].
236
* **No** -> Present Tier R confirmation prompt with all required fields
237
(Project ID, Region, Model ID, SDK, Input Prompt), wait for user
238
confirmation, then execute via Python SDK.
239
240
## 0.5 Region Availability Check for Publisher Endpoints (Gemini + LoRA base)
241
242
> [!NOTE] **Skip this section** if either of these applies:
243
>
244
> - The user is calling a custom endpoint (§4) — a tuned Gemini model served on
245
> a numeric `projects/.../endpoints/<id>`, a self-deployed OSS LLM (Llama,
246
> DeepSeek, Qwen, Gemma, etc.), or a legacy custom model. Those requests hit
247
> a specific endpoint resource whose region is fixed at deploy time; if the
248
> caller-side region doesn't match, the endpoint lookup returns a clean 404
249
> without incurring inference cost. Go to §4.
250
> - The user is calling an OpenMaaS publisher model (§2) — Llama, DeepSeek,
251
> Qwen, etc. served via the global `openapi` base URL. These don't have
252
> per-region availability restrictions in the same way first-party Gemini
253
> does. Go to §2.
254
>
255
> **Apply this section** only if the user is calling a first-party managed
256
> Gemini model (`gemini-*`, via §1), including fine-tuned LoRA adapters on
257
> top of Gemini — these route through a publisher endpoint whose regional
258
> availability actually varies.
259
260
Before responding to any inference request that names a specific region for a
261
first-party managed Gemini model (`gemini-*`) or a fine-tuned Gemini LoRA
262
adapter (identified by numeric endpoint ID + user-stated base model), you
263
**MUST** verify the model is actually available in that region by making a
264
live API call. Do not rely on Google Search, training-corpus knowledge, or
265
publisher documentation for availability claims — regional availability
266
changes frequently and grounded text can be stale or wrong.
267
268
Probe only the exact model and region the user asked about. Do not probe other
269
models as a "control" — you cannot infer anything about model A's availability
270
from model B's status, because a different model may itself be unavailable in
271
the reference region for unrelated reasons.
272
273
For first-party Gemini models, probe with a real `:generateContent` call using
274
a minimal valid payload:
275
276
```bash
277
curl -sS -o /dev/null -w "%{http_code}\n" \
278
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
279
-H "Content-Type: application/json" \
280
"https://${LOCATION_ID}-aiplatform.googleapis.com/v1/projects/${PROJECT_ID}/locations/${LOCATION_ID}/publishers/google/models/${MODEL_ID}:generateContent" \
281
-d "{\"contents\":{\"role\":\"user\",\"parts\":{\"text\":\"${PROBE_TEXT:-hi}\"}}}"
282
```
283
284
For inference against a fine-tuned Gemini LoRA adapter, probe the **base
285
model** in the target region using the same `:generateContent` call above with
286
`${MODEL_ID}` set to the base (e.g. `gemini-3.5-flash` if the adapter was
287
tuned on `gemini-3.5-flash`). The LoRA adapter cannot serve in a region where
288
its base model isn't available.
289
290
Interpret the probe result and act:
291
292
- **200** — model is available in that region. Proceed with the SDK setup in
293
§1.
294
- **404** — model is not available in that region. STOP. Tell the user
295
plainly that the model isn't offered in that region and list the regions
296
where it is available (from
297
[Gemini Models][gemini-models-docs] or `gcloud ai model-garden models list
298
--filter="name~$MODEL_NAME"` without `--region`). Do not silently switch
299
regions. Do not proceed to write inference code or SDK initialization for
300
the unsupported region. Do not run additional "control" probes to
301
double-check the 404 — the target-region probe is authoritative.
302
- **Any other outcome** (permission denied, quota, transient failure, etc.)
303
— do not conclude the model is available or unavailable. Explain the
304
underlying cause in plain language (e.g. "your account doesn't have access
305
to this project's Vertex AI API — enable it in the console or switch
306
projects") and the concrete next action.
307
308
## 1. Gemini Models
309
310
For Gemini models (e.g., `gemini-4-argon`, `gemini-3-flash-preview`), the
311
**GenAI SDK** (`google-genai`) is the **PREFERRED** method. The legacy
312
`vertexai` SDK is still supported but GenAI SDK is recommended for new projects.
313
314
> [!IMPORTANT]
315
> **Preview Models (including Gemini 3.1)** are often **ONLY** available in the
316
> `global` region. Stable models are available in `us-central1` and other
317
> regions.
318
319
### Choosing the Right SDK
320
321
* **Gemini Models**: **GenAI SDK** (`google-genai`) is **PREFERRED**. Use
322
OpenAI SDK for compatibility, or Legacy SDK (`vertexai`) if needed.
323
* **OpenMaaS Models**: **OpenAI SDK** is **HIGHLY RECOMMENDED**. Use GenAI SDK
324
or Legacy SDK if you have specific infrastructure requirements.
325
326
### Installation
327
328
```bash
329
pip install google-genai
330
```
331
332
### Python Example (GenAI SDK - Preferred)
333
334
See [`scripts/gemini_genai_sdk.py`](scripts/gemini_genai_sdk.py) for the
335
complete code.
336
337
### Alternative: OpenAI SDK (Chat Completions)
338
339
Use the standard OpenAI SDK with the Agent Platform endpoint. This is great for
340
cross-compatibility.
341
342
See [`scripts/gemini_openai_sdk.py`](scripts/gemini_openai_sdk.py) for the
343
complete code.
344
345
### Legacy: Agent Platform SDK
346
347
The legacy `vertexai` SDK is still widely used but `google-genai` is preferred
348
for new Gemini projects.
349
350
See [`scripts/gemini_vertexai_sdk.py`](scripts/gemini_vertexai_sdk.py) for the
351
complete code.
352
353
**Documentation**:
354
[Google GenAI SDK](https://github.com/googleapis/python-genai)
355
356
**Documentation**:
357
[Agent Platform Gemini Models](https://docs.cloud.google.com/gemini-enterprise-agent-platform/models/google-models)
358
359
## 2. OpenMaaS Models (Llama, DeepSeek, Qwen, etc.)
360
361
For OpenMaaS (Model-as-a-Service) models, the **HIGHLY RECOMMENDED** approach is
362
to use the standard **OpenAI SDK** with a specific Vertex AI endpoint.
363
364
> [!WARNING] While `GenerativeModel` *can* support some OpenMaaS models, it is
365
> **discouraged**. Use the OpenAI SDK for best compatibility (especially for
366
> Chat Completions).
367
368
### Installation
369
370
```bash
371
pip install openai google-auth
372
```
373
374
### Authentication for OpenAI SDK
375
376
You **MUST** use a Google Cloud OAuth access token as the API key for the OpenAI
377
SDK.
378
379
```python
380
import subprocess
381
382
def get_gcp_access_token():
383
return subprocess.check_output(
384
["gcloud", "auth", "print-access-token"]
385
).decode("utf-8").strip()
386
```
387
388
> [!NOTE] Google Cloud access tokens typically expire after 1 hour. The
389
> `get_gcp_access_token()` function above retrieves a *fresh* token at the time
390
> it is called. For long-running
391
> applications, you implement a refresh mechanism. See
392
> [Refresh the access token](https://docs.cloud.google.com/gemini-enterprise-agent-platform/models/migrate/openai/auth-and-credentials?hl=en#refresh_your_credentials)
393
> for details.
394
395
### Configuration (Base URL)
396
397
398
399
- **Global Endpoint** (Recommended for most models requiring global
400
availability):
401
`https://aiplatform.googleapis.com/v1/projects/{PROJECT_ID}/locations/global/endpoints/openapi`
402
- **Regional Endpoint**:
403
`https://{REGION}-aiplatform.googleapis.com/v1/projects/{PROJECT_ID}/locations/{REGION}/endpoints/openapi`
404
405
406
### Python Example (OpenMaaS - Chat Completions)
407
408
See [`scripts/openmaas_openai_sdk.py`](scripts/openmaas_openai_sdk.py) for the
409
complete code.
410
411
> [!TIP] **Alternative: Environment Variables** You can set environment
412
> variables in your shell instead of updating the code.
413
>
414
> **Alternative: Environment Variables** You can set environment variables in
415
> your shell instead of updating the code.
416
417
```bash
418
export OPENAI_BASE_URL="https://aiplatform.googleapis.com/v1/projects/YOUR_PROJECT_ID/locations/global/endpoints/openapi"
419
export OPENAI_API_KEY="$(gcloud auth application-default print-access-token)"
420
```
421
> Then initialize the client without arguments: `client = OpenAI()`
422
423
### Python Example (OpenMaaS - Completions API)
424
425
The following models support the legacy Completions API: `zai-org/glm-5-maas`,
426
`moonshotai/kimi-k2-thinking-maas`, `minimaxai/minimax-m2-maas`,
427
`deepseek-ai/deepseek-v3.1-maas`, and `deepseek-ai/deepseek-v3.2-maas`.
428
429
```python
430
response = client.completions.create(
431
model="deepseek-ai/deepseek-v3.2-maas",
432
prompt="Once upon a time",
433
max_tokens=100
434
)
435
print(response.choices[0].text)
436
```
437
438
### Python Example (OpenMaaS - Embeddings)
439
440
```python
441
# Verify specific Embedding Model ID on Model Garden (e.g., intfloat/multilingual-e5-small)
442
response = client.embeddings.create(
443
model="intfloat/multilingual-e5-large-maas",
444
input="The quick brown fox jumps over the lazy dog",
445
)
446
print(response.data[0].embedding)
447
```
448
449
### Alternative: GenAI SDK
450
451
The `google-genai` SDK can also access OpenMaaS models via the `vertexai`
452
backend.
453
454
See [`scripts/openmaas_genai_sdk.py`](scripts/openmaas_genai_sdk.py) for the
455
complete code.
456
457
> [!IMPORTANT]
458
> **Model ID Format**: For GenAI SDK with OpenMaaS, you **MUST** use the full
459
> path: `publishers/PUBLISHER/models/MODEL` (e.g.,
460
> `publishers/zai-org/models/glm-5-maas`).
461
462
### Legacy: Agent Platform SDK (OpenMaaS)
463
464
For OpenMaaS, you can also use `GenerativeModel` (if supported).
465
466
See [`scripts/openmaas_vertexai_sdk.py`](scripts/openmaas_vertexai_sdk.py) for
467
the complete code.
468
469
> [!IMPORTANT] **Model ID Format**: For Agent Platform SDK with OpenMaaS, you
470
> **MUST** use the full path: `publishers/PUBLISHER/models/MODEL`.
471
472
### Model Reference & Availability
473
474
**Documentation**:
475
[Use Open Models on Agent Platform](https://docs.cloud.google.com/gemini-enterprise-agent-platform/models/maas/use-open-models)
476
477
> [!TIP]
478
> **Self-Deployment for Control**: If you need **dedicated hardware**
479
> (GPUs/TPUs), **guaranteed capacity**, or **specific regional placement** not
480
> offered by MaaS, you can **Self-Deploy** these models to Agent Platform
481
> Endpoints. Search for the model in Model Garden and click "Deploy" to select
482
> your machine type. See the `agent-platform-deploy` skill for the deployment
483
> workflow, and **section 4 of this skill** for how to invoke the resulting
484
> self-deployed endpoint (use `/chat/completions` on the dedicated endpoint
485
> DNS, NOT the OpenMaaS publisher URL above).
486
487
> [!IMPORTANT] **Finding Inference Examples**: The list above is a starting
488
> point. For the **definitive** inference snippets (especially for Chat
489
> Completions payload structure): 1. Consult the
490
> [Use Open Models on Agent Platform](https://docs.cloud.google.com/gemini-enterprise-agent-platform/models/maas/use-open-models)
491
> list. 2. Click the link for your specific model (e.g., "DeepSeek-V3") to visit
492
> its **Model Garden** page. 3. Look for the **"Sample Code"** or **"Use this
493
> model"** button on the Model Garden page to get the exact `curl` or Python
494
> code for that specific model version.
495
496
> [!NOTE] This list is **INCOMPLETE**. See
497
> [Use Open Models on Agent Platform](https://docs.cloud.google.com/gemini-enterprise-agent-platform/models/maas/use-open-models)
498
> for the full list of supported models.
499
500
Model Family | Model ID Examples | Location | Notes
501
:------------ | :--------------------------------------------- | :------------ | :----
502
**Llama 4** | `meta/llama-4-maverick-17b-128e-instruct-maas` | `us-east5` |
503
**Llama 4** | `meta/llama-4-scout-17b-16e-instruct-maas` | `us-east5` |
504
**Llama 3.3** | `meta/llama-3.3-70b-instruct-maas` | `us-central1` |
505
**DeepSeek** | `deepseek-ai/deepseek-v3.2-maas` | `global` | Global ONLY
506
**DeepSeek** | `deepseek-ai/deepseek-v3.1-maas` | `us-west2` | US-West2 ONLY
507
**DeepSeek** | `deepseek-ai/deepseek-r1-0528-maas` | `us-central1` |
508
**Qwen 3** | `qwen/qwen3-coder-480b-a35b-instruct-maas` | `global` |
509
**Qwen 3** | `qwen/qwen3-next-80b-a3b-instruct-maas` | `global` |
510
**Kimi** | `moonshotai/kimi-k2-thinking-maas` | `global` |
511
**MiniMax** | `minimaxai/minimax-m2-maas` | `global` |
512
**GLM** | `zai-org/glm-4.7-maas`, `zai-org/glm-5-maas` | `global` |
513
514
## 4. Custom Endpoints (tuned Gemini, self-deployed OSS LLM, legacy custom)
515
516
This section covers how to invoke a model on an Agent Platform
517
**Endpoint** that belongs to your project — i.e., something with a
518
numeric resource name like
519
`projects/.../endpoints/5875254126916403200`. This is distinct from
520
calling the publisher MaaS surfaces in sections 2 and 3 (which hit
521
`publishers/.../models/...` or `endpoints/openapi`, not your endpoint
522
ID).
523
524
> [!IMPORTANT]
525
>
526
> **Publisher MaaS vs your endpoint (don't confuse them).** Section 3's
527
> OpenMaaS examples (e.g. `meta/llama-3.3-70b-instruct-maas`) hit a
528
> **shared publisher URL** at
529
> `/v1/projects/.../locations/.../endpoints/openapi`. This section's
530
> recipes hit **YOUR** endpoint at `/v1/projects/.../endpoints/<id>`.
531
> If you have a Llama / Gemma / etc. model deployed via Model Garden
532
> "Deploy" (NOT the MaaS publisher product), follow this section — not
533
> section 3.
534
535
> [!IMPORTANT]
536
>
537
> **Active Endpoint Discovery & Single Source of Truth**:
538
>
539
> * To check if a model or tuned Gemini adapter is deployed and ready for
540
> inference, run:
541
>
542
> `gcloud ai endpoints list --project=<PROJECT_ID> --region=<REGION> --format=json`.
543
>
544
> * **`gcloud ai endpoints list` is the ONLY authoritative source of active
545
> serving endpoints.**
546
> * Do NOT rely on historical `job.tunedModel.endpoint` identifiers from past
547
> `gcloud ai tuning-jobs list` records — those record where an endpoint was
548
> initially created during tuning, but if the endpoint was subsequently
549
> deleted, undeployed, or expired, it is no longer active.
550
> * If `gcloud ai endpoints list` returns empty `[]` or the requested tuned
551
> model is not deployed on any listed endpoint, report directly to the user
552
> that no active endpoint was found in that region and halt. **NEVER**
553
> hallucinate that historical/deleted endpoints are ready, and **NEVER**
554
> silently substitute the base model without explicit user instruction and a
555
> fresh Tier R confirmation prompt.
556
557
> [!IMPORTANT]
558
>
559
> **Two orthogonal axes determine the call shape:**
560
>
561
> **Axis 1 — model family** drives the RPC method and payload:
562
>
563
> | Endpoint serves | Method | Payload |
564
> |---|---|---|
565
> | A **tuned Gemini model** (output of Gemini tuning — the endpoint is already deployed for you) | `:generateContent` | `contents` / `generationConfig` |
566
> | A **self-deployed OSS LLM** (Llama, DeepSeek, Qwen, Gemma, Mistral, etc., deployed via Model Garden) | `/chat/completions` | OpenAI-compatible `messages` |
567
> | A **legacy custom model** (classification, regression, custom-trained, embedding) | `:predict` | `instances` / `parameters` |
568
>
569
> Run `gcloud ai endpoints describe <ENDPOINT_ID> --region=<REGION>
570
> --format=json` and inspect `deployedModels[].model` to decide:
571
> contains `gemini` → tuned Gemini; matches an OSS publisher
572
> (`meta/`, `google/gemma-`, `deepseek-ai/`, `qwen/`, ...) → OSS LLM;
573
> otherwise → likely legacy custom.
574
>
575
> **Axis 2 — endpoint type (shared vs dedicated)** drives the URL host:
576
>
577
> | `dedicatedEndpointEnabled` | Host |
578
> |---|---|
579
> | `false` (default — shared endpoint) | `<REGION>-aiplatform.googleapis.com` |
580
> | `true` (dedicated endpoint, has its own DNS) | the value of `dedicatedEndpointDns` (format: `<ENDPOINT_ID>.<REGION>-<PROJECT_NUM>.prediction.vertexai.goog`) |
581
>
582
> A dedicated endpoint **cannot** be reached via the shared
583
> `<REGION>-aiplatform.googleapis.com` host (per the
584
> `Endpoint.dedicated_endpoint_enabled` proto: *"Once you enabled
585
> dedicated endpoint, you won't be able to send request to the shared
586
> DNS"*). Always check `dedicatedEndpointDns` in the describe output:
587
> if it's set, use it as the host; otherwise use the shared host.
588
>
589
> **Path is always
590
> `/v1/projects/.../locations/.../endpoints/<id>/...`** on both hosts.
591
> Both `/v1/` (GA) and `/v1beta1/` (beta) route to the same backend; the
592
> recipes in this skill use `/v1/`. The public
593
> [Gemma deployment notebook](https://github.com/GoogleCloudPlatform/vertex-ai-samples/blob/main/notebooks/community/model_garden/model_garden_gemma_deployment_on_vertex.ipynb)
594
> still uses `/v1beta1/`, which also works.
595
596
### 4a. REST recipe — tuned Gemini model
597
598
Output of Gemini tuning is always an endpoint that's already deployed for
599
you, reachable on the shared host with `:generateContent`.
600
601
```bash
602
PROJECT_ID=my-project
603
ENDPOINT_ID=5875254126916403200
604
REGION=us-central1
605
TOKEN=$(gcloud auth application-default print-access-token)
606
607
curl -sS -X POST \
608
-H "Authorization: Bearer $TOKEN" \
609
-H "Content-Type: application/json" \
610
"https://${REGION}-aiplatform.googleapis.com/v1/projects/${PROJECT_ID}/locations/${REGION}/endpoints/${ENDPOINT_ID}:generateContent" \
611
-d '{
612
"contents": [
613
{"role": "user", "parts": [{"text": "Hello! Introduce yourself briefly."}]}
614
],
615
"generationConfig": {
616
"temperature": 0.2
617
}
618
}'
619
```
620
621
> [!WARNING]
622
>
623
> **If you set `maxOutputTokens`, be generous for thinking models.**
624
> Gemini 2.5 Pro (and other thinking-enabled models) emit "thoughts"
625
> tokens that count against `maxOutputTokens` BEFORE any user-visible
626
> text. With a small cap (e.g. 100), the entire budget is consumed by
627
> thoughts and the response has empty `text` parts but a non-zero
628
> `usageMetadata.candidatesTokenCount`.
629
>
630
> If you don't need to constrain output length, omit `maxOutputTokens`
631
> entirely and let the model emit as much as it wants. If you do set
632
> it: `>= 512` for any chat-like use, `>= 1024` for a paragraph of
633
> output. If you see `finishReason: "MAX_TOKENS"` and no `text`
634
> content in the response, your cap is too low.
635
636
### 4b. REST recipe — self-deployed OSS LLM (Llama, DeepSeek, Qwen, Gemma, etc.)
637
638
Self-deployed OSS LLMs may be on a **shared** or **dedicated** endpoint
639
depending on how the deploy was configured (`dedicated_endpoint_enabled`
640
at create time). The recipe below handles both cases by checking
641
`dedicatedEndpointDns` in the describe output.
642
643
```bash
644
PROJECT_ID=my-project
645
ENDPOINT_ID=5875254126916403200
646
REGION=us-central1
647
TOKEN=$(gcloud auth application-default print-access-token)
648
649
# Step 1: discover host. dedicatedEndpointDns is empty for shared endpoints.
650
DEDICATED_DNS=$(gcloud ai endpoints describe "$ENDPOINT_ID" \
651
--project="$PROJECT_ID" --region="$REGION" \
652
--format="value(dedicatedEndpointDns)")
653
654
if [ -n "$DEDICATED_DNS" ]; then
655
HOST="$DEDICATED_DNS"
656
else
657
HOST="${REGION}-aiplatform.googleapis.com"
658
fi
659
660
# Step 2: call /chat/completions. Path is identical for both hosts.
661
curl -sS -X POST \
662
-H "Authorization: Bearer $TOKEN" \
663
-H "Content-Type: application/json" \
664
"https://${HOST}/v1/projects/${PROJECT_ID}/locations/${REGION}/endpoints/${ENDPOINT_ID}/chat/completions" \
665
-d '{
666
"messages": [
667
{"role": "user", "content": "Hello! Introduce yourself briefly."}
668
]
669
}'
670
```
671
672
> [!NOTE]
673
>
674
> - `max_tokens` (NOT `maxOutputTokens`) — this is OpenAI-compatible
675
> vocabulary, not Vertex. Omit it entirely to let the model emit as
676
> much as it wants; set it explicitly only if you need to cap output.
677
> - The `"model"` field in the OpenAI-style payload can be omitted (or
678
> set to `""`) for endpoint deployments — the endpoint already
679
> determines which model serves the request.
680
> - Same endpoint also exposes `/completions` (legacy text completion)
681
> and `/embeddings` for embedding models.
682
> - **Reasoning models** (DeepSeek-R1, Kimi-K2-Thinking, GLM-5 variants,
683
> etc.) emit thinking tokens that count against `max_tokens` BEFORE
684
> the final answer — same pathology as Gemini 2.5 Pro in section 4a.
685
> If you DO set `max_tokens` and get an empty
686
> `choices[0].message.content` or `finish_reason: "length"`, raise it
687
> (>= 1024 for chat, >= 2048 for longer thinking chains) or omit it.
688
689
Python equivalent (OpenAI SDK) — mirrors the public
690
[Gemma deployment notebook](https://github.com/GoogleCloudPlatform/vertex-ai-samples/blob/main/notebooks/community/model_garden/model_garden_gemma_deployment_on_vertex.ipynb):
691
692
```python
693
import google.auth
694
from google.auth.transport.requests import Request
695
import openai
696
697
from google.cloud import aiplatform
698
699
PROJECT_ID = "my-project"
700
ENDPOINT_ID = "5875254126916403200"
701
REGION = "us-central1"
702
703
aiplatform.init(project=PROJECT_ID, location=REGION)
704
endpoint = aiplatform.Endpoint(
705
f"projects/{PROJECT_ID}/locations/{REGION}/endpoints/{ENDPOINT_ID}"
706
)
707
endpoint_resource_name = endpoint.resource_name # full projects/.../endpoints/<id>
708
dedicated_dns = endpoint.gca_resource.dedicated_endpoint_dns # empty if shared
709
710
host = dedicated_dns if dedicated_dns else f"{REGION}-aiplatform.googleapis.com"
711
base_url = f"https://{host}/v1/{endpoint_resource_name}"
712
713
import subprocess
714
715
token = subprocess.check_output(
716
["gcloud", "auth", "print-access-token"]
717
).decode("utf-8").strip()
718
719
client = openai.OpenAI(base_url=base_url, api_key=token)
720
response = client.chat.completions.create(
721
model="", # endpoint determines the served model
722
messages=[{"role": "user", "content": "Hello! Introduce yourself briefly."}],
723
# Omit max_tokens to let the model emit as much as it wants. Set it
724
# only if you need to cap output length (see notes above).
725
)
726
print(response.choices[0].message.content)
727
```
728
729
See also: `agent-platform-deploy` skill section 4 "Verifying Deployment",
730
which uses the same pattern post-deploy.
731
732
### 4c. REST recipe — legacy `:predict` (custom / classification / embedding)
733
734
Same host-discovery logic as 4b (shared or dedicated based on
735
`dedicatedEndpointDns`):
736
737
```bash
738
DEDICATED_DNS=$(gcloud ai endpoints describe "$ENDPOINT_ID" \
739
--project="$PROJECT_ID" --region="$REGION" \
740
--format="value(dedicatedEndpointDns)")
741
HOST=${DEDICATED_DNS:-${REGION}-aiplatform.googleapis.com}
742
743
curl -sS -X POST \
744
-H "Authorization: Bearer $TOKEN" \
745
-H "Content-Type: application/json" \
746
"https://${HOST}/v1/projects/${PROJECT_ID}/locations/${REGION}/endpoints/${ENDPOINT_ID}:predict" \
747
-d '{
748
"instances": [{"key": "value"}],
749
"parameters": {}
750
}'
751
```
752
753
The exact `instances` shape is model-specific; consult the deployed
754
model's documentation or the Model Garden card it was deployed from.
755
756
### 4d. Python (Vertex AI SDK) — tuned Gemini model
757
758
```python
759
from google import genai
760
import google.auth
761
762
_, project_id = google.auth.default()
763
client = genai.Client(vertexai=True, project=project_id, location="us-central1")
764
765
ENDPOINT_ID = "5875254126916403200"
766
response = client.models.generate_content(
767
model=f"projects/{project_id}/locations/us-central1/endpoints/{ENDPOINT_ID}",
768
contents="Hello! Introduce yourself briefly.",
769
config={"temperature": 0.2}, # add max_output_tokens only if you need a cap
770
)
771
print(response.text)
772
```
773
774
## 5. Troubleshooting & Common Error Codes
775
776
### 429: Resource Exhausted
777
778
* **Cause**: OpenMaaS and Gemini models use **Dynamic Shared Quota (DSQ)**.
779
Resources are pooled and allocated dynamically based on availability. A 429
780
error indicates the shared pool is temporarily exhausted, not necessarily
781
that *your* specific project quota is hit (though it can be).
782
* **Solution**: Implement strict **exponential backoff and retry** strategies.
783
* **High Throughput**: For production workloads requiring high throughput or
784
guaranteed capacity, consider **Provisioned Throughput (PT)**.
785
* **Important**: Quota increases through normal cloud processes (Cloud
786
Console) are **NOT** applicable for DSQ constraints.
787
* **Documentation**:
788
[Quotas and limits (DSQ)](https://docs.cloud.google.com/gemini-enterprise-agent-platform/models/quotas)
789
790
### 400: User Validation Error
791
792
* **Cause**: Invalid request format, unsupported parameter, or incorrect Model
793
ID.
794
* **Action**: Double-check your request payload and parameters. Verify the
795
Model ID and Region are correct.
796
* **Custom endpoints**: pick the right method + host per section 4's
797
decision tables:
798
* Tuned Gemini + you called `:predict` → switch to `:generateContent`
799
(section 4a). Error mentions "Required instances format mismatch".
800
* OSS LLM (Llama/DeepSeek/Qwen/Gemma/etc.) + you called
801
`:generateContent` or `:predict` → switch to `/chat/completions`
802
(section 4b). Error may be 404, 405, or "method not allowed".
803
* Legacy / custom-trained + you called `:generateContent` or
804
`/chat/completions` → switch to `:predict` (section 4c).
805
* **Dedicated endpoint reached on the shared host (or vice versa)**:
806
* Symptom: DNS resolution failure (`Could not resolve host`) or 404.
807
* Cause: dedicated endpoints don't accept traffic on
808
`<REGION>-aiplatform.googleapis.com`, and the dedicated DNS
809
(`*.prediction.vertexai.goog`) only exists when
810
`dedicatedEndpointEnabled` is true.
811
* Action: re-check `gcloud ai endpoints describe ... --format=json`
812
for the `dedicatedEndpointDns` field; use it iff non-empty (per
813
the host-discovery snippets in section 4b/4c).
814
815
### Empty response text on Gemini deployed endpoints
816
817
* **Cause**: `maxOutputTokens` is set too low. Gemini 2.5 Pro and other
818
thinking models emit "thoughts" tokens that count against the budget
819
BEFORE any user-visible text. With a small cap (e.g. 100), the entire
820
budget is consumed by thoughts and the response has empty `text` parts
821
but a non-zero `usageMetadata.candidatesTokenCount` and
822
`finishReason: "MAX_TOKENS"`.
823
* **Action**: Omit `maxOutputTokens` entirely (let the model emit as much
824
as it wants), or raise it to >= 512 for chat-like use, >= 1024 for
825
longer output. See section 4 "Custom Endpoints" for details.
826
827
### 404: Not Found / Model Not Available
828
829
* **Cause**: The model is not enabled, or not available in the specified
830
project or region.
831
* **Action**:
832
1. **Check Location Availability**:
833
* **OpenMaaS**: Verify the model is available in your region. See
834
[Model Availability by Location](https://docs.cloud.google.com/gemini-enterprise-agent-platform/resources/locations#genai-open-models).
835
* **Gemini**:
836
* **Source of Truth**: Always check
837
[Gemini Model Locations](https://docs.cloud.google.com/gemini-enterprise-agent-platform/resources/locations#google-models)
838
for the authoritative list.
839
* **Preview Models**: All Preview models (e.g., Gemini 3.1,
840
experimental versions) are often **ONLY** available in the
841
`us-central1` or `global` regions.
842
* **Stable Models**: (e.g., Gemini 2.5 Pro) Available in
843
`us-central1`, `europe-west4`, and many other regions.
844
* **Important**: If you get a 404/400 error, try switching your
845
client location to `us-central1` or `global`.
846
2. **Enable Llama Models**: For **Llama 3.3** and **Llama 4**, you **MUST**
847
enable the model in Model Garden before use. Go to the
848
[Model Garden](https://console.cloud.google.com/agent-platform/model-garden),
849
search for the model card (e.g., "Llama 3.3 API Service"), and click
850
**Enable**. Only then can you make inference requests.
851

© Google LLC · Apache 2.0 · source · posted by @OpenSourceBuffGuy on promptparty.com

@OpenSourceBuffGuy

I find openly licensed prompts and post them here.

0 followers · 6,373 prompts

More by @OpenSourceBuffGuy

See all
Website Clone Architect prompt image

Website Clone Architect

Reverse-engineers a website section by section, writes component specs, and hands them to parallel builder agents in git worktrees to rebuild it.

agent-skill, orchestrator, parallel-agents, multi-agent, plan-then-execute, web-development, frontend, codebase-analysis, scaffolding, css, html, nextjs, typescript, git, mcp, claude-code, for-developers, for-designers, long-form, advanced, technical-spec, task-decomposition, structured-output, design-systems, ui-ux, tool-use, checklist, report, vibe-coding

Italian Terrace Cafe Candid Portrait prompt image

Italian Terrace Cafe Candid Portrait

Generates a photorealistic candid shot of a woman in a white corset dress laughing at a sunny hotel terrace cafe, written as detailed JSON.

image-prompt, json-prompt, structured-output, photorealistic, portrait, woman, candid, fashion, cottagecore, natural-light, golden-hour, bokeh, summer, travel, cityscape, mountains, medium-shot, vibrant-colors, for-photographers, nano-banana, fashion-shoot, luxury

Night Street Photo With Leashed Cat prompt image

Night Street Photo With Leashed Cat

Generates a flash-lit night street photo of a blonde woman in a retro track jacket walking a hissing tabby cat on a leash.

image-prompt, json-prompt, nano-banana, structured-output, portrait, woman, animals, pet-portrait, night-scene, street-photography, candid, editorial, fashion, dramatic-lighting, photorealistic, vertical-format, medium-shot, graffiti, for-photographers, for-content-creators

1 view

Reviews

Loading reviews…

Discussion

Loading comments…