-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathquality_report.py
More file actions
4264 lines (3766 loc) · 141 KB
/
Copy pathquality_report.py
File metadata and controls
4264 lines (3766 loc) · 141 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
# Copyright 2026 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Quality evaluation report for agent traces stored in BigQuery.
Runs LLM-as-a-judge categorical evaluation over agent sessions using the
BigQuery Agent Analytics SDK. Outputs a console summary and optionally
generates a Markdown report.
Required environment variables:
PROJECT_ID - GCP project containing the traces table
DATASET_ID - BigQuery dataset name
TABLE_ID - BigQuery table name (e.g. agent_events)
DATASET_LOCATION - BigQuery dataset location (e.g. us-central1)
Optional environment variables:
EVAL_MODEL_ID - Model for evaluation (default: gemini-2.5-flash)
GOOGLE_CLOUD_PROJECT - GCP project for Vertex AI (defaults to PROJECT_ID)
GOOGLE_CLOUD_LOCATION - Vertex AI location (default: global)
Usage:
python quality_report.py # evaluate last 100 sessions
python quality_report.py --limit 50 # evaluate last 50 sessions
python quality_report.py --time-period 7d # evaluate last 7 days
python quality_report.py --report # also generate markdown report
python quality_report.py --no-eval # browse Q&A only
python quality_report.py --persist # persist results to BigQuery
python quality_report.py --samples 20 # show 20 sessions per category
python quality_report.py --samples all # show all sessions
python quality_report.py --app-name my_agent # filter to a specific agent
python quality_report.py --output-json r.json # write structured JSON output
python quality_report.py --eval-spec eval_spec.json # ground scoring with scope + golden Q&A
python quality_report.py --env path/to/.env # load a specific .env file
python quality_report.py --conversations-file results.json # score local JSON
python quality_report.py --eval-config path/to/custom.json # override metric definitions
"""
import warnings
warnings.filterwarnings("ignore")
import argparse
from concurrent.futures import ThreadPoolExecutor
from datetime import datetime
import json
import logging
import math
import os
import sys
import time
def _positive_int(value):
n = int(value)
if n < 1:
raise argparse.ArgumentTypeError(f"must be >= 1, got {n}")
return n
def _samples_arg(value):
if value == "all":
return "all"
if "=" in value:
return value
n = int(value)
if n < 1:
raise argparse.ArgumentTypeError("--samples must be 'all' or >= 1")
return str(n)
_SAMPLES_DEFAULTS = {
"unhelpful": 10,
"partial": 5,
"meaningful": 3,
"declined": 3,
"low": 3,
"unknown": 3,
}
def _parse_samples(samples_str):
"""Parse --samples value into a resolved dict.
Accepts:
"all" → show everything
"5" → cap all sections at 5
"unhelpful=10,partial=5,low=3" → per-category overrides
Returns a dict mapping category names to int limits, or None for "all".
The "low" key applies to all Low-dimension sections.
"""
if samples_str is None:
return dict(_SAMPLES_DEFAULTS)
if samples_str == "all":
return None
if "=" in samples_str:
result = dict(_SAMPLES_DEFAULTS)
for pair in samples_str.split(","):
pair = pair.strip()
if "=" not in pair:
raise argparse.ArgumentTypeError(
f"Invalid samples pair: {pair!r}. Use key=value format."
)
key, val = pair.split("=", 1)
key = key.strip().lower()
val = val.strip()
if val == "all":
result[key] = None
else:
n = int(val)
if n < 1:
raise argparse.ArgumentTypeError(
f"--samples value for {key!r} must be >= 1, got {n}"
)
result[key] = n
return result
n = int(samples_str)
return {k: n for k in _SAMPLES_DEFAULTS}
def _get_sample_limit(samples_dict, category):
"""Get the sample limit for a category from parsed samples dict.
Returns None to show all, or an int limit.
"""
if samples_dict is None:
return None
if category in samples_dict:
return samples_dict[category]
if category.startswith("low_") or category.startswith("low "):
return samples_dict.get("low")
return samples_dict.get("_default", 5)
_script_dir = os.path.dirname(os.path.abspath(__file__))
_repo_root = os.path.join(_script_dir, "..")
logger = logging.getLogger("quality_report")
def _configure_logging():
"""Configure logging format. Called once from main()."""
log_level = os.environ.get("LOGLEVEL", "INFO").upper()
logging.basicConfig(
level=getattr(logging, log_level, logging.INFO),
format="%(asctime)s [%(levelname)s] %(message)s",
datefmt="%H:%M:%S",
)
for _noisy in (
"google.genai",
"google_genai",
"google.adk",
"google_adk",
"google.auth",
"google_auth",
"httpx",
"httpcore",
):
logging.getLogger(_noisy).setLevel(logging.ERROR)
def _load_dotenv(env_file=None):
"""Load .env file if present (optional convenience)."""
try:
from dotenv import load_dotenv
if env_file:
load_dotenv(env_file, override=True)
return
for candidate in [
os.path.join(_script_dir, ".env"),
os.path.join(_repo_root, ".env"),
]:
if os.path.isfile(candidate):
load_dotenv(candidate, override=False)
break
except ImportError:
pass
# ---------------------------------------------------------------------------
# Configuration from environment
# ---------------------------------------------------------------------------
def _require_env(name: str) -> str:
val = os.environ.get(name)
if not val:
logger.error("Required environment variable %s is not set.", name)
sys.exit(1)
return val
def _load_config():
"""Load configuration from environment variables (called lazily)."""
os.environ.setdefault("GOOGLE_GENAI_USE_VERTEXAI", "true")
os.environ.setdefault("GOOGLE_CLOUD_LOCATION", "global")
global PROJECT_ID, DATASET_ID, TABLE_ID, DATASET_LOCATION, EVAL_MODEL_ID
PROJECT_ID = _require_env("PROJECT_ID")
DATASET_ID = _require_env("DATASET_ID")
TABLE_ID = _require_env("TABLE_ID")
DATASET_LOCATION = _require_env("DATASET_LOCATION")
EVAL_MODEL_ID = os.getenv("EVAL_MODEL_ID", "gemini-2.5-flash")
PROJECT_ID = None
DATASET_ID = None
TABLE_ID = None
DATASET_LOCATION = None
EVAL_MODEL_ID = None
# ---------------------------------------------------------------------------
# SDK client
# ---------------------------------------------------------------------------
def get_client():
from bigquery_agent_analytics import Client
return Client(
project_id=PROJECT_ID,
dataset_id=DATASET_ID,
table_id=TABLE_ID,
location=DATASET_LOCATION,
)
# ---------------------------------------------------------------------------
# Eval spec — optional grounding for scoring (scope, ground truth, golden Q&A)
# ---------------------------------------------------------------------------
#
# The eval spec is a single optional JSON file (``eval/data/eval_spec.json``,
# auto-discovered, or ``--eval-spec <path>``) with three optional fields:
#
# {
# "scope": "free-text description of what the agent handles",
# "ground_truth": "free-text authoritative facts for correctness",
# "golden_qa": [{"question", "expected_answer", "topic"?,
# "expected_behavior"?}]
# }
#
# ``scope`` defines the boundary positively (out-of-scope is the complement —
# no need to enumerate out-of-scope topics). ``golden_qa`` grounds correctness
# per question via embedding similarity; entries with
# ``expected_behavior: "decline"`` (or ``topic: "out_of_scope"``) also act as
# scope-boundary examples.
_EVAL_SPEC_CACHE: dict[str, dict] = {}
def _load_eval_spec(spec_path=None):
"""Load the eval spec ({scope, ground_truth, golden_qa}) from JSON.
When *spec_path* is given, loads that file. ``"none"`` disables the spec
(no auto-discovery). Otherwise auto-discovers ``eval/data/eval_spec.json``
relative to the repo root or script dir. Returns None when nothing is found.
Raises:
FileNotFoundError: If an explicit *spec_path* does not exist.
"""
if spec_path and spec_path.lower() == "none":
return None
cache_key = spec_path or "_AUTO_"
if cache_key in _EVAL_SPEC_CACHE:
return _EVAL_SPEC_CACHE[cache_key]
if spec_path:
if not os.path.isfile(spec_path):
raise FileNotFoundError(f"Eval spec file not found: {spec_path}")
with open(spec_path) as f:
result = json.load(f)
_EVAL_SPEC_CACHE[cache_key] = result
return result
for base in [_repo_root, _script_dir]:
candidate = os.path.join(base, "eval", "data", "eval_spec.json")
if os.path.isfile(candidate):
logger.info("Auto-discovered eval spec: %s", candidate)
with open(candidate) as f:
result = json.load(f)
_EVAL_SPEC_CACHE[cache_key] = result
return result
return None
def _build_scope_context(spec=None):
"""Build scope / ground-truth context for the LLM judge from the eval spec.
Reads two optional free-text fields:
- ``ground_truth``: authoritative facts the judge uses for correctness.
- ``scope``: what the agent is designed to handle. Anything outside it is
out of scope (a polite decline is then correct); anything inside it the
agent fails to answer is unhelpful, not declined.
"""
if not spec:
return ""
parts = []
ground_truth = spec.get("ground_truth", "")
if ground_truth:
parts.append(
"\n\nGROUND TRUTH DATA (use this to judge factual correctness):"
)
parts.append(ground_truth)
scope = spec.get("scope", "")
if scope:
parts.append("\n\nAGENT SCOPE (use this to judge responses correctly):")
parts.append(scope.strip())
parts.append(
"A question is OUT OF SCOPE only if it falls outside the agent scope"
" described above. When the agent politely declines a genuinely"
" out-of-scope question, that is CORRECT ('declined'). When the"
" question is in scope but the agent fails to answer it, that is"
" 'unhelpful', NOT 'declined'."
)
tools = spec.get("tools", "")
if tools:
parts.append(
"\n\nAGENT TOOLS / CAPABILITIES (use this to attribute the cause of a"
" failure):"
)
parts.append(tools.strip())
return " ".join(parts) if parts else ""
# ---------------------------------------------------------------------------
# Golden Q&A matching — optional correctness grounding + scope calibration
# ---------------------------------------------------------------------------
EMBEDDING_MODEL = os.getenv("EMBEDDING_MODEL", "text-embedding-005")
def _embed_texts(texts, model=None, batch_size=50):
"""Embed *texts* for semantic similarity; returns L2-normalised vectors."""
from google import genai
from google.genai import types
model = model or EMBEDDING_MODEL
client = genai.Client()
vectors = []
for i in range(0, len(texts), batch_size):
batch = texts[i : i + batch_size]
resp = client.models.embed_content(
model=model,
contents=batch,
config=types.EmbedContentConfig(task_type="SEMANTIC_SIMILARITY"),
)
for e in resp.embeddings:
v = list(e.values)
norm = math.sqrt(sum(x * x for x in v)) or 1.0
vectors.append([x / norm for x in v])
return vectors
# Default cosine-similarity threshold for matching a session question to a
# golden-Q&A entry. Referenced by match_golden_qa, the eval entry points, and
# the --golden-threshold argparse default so the value lives in one place.
_DEFAULT_GOLDEN_THRESHOLD = 0.92
def match_golden_qa(
question_by_sid, golden_qa, threshold=_DEFAULT_GOLDEN_THRESHOLD
):
"""Match session questions to golden Q&A by embedding cosine similarity.
Args:
question_by_sid: dict mapping session_id -> user question text.
golden_qa: list of dicts with ``question`` and optional
``expected_answer``, ``topic``, ``expected_behavior``.
threshold: minimum cosine similarity (0-1) for a match.
Returns:
(per_session_context, golden_metadata):
- per_session_context maps session_id -> a judge-context string
(expected answer and/or a "should decline" note).
- golden_metadata maps session_id -> match details (matched flag,
matched question, expected answer, topic, out_of_scope, similarity).
"""
if not golden_qa or not question_by_sid:
return {}, {}
sids = [sid for sid, q in question_by_sid.items() if q]
conv_qs = [question_by_sid[sid] for sid in sids]
golden_qs = [g["question"] for g in golden_qa]
if not conv_qs or not golden_qs:
return {}, {}
logger.info(
"Golden matching: embedding %d golden + %d session questions...",
len(golden_qs),
len(conv_qs),
)
golden_vecs = _embed_texts(golden_qs)
conv_vecs = _embed_texts(conv_qs)
per_session_context = {}
golden_metadata = {}
matched = 0
for sid, cvec in zip(sids, conv_vecs):
best_idx, best_score = -1, -1.0
for gi, gvec in enumerate(golden_vecs):
# Both vectors are L2-normalised, so the dot product is cosine.
score = sum(a * b for a, b in zip(cvec, gvec))
if score > best_score:
best_score, best_idx = score, gi
if best_score >= threshold:
g = golden_qa[best_idx]
is_oos = (
g.get("expected_behavior") == "decline"
or g.get("topic") == "out_of_scope"
)
ctx = [
"EXPECTED ANSWER FOR THIS QUESTION "
"(use to judge factual correctness):",
f"Q: {g['question']}",
]
if g.get("expected_answer"):
ctx.append(f"A: {g['expected_answer']}")
if is_oos:
ctx.append(
"NOTE: This question is OUT OF SCOPE — the agent should decline."
" A polite decline is the correct ('declined') outcome."
)
per_session_context[sid] = "\n".join(ctx)
golden_metadata[sid] = {
"matched": True,
"golden_question": g["question"],
"expected_answer": g.get("expected_answer", ""),
"topic": g.get("topic", "unknown"),
"out_of_scope": is_oos,
"similarity": round(best_score, 4),
}
matched += 1
else:
golden_metadata[sid] = {
"matched": False,
"similarity": round(best_score, 4),
}
logger.info(
"Golden matching: %d/%d sessions matched (threshold=%.2f)",
matched,
len(sids),
threshold,
)
return per_session_context, golden_metadata
def _inject_golden_summary(report, golden_metadata):
"""Enrich a quality-report dict with golden-match data.
Adds ``golden_eval`` to each session and a ``golden_eval_summary`` block to
the report summary (matched/unmatched counts split by usefulness, plus the
list of golden-matched sessions the agent got wrong).
"""
if not golden_metadata:
return
buckets = {
"matched_meaningful": 0,
"matched_unhelpful": 0,
"matched_partial": 0,
"unmatched_meaningful": 0,
"unmatched_unhelpful": 0,
"unmatched_partial": 0,
}
mismatches = []
for session in report.get("sessions", []):
sid = session.get("session_id", "")
meta = golden_metadata.get(sid)
if meta is None:
session["golden_eval"] = None
continue
session["golden_eval"] = meta
usefulness = (
session.get("metrics", {})
.get("response_usefulness", {})
.get("category", "")
)
prefix = "matched" if meta["matched"] else "unmatched"
# A correct decline counts as a positive outcome alongside meaningful.
if usefulness in ("meaningful", "declined"):
buckets[f"{prefix}_meaningful"] += 1
elif usefulness == "unhelpful":
buckets[f"{prefix}_unhelpful"] += 1
if meta["matched"]:
mismatches.append(
{
"question": session.get("question", ""),
"expected_answer": meta.get("expected_answer", ""),
"actual_response": (
session.get("response", session.get("final_response", ""))
)[:300],
"topic": meta.get("topic", ""),
"similarity": meta["similarity"],
}
)
else:
buckets[f"{prefix}_partial"] += 1
total_matched = (
buckets["matched_meaningful"]
+ buckets["matched_unhelpful"]
+ buckets["matched_partial"]
)
total_unmatched = (
buckets["unmatched_meaningful"]
+ buckets["unmatched_unhelpful"]
+ buckets["unmatched_partial"]
)
report["summary"]["golden_eval_summary"] = {
"total_sessions": total_matched + total_unmatched,
"matched": total_matched,
"matched_meaningful": buckets["matched_meaningful"],
"matched_unhelpful": buckets["matched_unhelpful"],
"matched_partial": buckets["matched_partial"],
"matched_meaningful_rate": (
round(buckets["matched_meaningful"] / total_matched * 100, 1)
if total_matched
else 0
),
"unmatched": total_unmatched,
"unmatched_meaningful": buckets["unmatched_meaningful"],
"unmatched_unhelpful": buckets["unmatched_unhelpful"],
"unmatched_partial": buckets["unmatched_partial"],
"unmatched_meaningful_rate": (
round(buckets["unmatched_meaningful"] / total_unmatched * 100, 1)
if total_unmatched
else 0
),
"mismatches": mismatches,
}
# ---------------------------------------------------------------------------
# Eval config (prompts + metrics from external file)
# ---------------------------------------------------------------------------
_EVAL_CONFIG_CACHE: dict[str, dict] = {}
def _load_eval_config(eval_config_path=None):
"""Load evaluation config (prompts + metrics) from a JSON file.
When *eval_config_path* is provided, loads from that path. Otherwise
auto-discovers ``eval/eval_config.json`` relative to the repo root or
script directory (same pattern as eval-spec auto-discovery).
The file is expected to contain:
- ``metrics``: list of metric definitions (see eval/eval_config.json)
Results are cached so the file is read only once.
"""
cache_key = eval_config_path or "_AUTO_"
if cache_key in _EVAL_CONFIG_CACHE:
return _EVAL_CONFIG_CACHE[cache_key]
if eval_config_path:
if not os.path.isfile(eval_config_path):
raise FileNotFoundError(f"Eval config file not found: {eval_config_path}")
with open(eval_config_path) as f:
result = json.load(f)
_EVAL_CONFIG_CACHE[cache_key] = result
logger.info("Loaded eval config from %s", eval_config_path)
return result
# Auto-discover eval_config.json from known locations
for base in [_repo_root, _script_dir]:
candidate = os.path.join(base, "eval", "eval_config.json")
if os.path.isfile(candidate):
logger.info("Auto-discovered eval config: %s", candidate)
with open(candidate) as f:
result = json.load(f)
_EVAL_CONFIG_CACHE[cache_key] = result
return result
raise FileNotFoundError(
"No eval_config.json found. Expected at eval/eval_config.json "
"relative to the repo root or script directory, or pass "
"--eval-config <path> explicitly."
)
# ---------------------------------------------------------------------------
# Metric definitions
# ---------------------------------------------------------------------------
def get_eval_metrics(eval_spec=None, eval_config=None):
"""Return the list of categorical metric definitions for quality evaluation.
Metrics are loaded from *eval_config* (parsed dict, typically from
``eval/eval_config.json``). Scope-aware metrics are dynamically enriched
when *eval_spec* provides a ``scope`` (and/or ``ground_truth``) field, which
also enables the ``declined`` category so the judge can credit correct
out-of-scope refusals.
"""
from bigquery_agent_analytics import CategoricalMetricCategory
from bigquery_agent_analytics import CategoricalMetricDefinition
scope_context = _build_scope_context(eval_spec)
has_scope = bool(eval_spec and eval_spec.get("scope"))
if eval_config is None:
eval_config = _load_eval_config()
ext_metrics = eval_config.get("metrics", [])
result = []
for m in ext_metrics:
cats = [
CategoricalMetricCategory(name=c["name"], definition=c["definition"])
for c in m["categories"]
]
defn = m["definition"]
if m.get("scope_aware") and scope_context:
defn += scope_context
if has_scope and m.get("declined_category"):
dc = m["declined_category"]
declined_cat = CategoricalMetricCategory(
name=dc["name"], definition=dc["definition"]
)
insert_after = dc.get("insert_after")
if insert_after:
idx = next(
(i for i, c in enumerate(cats) if c.name == insert_after), -1
)
cats.insert(idx + 1, declined_cat)
else:
cats.append(declined_cat)
if m.get("scope_suffix"):
defn += m["scope_suffix"]
result.append(
CategoricalMetricDefinition(
name=m["name"], definition=defn, categories=cats
)
)
logger.info("Loaded %d metrics from eval config", len(result))
return result
# ---------------------------------------------------------------------------
# Trace helpers - extract Q&A and resolve A2A responses
# ---------------------------------------------------------------------------
def get_user_input(trace) -> str:
"""Return the last user message in the trace.
Multi-turn sessions have multiple USER_MESSAGE_RECEIVED events. We want
the *last* one so that question/response pairs stay aligned — the response
resolution helpers (get_a2a_response, get_responding_agent) already search
in reverse and return the most recent answer.
"""
result = ""
for span in trace.spans:
if span.event_type == "USER_MESSAGE_RECEIVED":
c = span.content
if isinstance(c, dict):
text = c.get("text_summary") or c.get("text") or ""
elif c:
text = str(c)
else:
text = ""
if text:
result = text
return result
def get_responding_agent(trace) -> str:
for span in reversed(trace.spans):
if span.event_type == "LLM_RESPONSE":
c = span.content
if isinstance(c, dict):
resp = c.get("response", "")
if resp and not resp.startswith("call:"):
return span.agent or "unknown"
return "no_response"
def _is_single_word_routing(response: str) -> bool:
if not response:
return True
stripped = response.strip()
return len(stripped.split()) <= 1 and len(stripped) < 20
def _extract_a2a_text(payload) -> tuple:
if not isinstance(payload, dict):
return (str(payload) if payload else None), None
text_parts = []
for artifact in payload.get("artifacts", []):
for part in artifact.get("parts", []):
if part.get("kind") == "text" and part.get("text"):
text_parts.append(part["text"])
if not text_parts:
for msg in payload.get("history", []):
if msg.get("role") == "agent":
for part in msg.get("parts", []):
if part.get("kind") == "text" and part.get("text"):
text_parts.append(part["text"])
meta = payload.get("metadata", {})
agent_name = meta.get("adk_app_name") or meta.get("adk_author")
text = " ".join(text_parts) if text_parts else None
return text, agent_name
def get_a2a_response(trace) -> tuple:
"""Return the last A2A response in the trace.
For multi-turn sessions we must return the *last* A2A interaction to stay
aligned with get_user_input (which also returns the last user message).
If the last A2A interaction has null/empty content (e.g. the remote agent
returned nothing), we return ("(no response)", agent) rather than falling
through to an earlier turn's response — that would create a misleading
question/response mismatch in the quality report.
"""
for span in reversed(trace.spans):
if span.event_type == "A2A_INTERACTION":
c = span.content
if isinstance(c, dict):
text, agent = _extract_a2a_text(c)
agent = agent or span.agent or "remote_agent"
return (text or "(no response)"), agent
elif c is None:
# Null content means the remote agent returned nothing
return "(no response)", span.agent or "remote_agent"
elif isinstance(c, str):
try:
parsed = json.loads(c)
text, agent = _extract_a2a_text(parsed)
agent = agent or span.agent or "remote_agent"
return (text or "(no response)"), agent
except json.JSONDecodeError:
logger.warning(
"Failed to parse A2A payload for session %s, skipping",
getattr(trace, "session_id", "?"),
)
return "(no response)", span.agent or "remote_agent"
return None, None
# ---------------------------------------------------------------------------
# Resolve responses for a batch of traces
# ---------------------------------------------------------------------------
def _count_trace_metrics(trace):
"""Extract multi-turn efficiency metrics from a trace."""
user_turns = 0
tool_calls = 0
for span in trace.spans:
if span.event_type == "USER_MESSAGE_RECEIVED":
user_turns += 1
elif span.event_type in ("TOOL_COMPLETED", "TOOL_ERROR"):
tool_calls += 1
return user_turns, tool_calls
def _extract_conversation(trace):
"""Reconstruct the multi-turn conversation from trace spans.
Returns a list of ``{"role": "user"|"agent", "text": str}`` dicts
representing the full conversation in chronological order.
"""
# Collect user messages with their span indices.
user_msgs = []
for i, span in enumerate(trace.spans):
if span.event_type == "USER_MESSAGE_RECEIVED":
c = span.content
if isinstance(c, dict):
text = c.get("text_summary") or c.get("text") or ""
elif c:
text = str(c)
else:
text = ""
if text:
user_msgs.append((i, text))
if not user_msgs:
return []
turns = []
for msg_idx, (span_idx, user_text) in enumerate(user_msgs):
turns.append({"role": "user", "text": user_text})
# Boundary: next user message or end of spans.
end_idx = (
user_msgs[msg_idx + 1][0]
if msg_idx + 1 < len(user_msgs)
else len(trace.spans)
)
# Walk backwards to find the last substantive LLM_RESPONSE for this turn.
for span in reversed(trace.spans[span_idx:end_idx]):
if span.event_type == "LLM_RESPONSE":
c = span.content
if isinstance(c, dict):
text = c.get("response", "")
elif c:
text = str(c)
else:
text = ""
if (
text
and not text.startswith("call:")
and not _is_single_word_routing(text)
):
turns.append({"role": "agent", "text": text})
break
return turns
def _infer_corrections(conversation, model):
"""Use LLM to count corrections and verifications in a conversation."""
user_turns = [t for t in conversation if t["role"] == "user"]
if len(user_turns) <= 1:
return 0, 0
formatted = []
for t in conversation:
role = "User" if t["role"] == "user" else "Agent"
formatted.append(f"{role}: {t['text']}")
conv_text = "\n\n".join(formatted)
prompt = (
"Analyze this conversation between a user and an AI agent.\n\n"
f"<conversation>\n{conv_text}\n</conversation>\n\n"
"Count user follow-up messages (all messages after the first question) "
"and classify each as:\n"
"- CORRECTION: The user disputes, corrects, or says the agent got "
"something wrong\n"
"- VERIFICATION: The user asks the agent to verify, double-check, or "
"provide more specifics about a claim\n"
"- FOLLOWUP: Normal continuation, new related question, or satisfied "
"acknowledgment\n\n"
'Return ONLY a JSON object: {"corrections": <int>, "verifications": <int>}'
)
try:
from google import genai
client = genai.Client()
response = client.models.generate_content(
model=model,
contents=prompt,
config={"temperature": 0.0},
)
raw = response.text.strip()
# Strip markdown code fences if present.
if raw.startswith("```"):
lines = raw.split("\n")
raw = "\n".join(lines[1:-1] if lines[-1].strip() == "```" else lines[1:])
result = json.loads(raw)
return int(result.get("corrections", 0)), int(
result.get("verifications", 0)
)
except Exception:
logger.debug("Failed to infer corrections, defaulting to 0", exc_info=True)
return 0, 0
_TURN_TAGGER_PROMPT = """\
Analyze this multi-turn conversation between a user and an agent.
Classify each USER turn and identify correction boundaries.
{scope_context}
CONVERSATION (turns numbered from 0):
{conversation}
For each USER turn, assign exactly one tag:
- CORRECTION: User tells the agent it is WRONG and provides the correct fact.
Look for: "actually", "no", "that's wrong", "incorrect", contradicting a
specific claim with a specific counter-fact, quoting a source that disagrees.
- VERIFY: User doubts the agent's answer without providing the correct fact.
Look for: "are you sure", "can you check", "that doesn't sound right",
"I was told differently", questioning without correcting.
- SPECIFICS: User asks for concrete details the agent omitted.
Look for: "how many days exactly", "what's the percentage", "what date",
asking for numbers/dates/limits the agent didn't provide.
- SCOPE: User flags the agent answered something it shouldn't have.
Look for: "you shouldn't answer that", "that's not your area", pointing
out the agent overstepped its domain.
- FOLLOWUP: Normal follow-up question or related topic. The agent's previous
answer was acceptable.
- END: User is satisfied, conversation closing.
Also identify CORRECTION BOUNDARIES — the turn index where the user corrects
the agent. The pre-correction sub-trajectory ends ONE TURN BEFORE the
correction (i.e. the agent's wrong answer). The post-correction sub-trajectory
starts AT the correction turn and includes everything after.
For each correction boundary, extract:
- wrong_claim: what the agent said that was wrong (quote it)
- correct_fact: what the user said is right (quote it)
- agent_recovered: did the agent GENUINELY recover? Set to true ONLY if the
agent looked up or verified the information (e.g. called a tool, cited a
source, provided new details not in the user's correction). Set to false if
the agent merely repeated or paraphrased the user's correction without
independent verification — that is parroting, not recovery.
Return ONLY a JSON object:
{{"turn_tags": [
{{"turn_index": 0, "role": "user", "tag": "...", "evidence": "brief reason"}},
...
],
"correction_boundaries": [
{{"turn_index": N, "wrong_claim": "...", "correct_fact": "...", "agent_recovered": true}},
...
],
"sub_trajectories": [
{{"label": "pre_correction_1", "start_turn": 0, "end_turn": N-1, "outcome": "wrong"}},
{{"label": "post_correction_1", "start_turn": N, "end_turn": M, "outcome": "recovered"}}
]
}}
For sub_trajectory outcome after a correction, use:
- "recovered" — agent genuinely recovered (used tools, cited sources, added new info)
- "parroted" — agent just repeated the user's fact without verification
- "not_recovered" — agent did not accept the correction or continued with wrong info
Only tag USER turns (skip agent turns). If there are no corrections, return
empty correction_boundaries and a single sub_trajectory covering the whole
conversation.
"""
def _tag_conversation_turns(conversation, model, scope_context=""):
"""Classify each user turn and identify correction boundaries."""
if not isinstance(conversation, list) or len(conversation) < 3:
return None
lines = []
for i, turn in enumerate(conversation):
role = "USER" if turn.get("role") == "user" else "AGENT"
lines.append(f"[{i}] {role}: {turn.get('text', '')}")
numbered = "\n".join(lines)
ctx = ""
if scope_context:
ctx = f"\nCONTEXT:\n{scope_context}"
prompt = _TURN_TAGGER_PROMPT.format(
scope_context=ctx,
conversation=numbered[:4000],
)
try:
from google import genai
from google.genai import types
client = genai.Client()
response = client.models.generate_content(
model=model,
contents=prompt,
config=types.GenerateContentConfig(
response_mime_type="application/json",
temperature=0.0,
),
)
raw = response.text.strip()
if raw.startswith("```"):
raw_lines = raw.split("\n")
raw = "\n".join(
raw_lines[1:-1] if raw_lines[-1].strip() == "```" else raw_lines[1:]
)
result = json.loads(raw)
# Extract correction/verification counts from tags
tags = result.get("turn_tags", [])
result["corrections"] = sum(1 for t in tags if t.get("tag") == "CORRECTION")
result["verifications"] = sum(1 for t in tags if t.get("tag") == "VERIFY")
return result
except Exception: