Module 30.2: The Quality Flywheel β GenAI Eval, User Simulation & GEPA
Theoryβ
Figure: Closed-loop 4-stage Quality Flywheel combining EvaluationDataset rubrics, dynamic user simulation (synthesize), failure clustering (analyze), and bounded GEPA instruction optimization (optimize).
Why .evalset.json Alone Isn't Enough for Production AgentOpsβ
In Module 24, you built your first regression safety net using adk web and uv run adk eval over local .evalset.json recordings. That workflow is ideal when designing an agent's graph in Parts 1β5, because it gives instant feedback on golden-path tool sequences.
When support-ops-agent graduates into an enterprise repository managed by google-agents-cli (v1.10+), four production pressures outgrow static .evalset.json snapshots:
- Multi-Turn Trajectory Variability: Real customers rarely state ticket IDs, tiers, and escalation justifications in one clean turn. Rigid tool-order matching fails whenever an agent asks a clarifying question or invokes a read-only helper in a valid alternative order.
- Per-Case Domain Rubrics: A P1 enterprise outage (
TCK-1042, 15-minute SLA + 24/7 SRE pager) and a P3 standard export bug (TCK-2088, 24-business-hour SLA, no escalation) demand completely different pass/fail criteria within the same evaluation run. - Failure Clustering at Scale: Reading 50+ HTML trace cards one by one after a prompt or model change is slow and error-prone; teams need automated loss clustering across failing runs.
- Systematic Prompt Refinement Without Overfitting: Tweaking system instructions by intuition often fixes Case A while silently breaking Case B unless changes are measured with
eval compareand validated against a holdout dataset.
agents-cli eval solves these challenges by standardizing on the Gemini platform EvaluationDataset schema (tests/eval/datasets/*.json) and orchestrating a four-stage Quality Flywheel.
Architectural Walkthrough: The 4-Stage Quality Flywheelβ
Improving an enterprise agent is a disciplined engineering loopβnever a single pass. Every stage in agents-cli eval pairs a Default Path (local, fast, works with AI Studio GEMINI_API_KEY or Google Cloud ADC) with an Opt-in Managed Scale Path powered by the Eval Service in Gemini platform and ADK's GEPA optimizer:
How the Four Stages Fit Togetherβ
- Stage 1 β Prepare Data: Start small (2β5 crisp cases in
tests/eval/datasets/). When you need dynamic multi-turn stress coverage without hand-scripting every turn, runagents-cli eval dataset synthesize. Becausesynthesizeexecutes your ADK agent against an LLM-backed user simulator, its output inartifacts/traces/traces_<ts>.jsonalready contains fullagent_data.turnstrajectoriesβso Stage 2 collapses toagents-cli eval gradealone. - Stage 2 β Run & Grade:
- Local synchronous:
agents-cli eval runstarts your project's HTTP server (app/fast_api_app.pyif scaffolded, oradk api_server), drives each case over/apps/app/...and/run_sse(or WebSocket/run_livewhen--mode adk_liveis passed), writes raw traces toartifacts/traces/, and grades them intoartifacts/grade_results/results_<YYYYMMDD_HHMMSS>.{json,html}. - Decoupled: Run
agents-cli eval generateonce (or point--url https://... --app-name appat a deployed staging service) and iterate onagents-cli eval gradewithout re-invoking the agent. - Cloud-side asynchronous (
eval submit/eval results): For large benchmark suites or non-blocking CI pipelines,agents-cli eval submit --dataset ... --dest gs://my-eval-bucket(optionally adding--resource-name projects/<p>/locations/<l>/reasoningEngines/<id>for server-side inference) hands execution to the managed Eval Service and returns a run resource ID thatagents-cli eval results --run-id <id>polls and downloads.
- Local synchronous:
- Stage 3 β Analyze Failures: Inspect judge rationales and per-rubric verdicts in
results_<ts>.html/.json. When 10+ cases fail across multi-turn conversations, runagents-cli eval analyzeto cluster failures into actionable root-cause categories. - Stage 4 β Fix, Optimize (GEPA) & Verify: Fix deterministic code, state callbacks (
before_agent_callback), and tool docstrings first. Only when remaining failures are purely instructional phrasing issues, run a single pass ofagents-cli eval optimize(GEPA), apply the winning prompt, and prove zero regressions viaagents-cli eval compareβgrading your untouched holdout dataset last to rule out overfitting.
Deep Dive: The Canonical EvaluationDataset Schemaβ
Every dataset and trace file in agents-cli eval validates against the EvaluationDataset Pydantic model ({"eval_cases": [...]}). Understanding its exact wrapper boundaries prevents the most common 400 INVALID_ARGUMENT and validation errors.
EvaluationDataset
βββ eval_cases: list[EvalCase]
βββ eval_case_id: str # Unique identifier for tracking regressions
βββ prompt: Content # Shape A (Single-Turn): bare Content {"role": "user", "parts": [...]}
βββ responses: list[ResponseCandidate] # Single-turn model output(s) β WRAPPED in {"response": Content}
βββ reference: ResponseCandidate # Golden answer β WRAPPED in {"response": Content}
βββ context: str | Content # Grounding source document (required by `grounding` metric)
βββ agent_data: AgentData # Shape B (Multi-Turn): full or N+1 conversation trajectory
β βββ agents: dict[str, AgentConfig] # Participating agent metadata & tool declarations
β βββ turns: list[ConversationTurn] # Sequential 0-based turn_index: 0, 1, ...
β βββ events: list[AgentEvent] # author ("user" | agent_id | "tool") + bare Content
βββ rubric_groups: dict[str, RubricGroup] # Case-specific pass/fail rubrics carried onto traces
1. Single-Turn Cases (Shape A) & The ResponseCandidate Wrapper Ruleβ
Notice the critical structural asymmetry in EvalCase:
prompt(andagent_data.turns[].events[].content) is a bareContentobject:{"role": "user", "parts": [{"text": "..."}]}.referenceand entries insideresponsesare wrapped inside aResponseCandidateobject:{"response": {"role": "model", "parts": [{"text": "..."}]}}.
Here is a valid single-turn EvaluationDataset case with both reference and per-case rubric_groups:
{
"eval_cases": [
{
"eval_case_id": "p1_ticket_triage_and_escalation",
"prompt": {
"role": "user",
"parts": [
{
"text": "Investigate ticket TCK-1042, check its SLA target, and escalate if required."
}
]
},
"reference": {
"response": {
"role": "model",
"parts": [
{
"text": "Ticket TCK-1042 for Acme Cloud Robotics (enterprise tier, P1 severity) has a 15-minute SLA response target and has been escalated to the 24/7 P1 SRE Oncall queue."
}
]
}
},
"rubric_groups": {
"sla_rubrics": {
"rubrics": [
{
"rubric_id": "cites_15_min_sla",
"content": {
"property": {
"description": "The response explicitly states the 15-minute P1 SLA response target for enterprise tier."
}
}
},
{
"rubric_id": "confirms_sre_escalation",
"content": {
"property": {
"description": "The response confirms escalation of TCK-1042 to the 24/7 P1 SRE Oncall queue."
}
}
}
]
}
}
}
]
}
2. Multi-Turn Cases (Shape B β Recorded Traces & The "N+1" Continuation Pattern)β
When evaluating multi-turn conversations or multi-agent handoffs, EvalCase uses agent_data instead of prompt.
- For inference (
eval generateover SSE), Shape B seeds prior turns inagent_data.turnsending with a trailing"user"event;eval generatereplays the history and records the agent'sN+1reply. (For--mode adk_livevoice/streaming agents, author user-only turns so the live session generates every reply organically.) - For grading (
eval grade),agent_data.turnscontains the full chronological trace with 0-basedturn_index(0, 1, ...) andevents[]whereauthoris"user", an agent ID declared inagent_data.agents(such as"support_ops_agent"), or"tool", with tool calls encoded asfunction_callandfunction_responseparts:
{
"eval_cases": [
{
"eval_case_id": "multi_turn_escalation_followup",
"agent_data": {
"agents": {
"support_ops_agent": {
"agent_id": "support_ops_agent",
"agent_type": "LlmAgent",
"instruction": "Triage tickets, verify SLA targets, and escalate P1 incidents."
}
},
"turns": [
{
"turn_index": 0,
"events": [
{
"author": "user",
"content": {
"role": "user",
"parts": [{"text": "Can you look up ticket TCK-1042?"}]
}
},
{
"author": "support_ops_agent",
"content": {
"role": "model",
"parts": [
{
"function_call": {
"name": "lookup_ticket",
"args": {"ticket_id": "TCK-1042"}
}
}
]
}
},
{
"author": "support_ops_agent",
"content": {
"role": "user",
"parts": [
{
"function_response": {
"name": "lookup_ticket",
"response": {
"status": "found",
"ticket_id": "TCK-1042",
"tier": "enterprise",
"severity": "P1"
}
}
}
]
}
},
{
"author": "support_ops_agent",
"content": {
"role": "model",
"parts": [{"text": "TCK-1042 is an open P1 enterprise ticket for Acme Cloud Robotics."}]
}
}
]
},
{
"turn_index": 1,
"events": [
{
"author": "user",
"content": {
"role": "user",
"parts": [{"text": "Check our SLA and page oncall immediately."}]
}
}
]
}
]
}
}
]
}
3. Critical Service & Schema Constraintsβ
[!WARNING] Memorize these five
EvaluationDatasetinvariants before running managed metrics:
- Always use
"role": "model"β NEVER"role": "assistant". Gemini platform conventions reject OpenAI-style"assistant"roles.- Sequential 0-based
turn_index: EveryConversationTurninagent_data.turnsmust carry sequential indices0, 1, 2, ..., and every event must have non-emptycontent(eval gradeautomatically strips empty state-delta-only events before calling the Eval Service).- NEVER mix
promptandagent_datain the sameEvalCase, AND NEVER mix single-turn and multi-turn cases in the same dataset when running single-turn managed metrics. Metrics ineval_config.yamlexecute against every case in the dataset. Passing a 2+ turn trace to a single-turn metric (final_response_quality,hallucination,safety,final_response_match) fails with HTTP400: Single-turn metric '<name>_v1' received agent_eval_data with N turns. Keep single-turn and multi-turn suites in separate dataset + config pairs!- Per-case
rubric_groupskey resolution: If a case defines multiple groups underrubric_groups, you must specify which key to grade viametric_spec_parameters.rubric_group_keyineval_config.yaml(otherwise the service returns HTTP400: Multiple rubric groups provided in instance but no rubric_group_key specified). Conversely, ifrubric_group_keynames a group missing on any case in that dataset, the service returns HTTP400: rubric_group_key '<name>' not found.- Never set
rubric_group_nameon a customLLMMetric:agents-clirejectsrubric_group_nameonprompt_templatemetrics because custom prompts cannot emit the internal proto rubric-verdict structure. Graderubric_groupseither with a single-turn managed rubric metric (final_response_quality+metric_spec_parameters.rubric_group_key) orβfor multi-turn tracesβwith a local Pythoncustom_function_filejudge readinginstance["rubric_groups"].
Local In-Process Metrics vs. Managed Gemini Platform Metricsβ
tests/eval/eval_config.yaml separates metric selection (metrics_to_run) from your project's custom definition pool (custom_metrics). Defining a metric under custom_metrics does not run it unless its name also appears in metrics_to_run (or --metrics on the CLI).
1. Local In-Process Metrics (custom_function_file & custom_function)β
Every ADK project scaffolded by agents-cli includes two out-of-the-box local metrics in tests/eval/eval_config.yaml:
custom_response_quality(custom_function_file: response_quality.py): A local in-process LLM-as-judge powered bygoogle-genai. Because it callsgenai.Client()inside your CLI process (execution: local, the default), it works seamlessly on both Google AI Studio (GEMINI_API_KEY) and Google Cloud (GOOGLE_CLOUD_PROJECT+ ADC), and works in any data-residency region! Notice howresponse_quality.pycaches onegenai.Client()per worker thread viathreading.local()so the SDK's grading thread pool neither repeats TLS/ADC handshakes per case nor shares mutable SSL contexts across threads, and enforces deterministic JSON output viatemperature=0+response_schema=_Verdict.- Inline Python (
custom_function:): Deterministic code checks (CodeExecutionMetricschema) that inspectinstance["prompt"],instance["response"],instance["agent_data"],instance.get("reference"), andinstance.get("rubric_groups")with zero LLM cost or latency. (Settingexecution: remoteuploads the Python function to the Gemini platformCodeExecutionMetricsandbox instead, which has no outbound network access and requires a GCP project.)
# tests/eval/eval_config.yaml
metrics_to_run:
- custom_response_quality
- sla_and_ticket_check
- final_response_quality
custom_metrics:
# 1. Local thread-safe LLM-as-judge (runs on GEMINI_API_KEY or GCP ADC)
- name: custom_response_quality
custom_function_file: response_quality.py
# 2. Deterministic in-process Python verifier (zero API calls, 100% repeatable)
- name: sla_and_ticket_check
custom_function: |
def evaluate(instance):
resp_parts = (instance.get("response") or {}).get("parts", [])
text = " ".join(p.get("text", "") for p in resp_parts).lower()
has_sla = any(tok in text for tok in ("15 minutes", "15-minute", "24 business hours", "not found"))
return {
"score": 1.0 if has_sla else 0.0,
"explanation": "Verified explicit SLA target or not-found handling in final response.",
}
# 3. Managed metric parameterization (selects which rubric_groups key to grade)
- name: final_response_quality
metric_spec_parameters:
rubric_group_key: sla_rubrics
2. Managed Gemini Platform Metrics Matrixβ
When authenticated to Google Cloud (agents-cli login / ADC), eval grade and eval run talk to the Eval Service in Gemini platform (defaulting to --region global, independent of your manifest's deployment region; throttle dispatch rate with --qps 5 if you hit judge quota limits):
| Metric ID | Category | Multi-Turn Trace Support? | What It Evaluates & Required Case Fields |
|---|---|---|---|
multi_turn_task_success | Adaptive Rubric | Yes (Any) | Did the agent fulfill the user's overall goal across turns? (Ignores case rubric_groups.) |
multi_turn_trajectory_quality | Adaptive Rubric | Yes (Any) | Logical step ordering, efficiency, and error recovery across turns. |
multi_turn_tool_use_quality | Adaptive Rubric | Yes (Any) | Semantic & technical accuracy of function_call names and arguments across turns (replaces brittle exact-sequence matching!). |
final_response_quality | Adaptive Rubric | Single-turn only (400 on 2+ turns) | Holistic response + intermediate tool quality; grades case rubric_groups when supplied! |
hallucination | Static Rubric | Single-turn only (400 on 2+ turns) | Segments final response into atomic claims and verifies each against tool outputs. |
safety | Static Rubric | Single-turn only (400 on 2+ turns) | Compliance against PII, hate speech, harassment, and dangerous content policies. |
final_response_match | Static Rubric | Single-turn only (400 on 2+ turns) | Semantic equivalence to a golden answer (requires reference wrapped in ResponseCandidate). |
CRITICAL OPERATIONAL GOTCHA: Why eval run & eval grade Always Exit 0β
[!CAUTION]
agents-cli eval runandagents-cli eval gradeALWAYS exit with status code0whenever evaluation execution completesβeven if every single metric scores0.0!A non-zero exit code from
agents-cli eval runonly indicates an infrastructure or schema crash (for example, malformed JSON, missing GCP credentials, or an unsupported--region), never a low quality score. Moreover, if individual cases error out during grading (such as HTTP429rate limits),_warn_on_dropped_caseslogs a warning while summary averages are computed only over cases that completed!
Because exit code 0 means "the benchmark finished running" rather than "the agent passed quality standards", production AgentOps requires three mandatory practices:
- Always inspect
artifacts/grade_results/results_<ts>.{json,html}: Readsummary_metrics(mean scores andnum_cases_errorcounts) plus per-case judge explanations andrubric_verdicts. - Always diff before/after fixes with
agents-cli eval compare:agents-cli eval compare \
artifacts/grade_results/results_20261201_090000.json \
artifacts/grade_results/results_20261201_091500.jsoneval compareruns 100% in-process (zero network/LLM calls) and emits recursive dotted-key deltas ("delta": "+0.25"or"-0.10") so you catch silent regressions on existing cases immediately. - Enforce an explicit score-threshold gate before deployment: Never wire bare
agents-cli eval runinto CI/CD expecting GitHub Actions or Cloud Build to stop on a0.2score. Always parseresults_<ts>.jsonin a Python gate script that exits non-zero when any required metric falls below threshold ornum_cases_error > 0βwhich you will wire directly into anagents-cli-extension.yamldeployoverride in Module 30.3!
Stage 2, 3 & 4 Deep Dive: User Simulation, Failure Clustering & GEPAβ
Stage 2 Opt-In: Dynamic User Simulation (agents-cli eval dataset synthesize)β
Static prompts cannot test what happens when an impatient VP demands an escalation without knowing their ticket ID, or changes questions mid-conversation. In ADK Python projects, agents-cli eval dataset synthesize reads agent_directory from agents-cli-manifest.yaml, inspects support_ops_agent's instruction and tool docstrings (lookup_ticket, check_sla_policy, escalate_ticket), asks the Eval Service (at GOOGLE_CLOUD_LOCATION, keep global) to generate realistic {starting_prompt, conversation_plan} scenarios, and plays each scenario locally against ADK's LLM-backed user simulator:
# Synthesize 5 dynamic multi-turn scenarios (up to 6 turns each) and write
# graded-ready traces directly to artifacts/traces/traces_<ts>.json:
agents-cli eval dataset synthesize \
-n 5 \
--max-turns 6 \
--model gemini-3.8-flash \
--instruction "Enterprise and standard customers reporting urgent outages, unknown ticket IDs, or disputing SLA windows" \
--environment-context "Valid sample tickets in DB are TCK-1042 (P1 enterprise) and TCK-2088 (P3 standard)."
# Skip `eval generate` β synthesized files already contain populated agent_data.turns!
# Grade strictly with multi-turn adaptive metrics:
agents-cli eval grade \
--metrics multi_turn_task_success,multi_turn_trajectory_quality,multi_turn_tool_use_quality
Engineering tip: Scenario quality is a direct mirror of your agent's metadata. If synthesize invents unrealistic user prompts, tighten your tool docstrings and parameter descriptions first! Also remember that synthesize has no random seedβevery invocation explores fresh scenariosβso promote high-value discovered edge cases into committed Shape B regression files.
Stage 3 Opt-In: Automated Failure Clustering (agents-cli eval analyze)β
When an evaluation run across synthesized or production-sampled traces yields 10+ failing conversations, agents-cli eval analyze (global endpoint) clusters loss patterns across judge rationales and ranks the top root-cause buckets:
agents-cli eval analyze \
--eval-result artifacts/grade_results/results_20261201_103000.json \
--metric multi_turn_tool_use_quality \
--top-k 5 \
--output artifacts/analysis_tool_use.json \
--output-format json
Supported --metric targets for eval analyze are multi_turn_task_success and multi_turn_tool_use_quality. Each cluster highlights whether failures stem from tool/code defects (wrong schema, missing state initialization, broken lookup logic) or instructional ambiguity (agent forgetting to cite SLA hours after escalating).
Stage 4 Opt-In: Prompt Optimization with GEPA (agents-cli eval optimize)β
Onceβand only onceβdeterministic tool bugs, state callbacks, and orchestration structure are fixed, you can refine root_agent's system instructions automatically using GEPA (Genetic-Pareto Prompt Optimization), integrated into agents-cli eval optimize (wrapping uv run adk optimize and GEPARootAgentPromptOptimizerConfig).
# Drive repeatable train/validation GEPA optimization from tests/eval/optimization_config.json:
agents-cli eval optimize --config tests/eval/optimization_config.json
Under the hood, agents-cli eval optimize:
- Syncs ADK evaluation extras (
uv sync --dev --extra eval). - Reads
tests/eval/optimization_config.json, converts yourtrain_datasetandvalidation_datasetEvaluationDatasetJSON files into temporary ADK evalsets insideapp/.tmp/(mappingreferenceto target responses andrubric_groupsto ADK rubrics), and cleans them up automatically in afinally:block. - Launches GEPA with
GEPARootAgentPromptOptimizerConfig, which iteratively evaluates minibatches (reflection_minibatch_size), reflects on failing judge rationales usingoptimizer_model(gemini-3.8-flash), mutates candidate instructions along a Pareto frontier, and scores candidates onvalidation_datasetup tomax_metric_calls.
Here is a production-grade tests/eval/optimization_config.json:
{
"train_dataset": "tests/eval/datasets/support-triage-dataset.json",
"validation_dataset": "tests/eval/datasets/support-holdout-dataset.json",
"eval_config": {
"criteria": {
"rubric_based_final_response_quality_v1": 0.85,
"hallucinations_v1": 0.9
}
},
"optimizer_config": {
"optimizer_model": "gemini-3.8-flash",
"max_metric_calls": 24,
"reflection_minibatch_size": 3,
"run_dir": "artifacts/gepa_runs"
},
"log_level": "INFO",
"print_detailed_results": true
}
[!IMPORTANT] Three Golden Rules for GEPA (
agents-cli eval optimize):
- Never use GEPA to mask broken tools or orchestration: If
lookup_ticketcrashes orbefore_agent_callbackforgets to initialize{user:customer_tier}, prompt mutation will waste dozens of LLM calls trying to talk around a Python bug. Fix code and tool docstrings manually first!- Always supply a separate
validation_dataset(and keep a final holdout set): Ifvalidation_datasetis omitted,eval optimizelogs a warning and falls back to validating ontrain_dataset, inviting prompt overfitting to your training examples.- Run GEPA as a single bounded passβnever in an automated loop: GEPA makes up to
max_metric_callsfull agent + judge evaluations. Iterate manually first, run one boundedeval optimizepass, paste the winning instruction intoapp/agent.py, and confirm the gain withagents-cli eval run+agents-cli eval compare.
Your team wires `agents-cli eval run --dataset tests/eval/datasets/support-triage-dataset.json` into a pull-request check and also adds two multi-turn `agent_data` traces into that same JSON file alongside `final_response_quality` in `eval_config.yaml`. What two operational traps will hit this setup?
Key Takeawaysβ
- 4-Stage Quality Flywheel: Iterate systematically through Prepare Data (
EvaluationDataset/eval dataset synthesize) β Run & Grade (eval run,eval generate+eval grade, or cloud-sideeval submit/eval results) β Analyze (results_<ts>.html/eval analyze) β Fix, Optimize & Compare (manual code/tool fixes β bounded GEPAeval optimizeβeval compare+ holdout verification). EvaluationDatasetPrecision: Single-turnpromptand turnevents[].contentare bareContentobjects, whereasresponses[]andreferencewrapContentinsideResponseCandidate({"response": {"role": "model", "parts": [...]}}). Always userole="model", sequentialturn_index: 0, 1, ..., and separate single-turn (prompt) datasets from multi-turn (agent_data) datasets.- Hybrid Local + Managed Grading: Combine zero-cost deterministic Python
custom_functionchecks and thread-localcustom_function_fileLLM judges (response_quality.py, compatible with bothGEMINI_API_KEYand GCP ADC) with managed adaptive-rubric metrics (multi_turn_task_success,multi_turn_tool_use_quality,final_response_quality). - Exit Code
0Mandate:agents-cli eval runandeval gradeexit0regardless of metric scores. Always inspectartifacts/grade_results/results_<ts>.json, diff runs withagents-cli eval compare, and enforce a programmatic score-threshold gate (which you will automate as a CLI extension in Module 30.3). - Disciplined GEPA Optimization: Use
agents-cli eval optimize(tests/eval/optimization_config.json) strictly for prompt phrasing refinement after deterministic tool and state bugs are resolved, always pairingtrain_datasetwith a distinctvalidation_dataset.