Skip to main content

Module 30.2: The Quality Flywheel β€” GenAI Eval, User Simulation & GEPA

Theory​

The Quality Flywheel β€” GenAI Eval, User Simulation & GEPA (Light) The Quality Flywheel β€” GenAI Eval, User Simulation & GEPA (Dark) 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:

  1. 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.
  2. 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.
  3. 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.
  4. 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 compare and 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​

  1. 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, run agents-cli eval dataset synthesize. Because synthesize executes your ADK agent against an LLM-backed user simulator, its output in artifacts/traces/traces_<ts>.json already contains full agent_data.turns trajectoriesβ€”so Stage 2 collapses to agents-cli eval grade alone.
  2. Stage 2 β€” Run & Grade:
    • Local synchronous: agents-cli eval run starts your project's HTTP server (app/fast_api_app.py if scaffolded, or adk api_server), drives each case over /apps/app/... and /run_sse (or WebSocket /run_live when --mode adk_live is passed), writes raw traces to artifacts/traces/, and grades them into artifacts/grade_results/results_<YYYYMMDD_HHMMSS>.{json,html}.
    • Decoupled: Run agents-cli eval generate once (or point --url https://... --app-name app at a deployed staging service) and iterate on agents-cli eval grade without 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 that agents-cli eval results --run-id <id> polls and downloads.
  3. Stage 3 β€” Analyze Failures: Inspect judge rationales and per-rubric verdicts in results_<ts>.html / .json. When 10+ cases fail across multi-turn conversations, run agents-cli eval analyze to cluster failures into actionable root-cause categories.
  4. 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 of agents-cli eval optimize (GEPA), apply the winning prompt, and prove zero regressions via agents-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 (and agent_data.turns[].events[].content) is a bare Content object: {"role": "user", "parts": [{"text": "..."}]}.
  • reference and entries inside responses are wrapped inside a ResponseCandidate object: {"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 generate over SSE), Shape B seeds prior turns in agent_data.turns ending with a trailing "user" event; eval generate replays the history and records the agent's N+1 reply. (For --mode adk_live voice/streaming agents, author user-only turns so the live session generates every reply organically.)
  • For grading (eval grade), agent_data.turns contains the full chronological trace with 0-based turn_index (0, 1, ...) and events[] where author is "user", an agent ID declared in agent_data.agents (such as "support_ops_agent"), or "tool", with tool calls encoded as function_call and function_response parts:
{
"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 EvaluationDataset invariants before running managed metrics:

  1. Always use "role": "model" β€” NEVER "role": "assistant". Gemini platform conventions reject OpenAI-style "assistant" roles.
  2. Sequential 0-based turn_index: Every ConversationTurn in agent_data.turns must carry sequential indices 0, 1, 2, ..., and every event must have non-empty content (eval grade automatically strips empty state-delta-only events before calling the Eval Service).
  3. NEVER mix prompt and agent_data in the same EvalCase, AND NEVER mix single-turn and multi-turn cases in the same dataset when running single-turn managed metrics. Metrics in eval_config.yaml execute 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 HTTP 400: Single-turn metric '<name>_v1' received agent_eval_data with N turns. Keep single-turn and multi-turn suites in separate dataset + config pairs!
  4. Per-case rubric_groups key resolution: If a case defines multiple groups under rubric_groups, you must specify which key to grade via metric_spec_parameters.rubric_group_key in eval_config.yaml (otherwise the service returns HTTP 400: Multiple rubric groups provided in instance but no rubric_group_key specified). Conversely, if rubric_group_key names a group missing on any case in that dataset, the service returns HTTP 400: rubric_group_key '<name>' not found.
  5. Never set rubric_group_name on a custom LLMMetric: agents-cli rejects rubric_group_name on prompt_template metrics because custom prompts cannot emit the internal proto rubric-verdict structure. Grade rubric_groups either with a single-turn managed rubric metric (final_response_quality + metric_spec_parameters.rubric_group_key) orβ€”for multi-turn tracesβ€”with a local Python custom_function_file judge reading instance["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 by google-genai. Because it calls genai.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 how response_quality.py caches one genai.Client() per worker thread via threading.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 via temperature=0 + response_schema=_Verdict.
  • Inline Python (custom_function:): Deterministic code checks (CodeExecutionMetric schema) that inspect instance["prompt"], instance["response"], instance["agent_data"], instance.get("reference"), and instance.get("rubric_groups") with zero LLM cost or latency. (Setting execution: remote uploads the Python function to the Gemini platform CodeExecutionMetric sandbox 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 IDCategoryMulti-Turn Trace Support?What It Evaluates & Required Case Fields
multi_turn_task_successAdaptive RubricYes (Any)Did the agent fulfill the user's overall goal across turns? (Ignores case rubric_groups.)
multi_turn_trajectory_qualityAdaptive RubricYes (Any)Logical step ordering, efficiency, and error recovery across turns.
multi_turn_tool_use_qualityAdaptive RubricYes (Any)Semantic & technical accuracy of function_call names and arguments across turns (replaces brittle exact-sequence matching!).
final_response_qualityAdaptive RubricSingle-turn only (400 on 2+ turns)Holistic response + intermediate tool quality; grades case rubric_groups when supplied!
hallucinationStatic RubricSingle-turn only (400 on 2+ turns)Segments final response into atomic claims and verifies each against tool outputs.
safetyStatic RubricSingle-turn only (400 on 2+ turns)Compliance against PII, hate speech, harassment, and dangerous content policies.
final_response_matchStatic RubricSingle-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 run and agents-cli eval grade ALWAYS exit with status code 0 whenever evaluation execution completesβ€”even if every single metric scores 0.0!

A non-zero exit code from agents-cli eval run only 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 HTTP 429 rate limits), _warn_on_dropped_cases logs 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:

  1. Always inspect artifacts/grade_results/results_<ts>.{json,html}: Read summary_metrics (mean scores and num_cases_error counts) plus per-case judge explanations and rubric_verdicts.
  2. 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.json
    eval compare runs 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.
  3. Enforce an explicit score-threshold gate before deployment: Never wire bare agents-cli eval run into CI/CD expecting GitHub Actions or Cloud Build to stop on a 0.2 score. Always parse results_<ts>.json in a Python gate script that exits non-zero when any required metric falls below threshold or num_cases_error > 0β€”which you will wire directly into an agents-cli-extension.yaml deploy override 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:

  1. Syncs ADK evaluation extras (uv sync --dev --extra eval).
  2. Reads tests/eval/optimization_config.json, converts your train_dataset and validation_dataset EvaluationDataset JSON files into temporary ADK evalsets inside app/.tmp/ (mapping reference to target responses and rubric_groups to ADK rubrics), and cleans them up automatically in a finally: block.
  3. Launches GEPA with GEPARootAgentPromptOptimizerConfig, which iteratively evaluates minibatches (reflection_minibatch_size), reflects on failing judge rationales using optimizer_model (gemini-3.8-flash), mutates candidate instructions along a Pareto frontier, and scores candidates on validation_dataset up to max_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):

  1. Never use GEPA to mask broken tools or orchestration: If lookup_ticket crashes or before_agent_callback forgets 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!
  2. Always supply a separate validation_dataset (and keep a final holdout set): If validation_dataset is omitted, eval optimize logs a warning and falls back to validating on train_dataset, inviting prompt overfitting to your training examples.
  3. Run GEPA as a single bounded passβ€”never in an automated loop: GEPA makes up to max_metric_calls full agent + judge evaluations. Iterate manually first, run one bounded eval optimize pass, paste the winning instruction into app/agent.py, and confirm the gain with agents-cli eval run + agents-cli eval compare.

🎯 Knowledge CheckSelect Best Answer

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-side eval submit / eval results) β†’ Analyze (results_<ts>.html / eval analyze) β†’ Fix, Optimize & Compare (manual code/tool fixes β†’ bounded GEPA eval optimize β†’ eval compare + holdout verification).
  • EvaluationDataset Precision: Single-turn prompt and turn events[].content are bare Content objects, whereas responses[] and reference wrap Content inside ResponseCandidate ({"response": {"role": "model", "parts": [...]}}). Always use role="model", sequential turn_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_function checks and thread-local custom_function_file LLM judges (response_quality.py, compatible with both GEMINI_API_KEY and GCP ADC) with managed adaptive-rubric metrics (multi_turn_task_success, multi_turn_tool_use_quality, final_response_quality).
  • Exit Code 0 Mandate: agents-cli eval run and eval grade exit 0 regardless of metric scores. Always inspect artifacts/grade_results/results_<ts>.json, diff runs with agents-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 pairing train_dataset with a distinct validation_dataset.
πŸ“–

30.2: Quality Flywheel, Simulation & GEPA(Theory & Overview)

Part 6: AgentOps & Google Agents CLI β€’ Module 30.2

Overall Course Progress:
0%(0/98)
Next Step: Challenge Lab πŸ§ͺ β†’