Lab 30.2: Running the Quality Flywheel on support-ops-agent
Goalβ
In this hands-on Dual-Track Challenge Lab, you will take the enterprise support-ops-agent (gemini-3.8-flash) from Module 30.1 and engineer its end-to-end Quality Flywheel:
- Step 1 (Shared Foundation): Author a canonical
EvaluationDataset(tests/eval/datasets/support-triage-dataset.json) plus a separate holdout validation dataset (tests/eval/datasets/support-holdout-dataset.json) using validResponseCandidatewrappers andrubric_groups.sla_rubrics, and wire a deterministic Pythoncustom_function(sla_and_ticket_check) alongsidecustom_response_qualityintests/eval/eval_config.yaml. - Step 2 β Choose Your Execution Track:
- Track A (Google Cloud + ADC): Run the full managed Quality Flywheelβ
agents-cli eval run, dynamic multi-turn user simulation (agents-cli eval dataset synthesize), automated failure clustering (agents-cli eval analyze), bounded GEPA prompt optimization (agents-cli eval optimizeviatests/eval/optimization_config.json), and regression diffing (agents-cli eval compare). - Track B (100% Local / AI Studio
GEMINI_API_KEYor Offline): Run local trace generation and in-process grading (custom_response_quality+sla_and_ticket_check) and implement a production-grade Quality Flywheel & Schema Gate (scripts/validate_eval_flywheel.py) that validates single-turn and multi-turnEvaluationDatasetinvariants, gradessupport-ops-agenttraces deterministically, auditsoptimization_config.json, and enforces a non-zero exit code when scores fall below threshold!
- Track A (Google Cloud + ADC): Run the full managed Quality Flywheelβ
Environment setup:
- 1-Click Launch (Browser): Open in GitHub CodespacesOpen in Google Cloud Shell
- Local machine: If you're continuing the course in sequence,
cdinto theadk-trainingproject you created in Module 2 and skip the block below -- your environment and dependencies already carry forward. If you're starting fresh at this module, create that project first:uv init adk-training --python 3.10 && cd adk-training
uv add "google-adk>=2.1.0" python-dotenv- DevContainer / Codespaces (Alternative): If you opened this repository in a DevContainer or GitHub Codespaces, Python 3.11,
uv,gcloud, and all core ADK dependencies are pre-installed in your container environment.
Prerequisitesβ
- Python 3.10+,
uv, andgoogle-agents-cli(v1.10+) installed (uv tool install google-agents-cli). - Your
support-ops-agentproject from Module 30.1 (or use the 10-second fast-bootstrap below).
Step 0: Reuse or Fast-Bootstrap support-ops-agentβ
If you already built support-ops-agent/ in Module 30.1, cd into it. Otherwise, fast-bootstrap it from your adk-training workspace directory (remember: never mkdir before agents-cli create):
cd /path/to/your/adk-training
# Run ONLY if support-ops-agent/ does not exist yet:
agents-cli create support-ops-agent \
--agent adk \
--prototype \
--agent-guidance-filename GEMINI.md \
--skip-checks -y
curl -fsSL https://mauripsale.github.io/doc-adk-training/samples/part6/agent.py \
-o support-ops-agent/app/agent.py
cd support-ops-agent
agents-cli info
Verify one quick check before starting: open tests/eval/response_quality.py and confirm the judge generate_content(...) call uses model="gemini-3.8-flash".
Step 1 (Shared): Author EvaluationDataset Suites & Hybrid eval_config.yamlβ
1.1 Create tests/eval/datasets/support-triage-dataset.jsonβ
Create tests/eval/datasets/support-triage-dataset.json with three single-turn (Shape A) cases covering support-ops-agent's ticket database (TCK-1042 P1 enterprise, TCK-2088 P3 standard, and TCK-9999 unknown ticket).
Fill in every TODO placeholder while honoring all EvaluationDataset rules from the Theory section ("role": "model"βnever "assistant", reference wrapped inside {"response": ...}, and rubric_groups.sla_rubrics present on every case):
{
"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": "TODO_ROLE",
"parts": [
{
"text": "TODO: Write expected summary for TCK-1042 (Acme Cloud Robotics, enterprise tier, P1 severity, 15 minutes SLA target, escalated to 24/7 P1 SRE Oncall)."
}
]
}
},
"rubric_groups": {
"sla_rubrics": {
"rubrics": [
{
"rubric_id": "cites_15_min_sla",
"content": {
"property": {
"description": "TODO: Require explicit mention of the 15-minute enterprise P1 SLA target."
}
}
},
{
"rubric_id": "escalates_to_sre_oncall",
"content": {
"property": {
"description": "TODO: Require confirmation that TCK-1042 was escalated to the 24/7 P1 SRE Oncall queue."
}
}
}
]
}
}
},
{
"eval_case_id": "standard_ticket_sla_lookup",
"prompt": {
"role": "user",
"parts": [
{
"text": "What is the current status and applicable SLA response target for ticket TCK-2088?"
}
]
},
"reference": {
"response": {
"role": "TODO_ROLE",
"parts": [
{
"text": "TODO: Write expected summary for TCK-2088 (Northwind Retail, standard tier, P3 investigating status, 24 business hours SLA target, no escalation)."
}
]
}
},
"rubric_groups": {
"sla_rubrics": {
"rubrics": [
{
"rubric_id": "cites_24_business_hours",
"content": {
"property": {
"description": "TODO: Require explicit mention of the 24 business hours P3 SLA target for standard tier without escalating."
}
}
}
]
}
}
},
{
"eval_case_id": "unknown_ticket_graceful_handling",
"prompt": {
"role": "user",
"parts": [
{
"text": "Please check the status of ticket TCK-9999."
}
]
},
"reference": {
"response": {
"role": "TODO_ROLE",
"parts": [
{
"text": "TODO: State clearly that ticket TCK-9999 was not found and do not fabricate ticket details or escalate."
}
]
}
},
"rubric_groups": {
"sla_rubrics": {
"rubrics": [
{
"rubric_id": "reports_not_found_without_hallucination",
"content": {
"property": {
"description": "TODO: Require stating TCK-9999 was not found without inventing customer or SLA details."
}
}
}
]
}
}
}
]
}
1.2 Create Holdout Validation Dataset tests/eval/datasets/support-holdout-dataset.jsonβ
To prevent overfitting during manual prompt edits or GEPA optimization, create a separate 2-case holdout file at tests/eval/datasets/support-holdout-dataset.json (complete the TODO fields using the same EvaluationDataset structure):
{
"eval_cases": [
{
"eval_case_id": "holdout_standard_explicit_escalation",
"prompt": {
"role": "user",
"parts": [
{
"text": "Ticket TCK-2088 is blocking our quarter-end close. Check our SLA and escalate it right now."
}
]
},
"reference": {
"response": {
"role": "TODO_ROLE",
"parts": [
{
"text": "TODO: Summarize TCK-2088 (standard tier, 24 business hours P3 SLA) and confirm escalation to Tier-2 Engineering Queue."
}
]
}
},
"rubric_groups": {
"sla_rubrics": {
"rubrics": [
{
"rubric_id": "escalates_standard_to_tier2",
"content": {
"property": {
"description": "TODO: Confirm escalation of TCK-2088 to Tier-2 Engineering Queue while citing standard-tier SLA."
}
}
}
]
}
}
},
{
"eval_case_id": "holdout_case_insensitive_p1",
"prompt": {
"role": "user",
"parts": [
{
"text": "Status and SLA check on tck-1042 please."
}
]
},
"reference": {
"response": {
"role": "TODO_ROLE",
"parts": [
{
"text": "TODO: Confirm TCK-1042 is open P1 enterprise (15 minutes SLA) and escalated to 24/7 P1 SRE Oncall."
}
]
}
},
"rubric_groups": {
"sla_rubrics": {
"rubrics": [
{
"rubric_id": "handles_lowercase_p1_ticket",
"content": {
"property": {
"description": "TODO: Normalize tck-1042, cite 15-minute SLA, and escalate to 24/7 P1 SRE Oncall."
}
}
}
]
}
}
}
]
}
1.3 Configure tests/eval/eval_config.yaml with custom_response_quality & sla_and_ticket_checkβ
Update tests/eval/eval_config.yaml so both custom_response_quality (response_quality.py) and a deterministic Python custom_function named sla_and_ticket_check are selected in metrics_to_run.
Complete the # TODO logic inside sla_and_ticket_check so that:
- If the user prompt mentions
TCK-1042, the final response text must cite"15 minute"(or"15-minute") and"sre"(case-insensitive). - If the user prompt mentions
TCK-2088, the final response text must cite"24 business hours". - If the user prompt mentions
TCK-9999, the final response text must mention"not found"(or"unknown"). - Return
{"score": 1.0, "explanation": "..."}when matched, or{"score": 0.0, "explanation": "..."}when missing!
# tests/eval/eval_config.yaml
metrics_to_run:
- custom_response_quality
- sla_and_ticket_check
custom_metrics:
- name: custom_response_quality
custom_function_file: response_quality.py
- name: sla_and_ticket_check
custom_function: |
def evaluate(instance):
def _extract_text(obj):
if isinstance(obj, str):
return obj
if isinstance(obj, dict):
parts = obj.get("parts") or (obj.get("response") or {}).get("parts") or []
return " ".join(p.get("text", "") for p in parts if isinstance(p, dict))
return ""
prompt_text = _extract_text(instance.get("prompt")).lower()
response_text = _extract_text(instance.get("response")).lower()
# TODO: Implement deterministic SLA & ticket verification rules for
# tck-1042 ("15 minute"/"15-minute" and "sre"),
# tck-2088 ("24 business hours"), and
# tck-9999 ("not found" or "unknown").
# Return {"score": 1.0 or 0.0, "explanation": "<clear diagnostic reason>"}
raise NotImplementedError("TODO: Implement sla_and_ticket_check")
# Parameterized managed metric ready when running Track A on Google Cloud:
- name: final_response_quality
metric_spec_parameters:
rubric_group_key: sla_rubrics
Step 2: Choose Your Trackβ
Pick Track A if you have an active Google Cloud project with Application Default Credentials (agents-cli login / gcloud auth application-default login), or Track B if you are running locally with an AI Studio GEMINI_API_KEY or 100% offline with zero cloud billing. (We encourage Track A students to also run Track B's schema & score gate scriptβit becomes your deploy gate foundation in Module 30.3!)
βοΈ Track A: Google Cloud + ADC (Managed Eval, User Simulation, Analyze & GEPA)β
-
Stage 1 & 2 β Run Baseline Evaluation (
eval run): Ensure.envsetsGOOGLE_GENAI_USE_ENTERPRISE=true(orGOOGLE_GENAI_USE_VERTEXAI=TRUE),GOOGLE_CLOUD_PROJECT=<your-project-id>, andGOOGLE_CLOUD_LOCATION=global, then execute both your local metrics and managedfinal_response_quality(which gradesrubric_groups.sla_rubrics):agents-cli eval run \
--dataset tests/eval/datasets/support-triage-dataset.json \
--metrics custom_response_quality,sla_and_ticket_check,final_response_quality \
--config tests/eval/eval_config.yamlRecord the generated baseline JSON path (
artifacts/grade_results/results_<baseline_ts>.json) and open the sibling.htmlreport. Verify thateval runexited0βand checksummary_metricsin the JSON directly rather than trusting the shell exit code! -
Stage 2 Opt-In β Synthesize Multi-Turn User Simulation Traces (
eval dataset synthesize): Generate 4 dynamic multi-turn conversations (up to 6 turns each) and grade them strictly with multi-turn adaptive metrics (remember: never pass single-turn metrics likefinal_response_qualityto multi-turn traces!):agents-cli eval dataset synthesize \
-n 4 \
--max-turns 6 \
--model gemini-3.8-flash \
--instruction "Simulate enterprise and standard customers reporting P1 outages, missing ticket IDs, or requesting urgent escalations" \
--environment-context "Known tickets in TICKET_DB: TCK-1042 (enterprise, P1) and TCK-2088 (standard, P3)." \
-o artifacts/traces/synthesized_support_traces.json
agents-cli eval grade \
--traces artifacts/traces/synthesized_support_traces.json \
--metrics multi_turn_task_success,multi_turn_trajectory_quality,multi_turn_tool_use_quality -
Stage 3 Opt-In β Cluster Failure Modes (
eval analyze): Run LLM-based failure clustering over your multi-turn grade results file:# Replace <multiturn_ts> with the timestamp printed by `eval grade` above:
agents-cli eval analyze \
--eval-result artifacts/grade_results/results_<multiturn_ts>.json \
--metric multi_turn_tool_use_quality \
--top-k 5 \
--output artifacts/analysis_tool_use.json -
Stage 4 Opt-In β Configure & Run Bounded GEPA Prompt Optimization (
eval optimize): Createtests/eval/optimization_config.jsonby completing theTODOfields below so GEPA trains onsupport-triage-dataset.json, validates onsupport-holdout-dataset.json, and usesgemini-3.8-flashwith a boundedmax_metric_callsbudget:{
"train_dataset": "TODO_TRAIN_DATASET_PATH",
"validation_dataset": "TODO_HOLD_OUT_VALIDATION_DATASET_PATH",
"eval_config": {
"criteria": {
"rubric_based_final_response_quality_v1": 0.85
}
},
"optimizer_config": {
"optimizer_model": "TODO_FLASH_MODEL",
"max_metric_calls": 18,
"reflection_minibatch_size": 3,
"run_dir": "artifacts/gepa_runs"
},
"log_level": "INFO",
"print_detailed_results": true
}Run a single bounded optimization pass, apply any improved instruction phrasing to
app/agent.py, re-runeval runon both your triage and holdout datasets, and prove zero regressions witheval compare:agents-cli eval optimize --config tests/eval/optimization_config.json
# Re-run after applying prompt improvements:
agents-cli eval run \
--dataset tests/eval/datasets/support-triage-dataset.json \
--metrics custom_response_quality,sla_and_ticket_check,final_response_quality \
--config tests/eval/eval_config.yaml
# Diff baseline vs. candidate in-process:
agents-cli eval compare \
artifacts/grade_results/results_<baseline_ts>.json \
artifacts/grade_results/results_<candidate_ts>.json
# Final generalization check on your untouched holdout set:
agents-cli eval run \
--dataset tests/eval/datasets/support-holdout-dataset.json \
--metrics custom_response_quality,sla_and_ticket_check,final_response_quality \
--config tests/eval/eval_config.yaml
π» Track B: Local / AI Studio GEMINI_API_KEY or 100% Offline Validation Gateβ
-
Optional Live Local Grading (if
GEMINI_API_KEYis set in.env): Becausecustom_response_quality(response_quality.py) andsla_and_ticket_checkboth run in-process (execution: local), you can generate real agent traces and grade them locally with zero GCP project required:agents-cli eval generate \
--dataset tests/eval/datasets/support-triage-dataset.json \
-o artifacts/traces/local_triage/
agents-cli eval grade \
--traces artifacts/traces/local_triage/ \
--config tests/eval/eval_config.yaml \
--metrics custom_response_quality,sla_and_ticket_check -
Required Challenge β Implement
scripts/validate_eval_flywheel.py& Multi-Turn Fixture: First, createtests/eval/datasets/support-multiturn-trace-fixture.json(or let your script verify any trace inartifacts/traces/) andtests/eval/optimization_config.json(using the JSON skeleton in Track A Step 4 aboveβeven offline, your validator will audit its schema!).Next, create
scripts/validate_eval_flywheel.pyusing the# TODOskeleton below. Your script must:- TODO 1 (
validate_evaluation_dataset): EnforceEvaluationDatasetinvariants on any JSON dataset:- Non-empty
eval_caseslist; every case has EITHERpromptORagent_data(never both, and never mix single-turn and multi-turn cases inside the same dataset file). - Reject
"role": "assistant"anywhere inprompt,reference,responses, oragent_data.turns[].events[].content(must be"user"or"model"). - Verify
reference(when present) is wrapped insideResponseCandidate({"response": {"role": "model", "parts": [...]}}) rather than a bareContentdict, and verifyrubric_groups.sla_rubrics.rubricshas non-emptycontent.property.descriptionstrings. - For multi-turn
agent_datacases, verifyturnsuses sequential 0-basedturn_index(0, 1, ...) and non-emptyevents.
- Non-empty
- TODO 2 (
load_custom_metric_fn& deterministic trace grading): Loadsla_and_ticket_checkdynamically fromtests/eval/eval_config.yaml(exec-ing itscustom_functionstring into a local namespace), evaluate each case insupport-triage-dataset.json(using real traces fromartifacts/traces/local_triage/if present, or each case'sreference.responseplusapp/agent.pytool outputslookup_ticket/check_sla_policy/escalate_ticket), and compute the mean score. - TODO 3 (
enforce_score_gate): Write a timestampedartifacts/grade_results/results_local_gate.jsonscorecard, verifytests/eval/optimization_config.jsonuses distincttrain_datasetvs.validation_datasetpaths and an approved Flash model (gemini-3.8-flash,gemini-3.7-flash, orgemini-3.6-flash), and exit with code1if mean score< 0.85or any schema check fails!
"""
Local Quality Flywheel Validator & Score-Threshold Gate (`support-ops-agent`).
Validates EvaluationDataset (Shape A & Shape B), executes deterministic custom_function
metrics from eval_config.yaml, audits GEPA optimization_config.json, and enforces a
non-zero exit code when quality drops below threshold.
"""
from pathlib import Path
import json
import sys
import yaml
PROJECT_ROOT = Path(__file__).resolve().parents[1]
ALLOWED_FLASH_MODELS = {"gemini-3.8-flash", "gemini-3.7-flash", "gemini-3.6-flash"}
MIN_REQUIRED_SCORE = 0.85
def validate_evaluation_dataset(dataset_path: Path) -> list[str]:
"""Returns a list of schema violation messages (empty list == valid)."""
errors: list[str] = []
data = json.loads(dataset_path.read_text(encoding="utf-8"))
cases = data.get("eval_cases")
if not isinstance(cases, list) or not cases:
return [f"{dataset_path.name}: 'eval_cases' must be a non-empty list."]
shapes_seen: set[str] = set()
for idx, case in enumerate(cases):
cid = case.get("eval_case_id", f"case_{idx}")
has_prompt = "prompt" in case and case["prompt"] is not None
has_agent_data = "agent_data" in case and case["agent_data"] is not None
# TODO 1a: Reject cases that have BOTH `prompt` and `agent_data` (or neither),
# and track `shapes_seen` ("single" vs "multi") so mixing shapes in one file fails.
# TODO 1b: If `reference` is present, verify it wraps Content inside `{"response": ...}`
# with `role == "model"` (never `"assistant"`) and non-empty `parts`.
# TODO 1c: If `rubric_groups` is present, verify `sla_rubrics.rubrics` has non-empty
# `content.property.description` strings and no `"TODO"` placeholders left behind.
# TODO 1d: If `has_agent_data`, verify `turns` has sequential 0-based `turn_index`
# (0, 1, 2, ...) and that no event uses `role == "assistant"`.
pass
return errors
def load_custom_metric_fn(eval_config_path: Path, metric_name: str):
"""Loads `def evaluate(instance)` from an inline `custom_function` in eval_config.yaml."""
cfg = yaml.safe_load(eval_config_path.read_text(encoding="utf-8"))
# TODO 2: Locate `metric_name` inside `cfg["custom_metrics"]`, `exec` its
# `custom_function` source into a fresh dict namespace, and return `ns["evaluate"]`.
raise NotImplementedError("TODO 2: Load custom_function callable from eval_config.yaml")
def main() -> int:
triage_path = PROJECT_ROOT / "tests/eval/datasets/support-triage-dataset.json"
holdout_path = PROJECT_ROOT / "tests/eval/datasets/support-holdout-dataset.json"
eval_cfg_path = PROJECT_ROOT / "tests/eval/eval_config.yaml"
opt_cfg_path = PROJECT_ROOT / "tests/eval/optimization_config.json"
all_errors: list[str] = []
for ds in (triage_path, holdout_path):
all_errors.extend(validate_evaluation_dataset(ds))
# TODO 3:
# 1) Audit `optimization_config.json` (train_dataset != validation_dataset,
# optimizer_model in ALLOWED_FLASH_MODELS).
# 2) Load `sla_and_ticket_check` via `load_custom_metric_fn` and score every case
# in `triage_path` and `holdout_path` (using populated traces if available, or
# the case's `reference["response"]` verified against `app/agent.py` tools).
# 3) Save `artifacts/grade_results/results_local_gate.json` and return exit code 1
# if `all_errors` is non-empty or mean_score < MIN_REQUIRED_SCORE (else 0).
raise NotImplementedError("TODO 3: Complete flywheel validation and score gate")
if __name__ == "__main__":
sys.exit(main()) - TODO 1 (
-
Run Your Flywheel Validator & Gate:
uv run python scripts/validate_eval_flywheel.pyConfirm that all schema invariants pass,
sla_and_ticket_checkscores1.00,artifacts/grade_results/results_local_gate.jsonis written to disk, and test breaking one SLA string to confirm your gate exits with status1!
Self-Reflection Questionsβ
- Why do
agents-cli eval runandagents-cli eval gradealways exit with code0even when metric scores drop to0.0, and how does that shape your CI/CD pipeline design for Module 30.3? - Why does passing a synthesized multi-turn conversation trace (
agent_data.turnswith 2+ turns) tofinal_response_qualityorhallucinationfail with HTTP400, and which three built-in metrics are designed for multi-turn traces instead? - Why must you fix broken tool implementations, parameter docstrings, and
before_agent_callbackstate initialization before runningagents-cli eval optimize(GEPA), and why is a separatevalidation_dataset+ untouched holdout set essential?
π Reference Solution Vaultβ
Official Solution Vault β Module 30.2
Locked Challenge β Active Pedagogical Socratic Gate