-
Notifications
You must be signed in to change notification settings - Fork 448
Expand file tree
/
Copy pathtest_evals.py
More file actions
9071 lines (8304 loc) · 351 KB
/
test_evals.py
File metadata and controls
9071 lines (8304 loc) · 351 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
# Copyright 2025 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.
#
# pylint: disable=protected-access,bad-continuation,
import base64
import importlib
import json
import os
import re
import statistics
import sys
import tempfile
import unittest
from unittest import mock
import google.auth.credentials
from google.cloud import aiplatform
import vertexai
from google.cloud.aiplatform import initializer as aiplatform_initializer
from vertexai import _genai
from vertexai._genai import _evals_data_converters
from vertexai._genai import _evals_metric_handlers
from vertexai._genai import _evals_visualization
from vertexai._genai import _evals_metric_loaders
from vertexai._genai import _gcs_utils
from vertexai._genai import _observability_data_converter
from vertexai._genai import _transformers
from vertexai._genai import evals
from vertexai._genai import types as vertexai_genai_types
from vertexai._genai.types import common as common_types
from google.genai import client
from google.genai import errors as genai_errors
from google.genai import types as genai_types
import pandas as pd
import pytest
_TEST_PROJECT = "test-project"
_TEST_LOCATION = "us-central1"
_evals_common = _genai.evals._evals_common
_evals_utils = _genai._evals_utils
pytestmark = pytest.mark.usefixtures("google_auth_mock")
class TestDropEmptyColumns:
"""Unit tests for the _drop_empty_columns function."""
def test_drop_empty_columns(self):
df = pd.DataFrame(
{
"col1": [1, 2, 3],
"col2": [None, None, None],
"col3": [[], [], []],
"col4": [{}, {}, {}],
"col5": [1, None, []],
}
)
result_df = _evals_common._drop_empty_columns(df)
assert "col1" in result_df.columns
assert "col2" not in result_df.columns
assert "col3" not in result_df.columns
assert "col4" not in result_df.columns
assert "col5" in result_df.columns
def test_drop_empty_columns_all_empty(self):
df = pd.DataFrame(
{
"col1": [None, None, None],
"col2": [[], [], []],
}
)
result_df = _evals_common._drop_empty_columns(df)
assert result_df.empty
def test_drop_empty_columns_none_empty(self):
df = pd.DataFrame(
{
"col1": [1, 2, 3],
"col2": ["a", "b", "c"],
}
)
result_df = _evals_common._drop_empty_columns(df)
assert list(result_df.columns) == ["col1", "col2"]
def _create_content_dump(text: str) -> dict[str, list[genai_types.Content]]:
return {
"contents": [
genai_types.Content(parts=[genai_types.Part(text=text)]).model_dump(
mode="json", exclude_none=True
)
]
}
@pytest.fixture
def mock_api_client_fixture():
mock_client = mock.Mock(spec=client.Client)
mock_client.project = _TEST_PROJECT
mock_client.location = _TEST_LOCATION
mock_client._credentials = mock.create_autospec(
google.auth.credentials.Credentials, instance=True
)
mock_client._credentials.universe_domain = "googleapis.com"
mock_client._evals_client = mock.Mock(spec=evals.Evals)
mock_client._http_options = None
return mock_client
@pytest.fixture
def mock_eval_dependencies(mock_api_client_fixture):
with mock.patch("google.cloud.storage.Client") as mock_storage_client, mock.patch(
"google.cloud.bigquery.Client"
) as mock_bq_client, mock.patch(
"vertexai._genai.evals.Evals.evaluate_instances"
) as mock_evaluate_instances, mock.patch(
"vertexai._genai._gcs_utils.GcsUtils.upload_json_to_prefix"
) as mock_upload_to_gcs, mock.patch(
"vertexai._genai._evals_metric_loaders.LazyLoadedPrebuiltMetric._fetch_and_parse"
) as mock_fetch_prebuilt_metric:
def mock_evaluate_instances_side_effect(*args, **kwargs):
metric_config = kwargs.get("metric_config", {})
if "exact_match_input" in metric_config:
return vertexai_genai_types.EvaluateInstancesResponse(
exact_match_results=vertexai_genai_types.ExactMatchResults(
exact_match_metric_values=[
genai_types.ExactMatchMetricValue(score=1.0)
]
)
)
elif "rouge_input" in metric_config:
return vertexai_genai_types.EvaluateInstancesResponse(
rouge_results=vertexai_genai_types.RougeResults(
rouge_metric_values=[genai_types.RougeMetricValue(score=0.8)]
)
)
elif "comet_input" in metric_config:
return vertexai_genai_types.EvaluateInstancesResponse(
comet_result=vertexai_genai_types.CometResult(score=0.75)
)
return vertexai_genai_types.EvaluateInstancesResponse()
mock_evaluate_instances.side_effect = mock_evaluate_instances_side_effect
mock_upload_to_gcs.return_value = (
"gs://mock-bucket/mock_path/evaluation_result_timestamp.json"
)
mock_prebuilt_fluency_metric = vertexai_genai_types.LLMMetric(
name="fluency", prompt_template="Is this fluent? {response}"
)
mock_prebuilt_fluency_metric._is_predefined = True
mock_prebuilt_fluency_metric._config_source = (
"gs://mock-metrics/fluency/v1.yaml"
)
mock_prebuilt_fluency_metric._version = "v1"
mock_fetch_prebuilt_metric.return_value = mock_prebuilt_fluency_metric
yield {
"mock_storage_client": mock_storage_client,
"mock_bq_client": mock_bq_client,
"mock_evaluate_instances": mock_evaluate_instances,
"mock_upload_to_gcs": mock_upload_to_gcs,
"mock_fetch_prebuilt_metric": mock_fetch_prebuilt_metric,
"mock_prebuilt_fluency_metric": mock_prebuilt_fluency_metric,
}
class TestGetApiClientWithLocation:
@mock.patch("vertexai._genai._evals_common.vertexai.Client")
def test_get_api_client_with_location_override(
self, mock_vertexai_client, mock_api_client_fixture
):
mock_api_client_fixture.location = "us-central1"
new_location = "europe-west1"
_evals_common._get_api_client_with_location(
mock_api_client_fixture, new_location
)
mock_vertexai_client.assert_called_once_with(
project=mock_api_client_fixture.project,
location=new_location,
credentials=mock_api_client_fixture._credentials,
http_options=mock_api_client_fixture._http_options,
)
@mock.patch("vertexai._genai._evals_common.vertexai.Client")
def test_get_api_client_with_same_location(
self, mock_vertexai_client, mock_api_client_fixture
):
mock_api_client_fixture.location = "us-central1"
new_location = "us-central1"
_evals_common._get_api_client_with_location(
mock_api_client_fixture, new_location
)
mock_vertexai_client.assert_not_called()
@mock.patch("vertexai._genai._evals_common.vertexai.Client")
def test_get_api_client_with_none_location(
self, mock_vertexai_client, mock_api_client_fixture
):
mock_api_client_fixture.location = "us-central1"
new_location = None
_evals_common._get_api_client_with_location(
mock_api_client_fixture, new_location
)
mock_vertexai_client.assert_not_called()
class TestTransformers:
"""Unit tests for transformers."""
def test_t_inline_results(self):
eval_result = common_types.EvaluationResult(
eval_case_results=[
common_types.EvalCaseResult(
eval_case_index=0,
response_candidate_results=[
common_types.ResponseCandidateResult(
response_index=0,
metric_results={
"tool_use_quality": common_types.EvalCaseMetricResult(
score=0.0,
explanation="Failed tool use",
)
},
)
],
)
],
evaluation_dataset=[
common_types.EvaluationDataset(
eval_cases=[
common_types.EvalCase(
prompt=genai_types.Content(
parts=[genai_types.Part(text="test prompt")]
)
)
]
)
],
metadata=common_types.EvaluationRunMetadata(candidate_names=["gemini-pro"]),
)
payload = _transformers.t_inline_results([eval_result])
assert len(payload) == 1
assert payload[0]["metric"] == "tool_use_quality"
assert payload[0]["request"]["prompt"]["text"] == "test prompt"
assert len(payload[0]["candidate_results"]) == 1
assert payload[0]["candidate_results"][0]["candidate"] == "gemini-pro"
assert payload[0]["candidate_results"][0]["score"] == 0.0
def test_t_inline_results_sanitizes_agent_data(self):
"""Tests that t_inline_results strips SDK-only fields from agent_data."""
eval_result = common_types.EvaluationResult(
eval_case_results=[
common_types.EvalCaseResult(
eval_case_index=0,
response_candidate_results=[
common_types.ResponseCandidateResult(
response_index=0,
metric_results={
"multi_turn_task_success_v1": common_types.EvalCaseMetricResult(
score=0.0,
explanation="Failed",
)
},
)
],
)
],
evaluation_dataset=[
common_types.EvaluationDataset(
eval_cases=[
common_types.EvalCase(
agent_data=vertexai_genai_types.evals.AgentData(
turns=[
vertexai_genai_types.evals.ConversationTurn(
turn_index=0,
turn_id="turn_0",
events=[
vertexai_genai_types.evals.AgentEvent(
author="user",
content=genai_types.Content(
role="user",
parts=[
genai_types.Part(text="Hello")
],
),
),
vertexai_genai_types.evals.AgentEvent(
author="model",
content=genai_types.Content(
role="model",
parts=[
genai_types.Part(
function_call=genai_types.FunctionCall(
name="search",
args={"q": "test"},
)
)
],
),
),
vertexai_genai_types.evals.AgentEvent(
author="model",
content=genai_types.Content(
role="model",
parts=[
genai_types.Part(
function_response=genai_types.FunctionResponse(
name="search",
response={
"result": "ok"
},
)
)
],
),
),
],
)
]
)
)
]
)
],
metadata=common_types.EvaluationRunMetadata(
candidate_names=["travel-agent"]
),
)
payload = _transformers.t_inline_results([eval_result])
assert len(payload) == 1
agent_data = payload[0]["request"]["prompt"]["agent_data"]
assert "turns" in agent_data
events = agent_data["turns"][0]["events"]
assert len(events) == 3
# Check text part is preserved
text_part = events[0]["content"]["parts"][0]
assert "text" in text_part
assert text_part["text"] == "Hello"
# Check function_call is preserved (API-recognized field)
fc_part = events[1]["content"]["parts"][0]
assert "function_call" in fc_part
assert fc_part["function_call"]["name"] == "search"
# SDK-only fields must NOT be present
assert "tool_call" not in fc_part
assert "tool_response" not in fc_part
assert "part_metadata" not in fc_part
# Check function_response is preserved but will_continue is stripped
fr_part = events[2]["content"]["parts"][0]
assert "function_response" in fr_part
assert fr_part["function_response"]["name"] == "search"
assert "will_continue" not in fr_part["function_response"]
def test_sanitize_agent_data_from_dataframe(self):
"""Tests sanitization when agent_data comes from DataFrame (dict form)."""
# Simulate agent_data stored in DataFrame with SDK-only fields
raw_agent_data = {
"turns": [
{
"turn_index": 0,
"turn_id": "turn_0",
"events": [
{
"author": "model",
"content": {
"role": "model",
"parts": [
{
"function_call": {
"name": "find_flights",
"args": {"origin": "NYC"},
},
"tool_call": None,
"tool_response": None,
"part_metadata": None,
}
],
},
},
{
"author": "model",
"content": {
"role": "model",
"parts": [
{
"function_response": {
"name": "find_flights",
"response": {"flights": []},
"will_continue": False,
"scheduling": None,
},
}
],
},
},
],
}
],
}
sanitized = _transformers._sanitize_agent_data(raw_agent_data)
parts_0 = sanitized["turns"][0]["events"][0]["content"]["parts"][0]
assert "function_call" in parts_0
assert "tool_call" not in parts_0
assert "tool_response" not in parts_0
assert "part_metadata" not in parts_0
parts_1 = sanitized["turns"][0]["events"][1]["content"]["parts"][0]
assert "function_response" in parts_1
assert parts_1["function_response"]["name"] == "find_flights"
assert "will_continue" not in parts_1["function_response"]
assert "scheduling" not in parts_1["function_response"]
def test_sanitize_agent_data_skips_error_payload(self):
"""Tests that error payloads from failed agent runs are stripped."""
error_data = {"error": "Multi-turn agent run with user simulation failed"}
sanitized = _transformers._sanitize_agent_data(error_data)
assert "error" not in sanitized
assert sanitized == {}
def test_t_inline_results_strips_none_tool_fields(self):
"""Tests that t_inline_results strips None tool fields like file_search."""
eval_result = common_types.EvaluationResult(
eval_case_results=[
common_types.EvalCaseResult(
eval_case_index=0,
response_candidate_results=[
common_types.ResponseCandidateResult(
response_index=0,
metric_results={
"multi_turn_task_success_v1": common_types.EvalCaseMetricResult(
score=0.0,
explanation="Failed",
)
},
)
],
)
],
evaluation_dataset=[
common_types.EvaluationDataset(
eval_cases=[
common_types.EvalCase(
agent_data=vertexai_genai_types.evals.AgentData(
agents={
"agent_0": vertexai_genai_types.evals.AgentConfig(
agent_id="agent_0",
agent_type="LlmAgent",
instruction="You are a helper.",
tools=[
genai_types.Tool(
function_declarations=[
genai_types.FunctionDeclaration(
name="search",
description="Searches the web.",
)
]
)
],
)
},
turns=[
vertexai_genai_types.evals.ConversationTurn(
turn_index=0,
events=[
vertexai_genai_types.evals.AgentEvent(
author="user",
content=genai_types.Content(
parts=[genai_types.Part(text="Hi")],
),
),
],
)
],
)
)
]
)
],
metadata=common_types.EvaluationRunMetadata(
candidate_names=["candidate-1"]
),
)
payload = _transformers.t_inline_results([eval_result])
assert len(payload) == 1
agent_data = payload[0]["request"]["prompt"]["agent_data"]
agent_config = agent_data["agents"]["agent_0"]
assert "tools" in agent_config
tool = agent_config["tools"][0]
# function_declarations should be preserved
assert "function_declarations" in tool
assert tool["function_declarations"][0]["name"] == "search"
# Gemini-API-only fields must NOT be present (they would be None)
assert "file_search" not in tool
assert "mcp_servers" not in tool
assert "google_search" not in tool
assert "code_execution" not in tool
def test_t_inline_results_skips_error_agent_data_in_df(self):
"""Tests that t_inline_results skips error agent_data from DataFrame."""
error_json = json.dumps({"error": "Agent run failed"})
df = pd.DataFrame(
{
"prompt": ["test"],
"agent_data": [error_json],
}
)
eval_result = common_types.EvaluationResult(
eval_case_results=[
common_types.EvalCaseResult(
eval_case_index=0,
response_candidate_results=[
common_types.ResponseCandidateResult(
response_index=0,
metric_results={
"metric_v1": common_types.EvalCaseMetricResult(
score=0.0,
)
},
)
],
)
],
evaluation_dataset=[common_types.EvaluationDataset(eval_dataset_df=df)],
metadata=common_types.EvaluationRunMetadata(candidate_names=["agent"]),
)
payload = _transformers.t_inline_results([eval_result])
assert len(payload) == 1
# The prompt should have no agent_data (error was skipped)
assert "agent_data" not in payload[0]["request"]["prompt"]
class TestLossAnalysis:
"""Unit tests for loss analysis types and visualization."""
def test_response_structure(self):
response = common_types.GenerateLossClustersResponse(
analysis_time="2026-04-01T10:00:00Z",
results=[
common_types.LossAnalysisResult(
config=common_types.LossAnalysisConfig(
metric="multi_turn_task_success_v1",
candidate="travel-agent",
),
analysis_time="2026-04-01T10:00:00Z",
clusters=[
common_types.LossCluster(
cluster_id="cluster-1",
taxonomy_entry=common_types.LossTaxonomyEntry(
l1_category="Tool Calling",
l2_category="Missing Tool Invocation",
description="The agent failed to invoke a required tool.",
),
item_count=3,
),
common_types.LossCluster(
cluster_id="cluster-2",
taxonomy_entry=common_types.LossTaxonomyEntry(
l1_category="Hallucination",
l2_category="Hallucination of Action",
description="Verbally confirmed action without tool.",
),
item_count=2,
),
],
)
],
)
assert len(response.results) == 1
assert response.analysis_time == "2026-04-01T10:00:00Z"
result = response.results[0]
assert result.config.metric == "multi_turn_task_success_v1"
assert len(result.clusters) == 2
assert result.clusters[0].cluster_id == "cluster-1"
assert result.clusters[0].item_count == 3
assert result.clusters[1].cluster_id == "cluster-2"
def test_get_loss_analysis_html(self):
"""Tests that _get_loss_analysis_html generates valid HTML with data."""
from vertexai._genai import _evals_visualization
import json
data = {
"results": [
{
"config": {
"metric": "test_metric",
"candidate": "test-candidate",
},
"clusters": [
{
"cluster_id": "c1",
"taxonomy_entry": {
"l1_category": "Tool Calling",
"l2_category": "Missing Invocation",
"description": "Agent failed to call the tool.",
},
"item_count": 5,
"examples": [
{
"evaluation_result": {
"request": {
"prompt": {
"agent_data": {
"turns": [
{
"turn_index": 0,
"events": [
{
"author": "user",
"content": {
"parts": [
{
"text": "Find flights to Paris"
}
],
},
}
],
}
],
},
},
},
},
"failed_rubrics": [
{
"rubric_id": "tool_use",
"classification_rationale": "Did not invoke find_flights.",
}
],
}
],
},
],
}
]
}
html = _evals_visualization._get_loss_analysis_html(json.dumps(data))
assert "Loss Pattern Analysis" in html
assert "test_metric" not in html # data is Base64-encoded in the HTML
assert "<!DOCTYPE html>" in html
assert "extractScenarioPreview" in html
assert "example-scenario" in html
assert "DOMPurify" in html # uses DOMPurify for sanitization
assert "example-section-label" in html # labels for scenario/rubrics
assert "Analysis Summary" in html # summary heading
def test_display_loss_clusters_response_no_ipython(self):
"""Tests graceful fallback when not in IPython."""
from vertexai._genai import _evals_visualization
from unittest import mock
response = common_types.GenerateLossClustersResponse(
results=[
common_types.LossAnalysisResult(
config=common_types.LossAnalysisConfig(
metric="test_metric",
candidate="test-candidate",
),
clusters=[
common_types.LossCluster(
cluster_id="c1",
taxonomy_entry=common_types.LossTaxonomyEntry(
l1_category="Cat1",
l2_category="SubCat1",
),
item_count=5,
),
],
)
],
)
with mock.patch.object(
_evals_visualization, "_is_ipython_env", return_value=False
):
# Should not raise, just log a warning
response.show()
def test_display_loss_analysis_result_no_ipython(self):
"""Tests graceful fallback for individual result when not in IPython."""
from vertexai._genai import _evals_visualization
from unittest import mock
result = common_types.LossAnalysisResult(
config=common_types.LossAnalysisConfig(
metric="test_metric",
candidate="test-candidate",
),
clusters=[
common_types.LossCluster(
cluster_id="c1",
taxonomy_entry=common_types.LossTaxonomyEntry(
l1_category="DirectCat",
l2_category="DirectSubCat",
),
item_count=7,
),
],
)
with mock.patch.object(
_evals_visualization, "_is_ipython_env", return_value=False
):
result.show()
def test_enrich_scenario_from_agent_data_in_eval_cases(self):
"""Tests scenario extraction from agent_data in eval_cases."""
from vertexai._genai import _evals_utils
# API response: evaluation_result has NO request (real API behavior)
api_response = common_types.GenerateLossClustersResponse(
results=[
common_types.LossAnalysisResult(
config=common_types.LossAnalysisConfig(
metric="multi_turn_task_success_v1",
candidate="travel-agent",
),
clusters=[
common_types.LossCluster(
cluster_id="c1",
taxonomy_entry=common_types.LossTaxonomyEntry(
l1_category="Tool Calling",
l2_category="Missing Invocation",
),
item_count=1,
examples=[
common_types.LossExample(
evaluation_result={
"candidateResults": [
{
"candidate": "travel-agent",
"metric": "multi_turn_task_success_v1",
}
]
},
failed_rubrics=[
common_types.FailedRubric(
rubric_id="tool_use",
classification_rationale="Did not call tool.",
)
],
)
],
)
],
)
],
)
# Original eval_result with agent_data in eval_cases
eval_result = common_types.EvaluationResult(
eval_case_results=[
common_types.EvalCaseResult(
eval_case_index=0,
response_candidate_results=[
common_types.ResponseCandidateResult(
response_index=0,
metric_results={
"multi_turn_task_success_v1": common_types.EvalCaseMetricResult(
score=0.0,
),
},
)
],
)
],
evaluation_dataset=[
common_types.EvaluationDataset(
eval_cases=[
common_types.EvalCase(
agent_data=vertexai_genai_types.evals.AgentData(
turns=[
vertexai_genai_types.evals.ConversationTurn(
turn_index=0,
events=[
vertexai_genai_types.evals.AgentEvent(
author="user",
content={
"parts": [
{
"text": "Book a flight to Paris."
}
]
},
),
],
)
],
)
)
]
)
],
metadata=common_types.EvaluationRunMetadata(
candidate_names=["travel-agent"]
),
)
_evals_utils._enrich_loss_response_with_rubric_descriptions(
api_response, eval_result
)
example = api_response.results[0].clusters[0].examples[0]
assert "scenario_preview" in example.evaluation_result
assert (
example.evaluation_result["scenario_preview"] == "Book a flight to Paris."
)
def test_enrich_scenario_from_user_scenario_starting_prompt(self):
"""Tests scenario extraction from user_scenario.starting_prompt."""
from vertexai._genai import _evals_utils
api_response = common_types.GenerateLossClustersResponse(
results=[
common_types.LossAnalysisResult(
config=common_types.LossAnalysisConfig(
metric="multi_turn_task_success_v1",
candidate="travel-agent",
),
clusters=[
common_types.LossCluster(
cluster_id="c1",
taxonomy_entry=common_types.LossTaxonomyEntry(
l1_category="Tool Calling",
l2_category="Missing Invocation",
),
item_count=1,
examples=[
common_types.LossExample(
evaluation_result={
"candidateResults": [
{"candidate": "travel-agent"}
]
},
failed_rubrics=[
common_types.FailedRubric(rubric_id="t1")
],
)
],
)
],
)
],
)
# eval_result with user_scenario (from generate_conversation_scenarios)
eval_result = common_types.EvaluationResult(
eval_case_results=[
common_types.EvalCaseResult(
eval_case_index=0,
response_candidate_results=[
common_types.ResponseCandidateResult(
response_index=0,
metric_results={
"multi_turn_task_success_v1": common_types.EvalCaseMetricResult(
score=0.0,
),
},
)
],
)
],
evaluation_dataset=[
common_types.EvaluationDataset(
eval_cases=[
common_types.EvalCase(
user_scenario=vertexai_genai_types.evals.UserScenario(
starting_prompt="I want to book a hotel in Tokyo.",
conversation_plan="User asks to book a hotel.",
)
)
]
)
],
metadata=common_types.EvaluationRunMetadata(
candidate_names=["travel-agent"]
),
)
_evals_utils._enrich_loss_response_with_rubric_descriptions(
api_response, eval_result
)
example = api_response.results[0].clusters[0].examples[0]
assert "scenario_preview" in example.evaluation_result
assert (
example.evaluation_result["scenario_preview"]
== "I want to book a hotel in Tokyo."
)
def test_enrich_scenario_from_dataframe_agent_data(self):
"""Tests scenario extraction from DataFrame agent_data column."""
import pandas as pd
from vertexai._genai import _evals_utils
api_response = common_types.GenerateLossClustersResponse(
results=[
common_types.LossAnalysisResult(
config=common_types.LossAnalysisConfig(
metric="multi_turn_task_success_v1",
candidate="travel-agent",
),
clusters=[
common_types.LossCluster(
cluster_id="c1",
taxonomy_entry=common_types.LossTaxonomyEntry(
l1_category="Tool Calling",
l2_category="Missing Invocation",
),
item_count=1,
examples=[
common_types.LossExample(
evaluation_result={
"candidateResults": [
{"candidate": "travel-agent"}
]
},
failed_rubrics=[
common_types.FailedRubric(rubric_id="t1")
],
)
],
)
],
)
],
)
# eval_result with agent_data in DataFrame (run_inference output)
agent_data_obj = vertexai_genai_types.evals.AgentData(
turns=[
vertexai_genai_types.evals.ConversationTurn(
turn_index=0,
events=[
vertexai_genai_types.evals.AgentEvent(
author="user",
content={"parts": [{"text": "Find flights to London"}]},
),
],
)
],
)
df = pd.DataFrame({"agent_data": [agent_data_obj]})
eval_result = common_types.EvaluationResult(
eval_case_results=[
common_types.EvalCaseResult(
eval_case_index=0,
response_candidate_results=[
common_types.ResponseCandidateResult(
response_index=0,
metric_results={
"multi_turn_task_success_v1": common_types.EvalCaseMetricResult(
score=0.0,
),
},
)
],
)
],
evaluation_dataset=[common_types.EvaluationDataset(eval_dataset_df=df)],
metadata=common_types.EvaluationRunMetadata(
candidate_names=["travel-agent"]
),
)
_evals_utils._enrich_loss_response_with_rubric_descriptions(
api_response, eval_result
)
example = api_response.results[0].clusters[0].examples[0]
assert "scenario_preview" in example.evaluation_result
assert example.evaluation_result["scenario_preview"] == "Find flights to London"
def test_enrich_scenario_e2e_simulation(self):
"""Simulates the full e2e flow: generate_scenarios -> run_inference -> evaluate -> loss_clusters."""
import pandas as pd
from vertexai._genai import _evals_utils
# Step 1: Simulate generate_conversation_scenarios output
# This creates eval_cases with user_scenario but no agent_data
scenario_dataset = common_types.EvaluationDataset(