Agent Platform Eval Flywheel
Skill files14 files

references/

scripts/

SKILL.md613 lines
1
---
2
name: agent-platform-eval-flywheel
3
metadata:
4
version: "1.0.4"
5
category: AiAndMachineLearning
6
description: >-
7
Measures and improves the quality of AI models and agents on Google Cloud
8
using the Eval Quality Flywheel methodology. Use when generating synthetic
9
user scenarios, evaluating an agent or model, building an eval dataset,
10
picking or writing evaluation metrics, analyzing failures, comparing results
11
before and after a fix, or when guidance is needed on Agent Platform eval
12
methodology — including dataset schema, LLM-as-judge scoring, and common
13
failure causes. For fine-tuning, use agent-platform-tuning. For general
14
production deployment, use agent-platform-deploy.
15
---
16
17
# Agent Platform Eval Flywheel Skill
18
19
Help users evaluate and iteratively improve GenAI models and agents using the
20
Agent Platform GenAI Evaluation SDK (`google.genai` / `agentplatform`).
21
22
## Attribution
23
24
**MUST READ**: Before executing any `gcloud`, REST API, or MCP command, you MUST
25
read [Usage Attribution](references/attribution.md). For commands executed
26
directly in the terminal (never in generated scripts, Terraform, or user code),
27
prefix `gcloud` with `CLOUDSDK_METRICS_REQUEST_ATTRIBUTION` and append the
28
attribution suffix to `User-Agent` headers:
29
30
```text
31
CLOUDSDK_METRICS_REQUEST_ATTRIBUTION="agent-skills/1.0 (skill:agent-platform-eval-flywheel)"
32
User-Agent: <existing_user_agent> agent-skills/1.0 (skill:agent-platform-eval-flywheel)
33
```
34
35
## When to use this skill
36
37
- Evaluating GenAI agents or models with the Agent Platform GenAI Evaluation
38
SDK (`client.evals.evaluate()`).
39
- Creating evaluation datasets from session traces, pandas DataFrames, or
40
synthetic generation.
41
- Selecting, configuring, or writing custom evaluation metrics.
42
- Analyzing rubric verdicts, loss patterns, and clustering failures.
43
- Suggesting concrete code/prompt improvements based on eval results.
44
- Evaluating a model served on an Agent Platform **endpoint** (BYOM) or a
45
**Model-as-a-Service (MaaS)** model by ID — including deploying the model
46
first if needed. For this case, follow
47
[references/deployment.md](references/deployment.md) and use the
48
`endpoint_evaluation.py` / `maas_evaluation.py` scripts.
49
50
## Safety & Confirmation Tiers (CRITICAL)
51
52
Before executing any commands or scripts on behalf of the user, you MUST adhere
53
to the following safety tiers based on the action requested:
54
55
1. **Tier R**: Read-only (`inspect_results.py`, `compare_results.py`,
56
`validate_dataset.py`, `parse_adk_traces.py`, `render_html_report.py`)
57
* **Rule**: No confirmation needed. You may execute these helper scripts
58
immediately to inspect data, validate schemas, parse traces, or compare
59
evaluation results.
60
2. **Tier M: Evaluation & Generation Runs (`client.evals.run_inference`,
61
`client.evals.evaluate`, `client.evals.generate_conversation_scenarios`,
62
`client.evals.generate_loss_clusters`)**
63
* **Rule**: For predictable user approval over dataset reads, result
64
writes (`dest`), and remote compute/API usage, every call to
65
`client.evals.evaluate()`, `client.evals.run_inference()`,
66
`client.evals.generate_conversation_scenarios()`, or
67
`client.evals.generate_loss_clusters()` — whether using remote metrics
68
(LLM/rubric metrics or sandboxed `types.CodeExecutionMetric`) or local
69
in-process metrics (`types.Metric` with a Python callable) — requires
70
presenting a dry-run confirmation preview showing the proposed
71
evaluation call and parameters and waiting for explicit 'Yes'/'No' user
72
approval (do not quote remote compute charges when only local in-process
73
`types.Metric` callables are used without `dest` or model inference).
74
* **Confirmation for EVERY evaluation run**: Every evaluation,
75
re-evaluation, metric update, parameter change, or synthetic scenario
76
generation requires its own dry-run preview and interactive
77
confirmation. Never execute a second evaluation, comparison pass, or
78
modified evaluation without presenting a new confirmation preview and
79
obtaining user approval.
80
* **Same-turn restriction**: Do not run the evaluation in the same turn as
81
presenting the confirmation prompt. End your turn after asking and wait
82
for the user's reply; only execute after explicit 'Yes' / approval.
83
Printing a preview and then calling the tool before the user can answer
84
does not count as obtaining confirmation.
85
* **No Pre-Execution of Evaluation Calls**: NEVER execute
86
`client.evals.evaluate()`, `client.evals.run_inference()`,
87
`client.evals.generate_conversation_scenarios()`, or run any script
88
invoking these SDK methods before user confirmation. In the initial
89
turn, you may write the evaluation script to disk, but you MUST present
90
the dry-run confirmation preview and obtain explicit user confirmation
91
before running `client.evals.evaluate()`.
92
* **Immediate Execution Upon Approval**: Once the user explicitly approves
93
(e.g., 'Yes', 'Approved', 'Go ahead', 'Proceed'), proceed directly to
94
executing the previewed evaluation script via `run_command` and report
95
the results. Do not conclude the turn without executing the approved
96
action.
97
98
## Setup
99
100
The scripts need `vertexai` (from `google-cloud-aiplatform[evaluation]`),
101
`google-genai`, `pandas`, and `requests`. Do **not** create a virtual
102
environment — it starts empty and hides packages the environment already
103
provides, forcing a redundant install. Probe, and install only what is missing:
104
105
```bash
106
python3 -c "import vertexai, google.genai, pandas, requests" \
107
|| pip install 'google-cloud-aiplatform[evaluation]>=1.163.0' 'google-genai>=1.0.0'
108
```
109
110
The version specifiers must stay quoted: unquoted, bash reads `>=1.154.0` as a
111
redirect and silently writes an empty file instead of constraining the install.
112
113
Need `GOOGLE_CLOUD_PROJECT` and `GOOGLE_CLOUD_LOCATION`.
114
115
- **Preserve User Project and Location**: Always prioritize the user's
116
explicitly provided project and location (e.g. `project='<PROJECT_NUMBER>'`,
117
`location='us-central1'`). Never change or override the user's requested
118
location to 'global' unless the user explicitly requested 'global'.
119
- **Missing Parameters**: If the user's request omits the project or location,
120
you MUST pause in your response and ask the user for the missing
121
location/project before preparing or running the evaluation.
122
123
### Correct SDK entrypoints
124
125
```python
126
import agentplatform
127
client = agentplatform.Client(project=PROJECT, location=LOCATION)
128
129
client.evals.run_inference(model=..., src=...)
130
client.evals.evaluate(dataset=..., metrics=...)
131
client.evals.generate_conversation_scenarios(...)
132
```
133
134
Two imports that look plausible and are not:
135
136
- `from agentplatform.types import evals` -- `ModuleNotFoundError`. `types` is
137
a module, not a package; use `from agentplatform import types`.
138
- `from vertexai.evaluation import PointwiseMetric, EvalTask` -- the
139
superseded SDK. Its classes take different arguments (`PointwiseMetric` has
140
no `system_instruction`), so code written against it fails with `TypeError`
141
rather than an import error. Use `agentplatform` throughout.
142
143
## The Quality Flywheel
144
145
Five stages, run in order on the first pass, then loop 2 → 5 until quality
146
targets are met.
147
148
### Shortcuts that waste time
149
150
| Shortcut | Why it fails |
151
| ------------------------------------ | ------------------------------------ |
152
| "I'll tune the metric threshold down | Hides real failures. Fix the agent, |
153
: so it passes." : not the bar. :
154
| "This case is flaky, I'll skip it." | Flakiness reveals non-determinism in |
155
: : the agent. Fix with `temperature=0` :
156
: : or stricter instructions. :
157
| "I just need to fix the eval | If expected outputs keep moving, the |
158
: dataset, not the agent." : agent has a behavior problem. :
159
| "I can tell from the trace it works | Self-grading doesn't generalize. |
160
: — skip Stage 3." : Always run `evaluate()` and read :
161
: : scores. :
162
| "One iteration is enough." | Expect 5–10+ iterations. Stopping |
163
: : early leaves regressions on other :
164
: : metrics undetected. :
165
166
### 1. Prepare Data
167
168
Produce an `EvaluationDataset`. There are three input shapes, pick the one that
169
matches the data the user already has:
170
171
- **`EvalCase` list (single-turn or multi-turn):**
172
173
```python
174
from agentplatform import types
175
from google.genai import types as genai_types
176
177
# prompt/reference/response values are Content, not str. UserContent and
178
# ModelContent wrap a plain string and set the right role.
179
dataset = types.EvaluationDataset(eval_cases=[
180
types.EvalCase(
181
prompt=genai_types.UserContent("What is 2+2?"),
182
responses=[types.ResponseCandidate(
183
response=genai_types.ModelContent("4"))],
184
reference=types.ResponseCandidate(
185
response=genai_types.ModelContent("4")),
186
),
187
# For multi-turn agent traces, set agent_data instead of prompt/responses.
188
])
189
```
190
191
Multi-turn agent traces wrap each conversation in `AgentData` →
192
`ConversationTurn` → `AgentEvent`. See
193
[references/dataset_schema.md](references/dataset_schema.md) for the full
194
type hierarchy.
195
196
- **Pandas DataFrame (tabular sources — CSV, BigQuery, Sheets):**
197
198
```python
199
import pandas as pd
200
from agentplatform import types
201
202
df = pd.DataFrame({
203
"prompt": ["What is 2+2?", "Capital of France?"],
204
"response": ["4", "Paris"],
205
"reference": ["4", "Paris"],
206
})
207
dataset = types.EvaluationDataset(eval_dataset_df=df)
208
```
209
210
Column names must match the fields the chosen metrics expect (see
211
[references/dataset_schema.md](references/dataset_schema.md) for the
212
per-metric requirements table).
213
214
- **Cold start (no data at all):** synthesize scenarios server-side with
215
`client.evals.generate_conversation_scenarios(agent=..., config=...)` -- the
216
parameter is `agent` or `agent_info`, not `agents`, and `config` is
217
required. The config class is `types.evals.UserScenarioGenerationConfig`,
218
not `types.UserScenarioGenerationConfig`. Set its `user_scenario_count`
219
(1-100): it defaults to None, the client accepts that, and the server
220
rejects the call with `400 INVALID_ARGUMENT`. `count` is a separate field
221
and does not substitute for it. Stage 2 plays the scenarios out.
222
* **CRITICAL - Multi-turn user-simulation scenarios must use this API**:
223
When the user asks to synthesize multi-turn **user scenarios** to
224
simulate customers interacting with an agent (as opposed to writing a
225
local single-turn test dataset in the sandbox), never author the
226
conversation scenarios yourself in prose or a handwritten file. Calling
227
`client.evals.generate_conversation_scenarios` is a server-side Tier M
228
API call (using the user's project, location, model, and environment
229
data) and requires a confirmation card; local single-turn dataset files
230
written in the sandbox without calling Agent Platform APIs are Tier R.
231
* **CRITICAL - Underspecified Requests**: When asked to synthesize
232
scenarios, if the request omits required parameters (such as `location`,
233
`environment_data`, `simulation_instruction`, or `model_name`), do NOT
234
assume defaults or guess values. You MUST pause in your first turn and
235
explicitly ask the user for the missing information (e.g., "Please
236
provide the missing simulation instructions, environment data, model
237
name, and location"). Only proceed with the dry-run preview after the
238
user provides them. `location` has no safe default: neither
239
`us-central1` nor a location you assumed on your own for another call is
240
a substitute for a location the user has not given.
241
* **Friction & Parameter Changes**: When asked to generate synthetic user
242
scenarios, if the user modifies requested parameters (such as scenario
243
count, model, or instructions) or pushes back, you MUST present a
244
revised dry-run confirmation card with the updated parameters and wait
245
for explicit user approval before executing generation code via
246
`run_command`.
247
248
- **Managed Agents (Gemini Agents API):** evaluate agents created with the
249
[Managed Agents API](https://docs.cloud.google.com/gemini-enterprise-agent-platform/build/managed-agents).
250
Use `generate_conversation_scenarios` to create test scenarios from the
251
agent's configuration, `run_inference` to execute the agent, and `evaluate`
252
to score the traces. These functions now accept managed agents and
253
interaction ids as input. You can also evaluate existing interactions
254
recorded via the Interactions API using `InteractionsDataSource`. See
255
[references/sdk_patterns.md](references/sdk_patterns.md) Pattern 8 for the
256
full code pattern.
257
258
For ADK session dumps, use `scripts/parse_adk_traces.py` instead of writing the
259
conversion by hand.
260
261
### 2. Run Inference
262
263
Populate responses/traces on the dataset. **Skip this stage** if traces are
264
already complete (e.g., production logs or replay).
265
266
```python
267
# Agent eval — pass a callable wrapping the user's ADK Agent/App.
268
client.evals.run_inference(model=agent_callable, src=dataset)
269
270
# Model eval — pass a model ID directly.
271
client.evals.run_inference(model="gemini-2.5-flash", src=dataset)
272
273
# Synthesized scenarios — let the simulator drive.
274
client.evals.run_inference(
275
model=agent_callable,
276
src=dataset,
277
user_simulator_config=UserSimulatorConfig(max_turn=10),
278
)
279
280
# DataFrame also works as src= — no EvalCase wrapping needed.
281
client.evals.run_inference(model="gemini-2.5-flash", src=df)
282
283
# Managed Agent — pass an agent resource name.
284
AGENT_RESOURCE = f"projects/{PROJECT_ID}/locations/global/agents/{AGENT_ID}"
285
client.evals.run_inference(
286
agent=AGENT_RESOURCE,
287
src=scenarios,
288
config={"user_simulator_config": {"max_turn": 3}},
289
)
290
```
291
292
### 3. Grade (always run)
293
294
```python
295
result = client.evals.evaluate(dataset=dataset, metrics=[...])
296
result.show() # Interactive HTML report with scores, rubrics, and traces.
297
```
298
299
**Pick metrics by what you want to measure.** Full catalog in
300
[references/metric_registry.md](references/metric_registry.md).
301
302
**If the user names a metric, use it directly.** Every identifier in the tables
303
below (`general_quality`, `text_quality`, `instruction_following`,
304
`hallucination`, `grounding`, `safety`, `multi_turn_*`, `final_response_*`,
305
`tool_use_quality`) is a `types.RubricMetric.<UPPERCASE_NAME>` accessor — pass
306
it straight into `metrics=[types.RubricMetric.GENERAL_QUALITY, ...]`. Do not
307
scaffold a custom `LLMMetric` for a name that appears here, and do not reach for
308
`vertexai.evaluation.EvalTask` / `PointwiseMetric` /
309
`MetricPromptTemplateExamples` — that SDK is superseded (see Setup).
310
311
**`judge_model` format and handling user-named models:**
312
313
* **Full resource name required for `judge_model`**: Both `LLMMetric` and
314
`RubricMetric` send `judge_model` as `autorater_config.autorater_model` to
315
the backend (even though `agentplatform` logs a client-side "ignored"
316
warning on `RubricMetric`). Short names like `"gemini-2.5-flash"` or
317
`"gemini-2.5-pro"` fail with `400 INVALID_ARGUMENT ("Invalid autorater model
318
resource name")`. Always pass the full publisher model resource name:
319
`f"projects/{PROJECT_ID}/locations/{LOCATION}/publishers/google/models/{MODEL_NAME}"`
320
(prefer `gemini-2.5-flash` as autorater; `gemini-2.5-pro` can intermittently
321
fail server-side with `"Rubric results could not be reliably computed"`).
322
* **Datasets without vs. with responses**:
323
* If the dataset contains **prompts only** (no `response` column), call
324
`run_inference(model="<the named model>", src=dataset)` to generate the
325
candidate model's responses first, then grade them with `evaluate()`.
326
* If the user **already supplies `response`s** in the dataset, **do NOT
327
call `run_inference`** — `run_inference` overwrites the existing
328
`response` column with the model's generated output and discards the
329
user's responses! Instead, grade the user's supplied `response`s
330
directly with `evaluate(dataset=dataset, ...)`, passing the named model
331
as the full resource path in `judge_model` (or if a predefined
332
`RubricMetric` cannot reliably compute rubric results with that
333
autorater model, fall back to the default autorater and explain why).
334
335
**Agent metrics (multi-turn, adaptive rubrics)** — start here for agent eval.
336
337
Goal | Metric
338
--------------------------------------------- | -------------------------------
339
Did the agent achieve the user's goal? | `multi_turn_task_success`
340
Was the reasoning path logical and efficient? | `multi_turn_trajectory_quality`
341
Tool/function calling quality across turns | `multi_turn_tool_use_quality`
342
Overall conversational quality | `multi_turn_general_quality`
343
Final response quality (no reference needed) | `final_response_quality`
344
Final response vs. a golden reference | `final_response_match`
345
Single-turn tool use | `tool_use_quality`
346
347
**General quality metrics (single-turn, adaptive rubrics)** — for model eval.
348
349
Goal | Metric
350
----------------------------------------------------- | -----------------------
351
Overall response quality (recommended starting point) | `general_quality`
352
Linguistic quality (fluency, coherence, grammar) | `text_quality`
353
Adherence to specific constraints / instructions | `instruction_following`
354
355
**Static rubric metrics (fixed criteria)** — apply alongside the above.
356
357
Goal | Metric
358
------------------------------------------------- | ---------------
359
Catch hallucinated claims (RAG, factual answers) | `hallucination`
360
Factuality / consistency against provided context | `grounding`
361
Safety policy compliance | `safety`
362
363
**Domain-specific check no built-in covers:** write a custom metric.
364
365
- **Predefined:** `types.RubricMetric.<NAME>` — server-side AutoRater, no
366
judge model needed.
367
- **Custom LLM-as-a-judge:** `types.LLMMetric` with `prompt_template` or
368
`types.MetricPromptBuilder` for structured rubrics. Always set
369
`judge_model`; it defaults to `None` and every case then fails with `400
370
INVALID_ARGUMENT: Error parsing JSON`.
371
* **Judge Model Selection**: If the user specifies a judge model (e.g.
372
`gemini-2.5-pro`), use it. If the user omits the judge model or states
373
they do not have information / preference for one, default to
374
`gemini-2.5-flash` as the judge model in the dry-run preview card and
375
ask for confirmation to run the evaluation. Do NOT halt or refuse to
376
evaluate when the user does not specify a judge model.
377
- **Custom code:** `types.CodeExecutionMetric` with a `custom_function` string
378
containing `def evaluate(instance: dict)` for remote sandboxed execution; or
379
`types.Metric` with `custom_function=<callable>` for local execution. The
380
`instance` dict's `prompt` / `response` / `reference` are `Content` dicts,
381
not strings; read
382
[references/metric_registry.md](references/metric_registry.md) ("What the
383
function receives") before writing the body, rather than discovering the
384
shape by running the evaluation.
385
386
**Always persist the result** so Stage 4 and 5 can read it. Save both JSON
387
(machine-readable, diffable) and HTML (human-readable, linkable):
388
389
```python
390
import datetime
391
from pathlib import Path
392
393
from agentplatform._genai import _evals_visualization
394
395
out_dir = Path("artifacts/grade_results")
396
out_dir.mkdir(parents=True, exist_ok=True)
397
ts = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
398
399
# fallback=str, or a DataFrame-backed dataset raises PydanticSerializationError.
400
result_json = result.model_dump_json(fallback=str)
401
(out_dir / f"results_{ts}.json").write_text(result_json)
402
403
html = _evals_visualization.get_evaluation_html(result_json)
404
(out_dir / f"results_{ts}.html").write_text(str(html))
405
```
406
407
Or after the fact: `scripts/render_html_report.py --type evaluation` or
408
`scripts/inspect_results.py --save-html`.
409
410
### 4. Analyze Failures
411
412
Read `summary_metrics` and `eval_case_results` — never fabricate scores. Use
413
`scripts/inspect_results.py --failing-only` to filter to failures.
414
415
For each failed metric, see
416
[references/failure_patterns.md](references/failure_patterns.md) for deeper
417
diagnoses. The compact mapping:
418
419
| Failing metric | What to change |
420
| ----------------------------------- | -------------------------------------- |
421
| `multi_turn_task_success` low | The agent isn't completing the goal — |
422
: : fix orchestration, missing tool calls, :
423
: : premature termination, wrong tool :
424
: : selection. :
425
| `multi_turn_trajectory_quality` low | The agent reaches the goal |
426
: : inefficiently — refine planning :
427
: : prompts, remove redundant tool calls. :
428
| `multi_turn_tool_use_quality` low | Fix tool descriptions, parameter |
429
: : docstrings, or agent instructions for :
430
: : tool selection. :
431
| `final_response_quality` low | Read auto-generated rubric verdicts; |
432
: : refine instructions to address the :
433
: : worst-scoring criterion. :
434
| `final_response_match` low | The agent's final answer doesn't match |
435
: : the golden reference — adjust response :
436
: : format or update the reference. :
437
| `hallucination` low | Tighten instructions to stay grounded |
438
: : in tool output; verify the tool :
439
: : actually returned the claimed data. :
440
| `grounding` low | The response contradicts the provided |
441
: : context — add explicit "cite only from :
442
: : context" instructions. :
443
| `safety` low | Add safety guardrails; review the |
444
: : violating content category in the :
445
: : rubric verdict. :
446
| `general_quality` / `text_quality` | Adjust system instruction wording; the |
447
: low : model's default phrasing is too :
448
: : generic for the task. :
449
| `instruction_following` low | The agent is ignoring constraints — |
450
: : restate them in the system instruction :
451
: : or use stricter wording. :
452
| Agent calls wrong tools | Fix tool descriptions, agent |
453
: : instructions, or `tool_config`. :
454
| Agent calls extra tools | Add explicit stop instructions, or |
455
: : switch to :
456
: : `multi_turn_tool_use_quality` to :
457
: : surface the extra calls in the rubric. :
458
459
**For 10+ failures on the same metric**, use the **Error Analysis service** to
460
cluster failures into themes (L1/L2 taxonomy categories) instead of reading
461
every trace:
462
463
```python
464
# Only supports multi_turn_task_success and multi_turn_tool_use_quality.
465
# Service runs in the global region.
466
analysis_client = agentplatform.Client(project="PROJECT_ID", location="global")
467
response = analysis_client.evals.generate_loss_clusters(
468
eval_result=result,
469
metric="multi_turn_task_success",
470
config={"max_top_cluster_count": 5},
471
)
472
for r in response.results:
473
for cluster in r.clusters:
474
print(
475
f"[{cluster.taxonomy_entry.l1_category}/"
476
f"{cluster.taxonomy_entry.l2_category}] "
477
f"{cluster.item_count} cases — {cluster.taxonomy_entry.description}"
478
)
479
```
480
481
Save `response.model_dump_json()` and render with `scripts/render_html_report.py
482
--type loss-analysis`.
483
484
### 5. Optimize & Iterate
485
486
Apply a fix targeting the failing metric. Re-run Stage 3. Compare with
487
`scripts/compare_results.py --baseline <prev> --candidate <new>` to confirm the
488
target improved AND no other metric regressed.
489
490
Track progress across iterations:
491
492
Iteration | Metric A | Metric B | Change made
493
--------- | -------- | -------- | ----------------------
494
Baseline | 0.62 | 0.55 | —
495
v2 | 0.78 | 0.68 | Added grounding prompt
496
v3 | 0.81 | 0.72 | Fixed tool selection
497
498
Expect 5–10+ iterations per failing case. Only after a case passes should you
499
expand coverage with more eval cases.
500
501
## Proving your work
502
503
Never claim eval results you didn't read from an actual `result` object.
504
505
- After running eval, print the `summary_metrics` table
506
(`scripts/inspect_results.py`).
507
- After a fix, show before/after via `scripts/compare_results.py`.
508
- Before declaring success, confirm ALL cases pass — not just the one you were
509
working on.
510
511
If you can't produce the evidence (SDK call failed, result truncated, metric
512
unsupported), say so explicitly. Don't paper over gaps.
513
514
## Rules of Engagement
515
516
1. **Always Plan First:** Before writing a script, output a `<plan>` block
517
detailing the steps you are about to take.
518
2. **Step-by-Step Execution:** Prepare the data and evaluation script, present
519
the dry-run confirmation card with full parameters, wait for user approval,
520
execute only after explicit confirmation, then inspect and analyze results.
521
Do NOT run evaluation calls before user confirmation.
522
3. **Standard Python:** Use standard Python imports (`import agentplatform`,
523
`from google.genai import types`). Don't use internal import paths.
524
4. **Verify Before Guessing:** When unsure about SDK types or metrics, check
525
the SDK source code rather than guessing or hallucinating.
526
5. **Never End a Turn Silently:** Every turn must end with a non-empty,
527
informative text reply to the user summarizing the actions taken or
528
presenting the next steps. Returning nothing reads as a failure no matter
529
what the tools did.
530
531
## SDK Quick Reference
532
533
```python
534
import agentplatform
535
from agentplatform import types
536
from google.genai import types as genai_types
537
import pandas as pd
538
539
# Initialize client
540
client = agentplatform.Client(project="PROJECT_ID", location="LOCATION")
541
542
# --- SINGLE-TURN EVAL (pandas DataFrame) -- RECOMMENDED ---
543
# The converter wraps plain strings for you.
544
df = pd.DataFrame({
545
"prompt": ["Q1", "Q2"],
546
"response": ["A1", "A2"],
547
})
548
dataset = types.EvaluationDataset(eval_dataset_df=df)
549
550
# --- SINGLE-TURN EVAL (direct EvalCase) ---
551
# Verbose and easy to get wrong; see references/dataset_schema.md for the
552
# exact types before using this form.
553
dataset = types.EvaluationDataset(eval_cases=[
554
types.EvalCase(
555
prompt=genai_types.UserContent("Query here"),
556
responses=[types.ResponseCandidate(
557
response=genai_types.ModelContent("Model response here"))],
558
reference=types.ResponseCandidate(
559
response=genai_types.ModelContent("Ground truth here")),
560
),
561
])
562
563
# --- MULTI-TURN AGENT EVAL ---
564
agent_data = types.evals.AgentData(
565
agents={"my_agent": types.evals.AgentConfig(
566
agent_id="my_agent", instruction="You are helpful.")},
567
turns=[types.evals.ConversationTurn(turn_index=0, events=[
568
types.evals.AgentEvent(author="user",
569
content=genai_types.Content(role="user",
570
parts=[genai_types.Part(text="Hello")])),
571
types.evals.AgentEvent(author="my_agent",
572
content=genai_types.Content(role="model",
573
parts=[genai_types.Part(text="Hi! How can I help?")])),
574
])],
575
)
576
dataset = types.EvaluationDataset(
577
eval_cases=[types.EvalCase(agent_data=agent_data)])
578
579
# --- METRICS ---
580
predefined = types.RubricMetric.MULTI_TURN_TRAJECTORY_QUALITY
581
custom_llm = types.LLMMetric(name="tone",
582
prompt_template="Is this polite? Response: {response}")
583
custom_code = types.CodeExecutionMetric(name="check",
584
custom_function='def evaluate(instance): return {"score": 1.0}')
585
586
# --- EVALUATE ---
587
result = client.evals.evaluate(dataset=dataset, metrics=[predefined])
588
589
# --- RESULTS ---
590
for s in result.summary_metrics:
591
print(f"{s.metric_name}: mean={s.mean_score}, pass_rate={s.pass_rate}")
592
for case in result.eval_case_results:
593
for cand in case.response_candidate_results:
594
for name, r in cand.metric_results.items():
595
print(f" {name}: score={r.score}, explanation={r.explanation}")
596
```
597
598
See [references/sdk_patterns.md](references/sdk_patterns.md) for advanced
599
patterns: synthetic data generation, pairwise comparison, `MetricPromptBuilder`,
600
multi-agent evaluation.
601
602
## Bundled scripts
603
604
Script | When to use
605
------------------------ | -----------
606
`validate_dataset.py` | Before Stage 3 — catch malformed `EvaluationDataset` JSON.
607
`parse_adk_traces.py` | Stage 1 — convert ADK session dumps to the canonical dataset shape.
608
`inspect_results.py` | Stages 3/4 — render summary + per-case scores. `--save-html` for a browsable report.
609
`compare_results.py` | Stage 5 — diff baseline vs. candidate, detect regressions.
610
`render_html_report.py` | Render HTML from a saved result JSON or loss-clusters JSON.
611
`endpoint_evaluation.py` | Stages 2/3 against a deployed Agent Platform endpoint (BYOM). See [references/deployment.md](references/deployment.md).
612
`maas_evaluation.py` | Stages 2/3 against a Model-as-a-Service model by ID. See [references/deployment.md](references/deployment.md).
613

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

@OpenSourceBuffGuy

I find openly licensed prompts and post them here.

0 followers · 10,806 prompts

More by @OpenSourceBuffGuy

See all
Legal Precedent Research Expert prompt image

Legal Precedent Research Expert

Turns the AI into a legal precedent researcher that maps authorities, analyses holdings, builds arguments and anticipates counterarguments in IRAC-structured memoranda.

system-prompt, act-as, legal-research, litigation, legal, for-lawyers, xml-tags, structured-output, report, guardrails, advanced, long-form, formal, objective, critique, academic-writing, citation-formatting, research-methods

Felt miniature doll walking with a fox prompt image

Felt miniature doll walking with a fox

Generates a handmade felt miniature scene of a wool doll in a casual tech outfit walking across felt grass beside a small felt fox, in a macro stop-motion look.

image-prompt, nano-banana, embroidery, miniature, storybook, whimsical, cozy, macro, bokeh, natural-light, pastel, animals, toys, character-design, cinematic, for-artists, for-designers

Baby copies mother's yoga poses in 3D prompt image

Baby copies mother's yoga poses in 3D

Generates a 20-second Pixar-style 3D clip of a mother doing morning yoga while her baby copies every pose, with fixed character looks and camera plan.

video-prompt, animation, pixar-style, yoga, family, family-friendly, cinematic, character-consistency, camera-movement, tracking-shot, multi-shot, seedance, natural-light, soft-lighting, bokeh, pastel, close-up, wide-shot, widescreen, negative-prompt

Reviews

Loading reviews…

Discussion

Loading comments…