Skip to content

Commit bafab9f

Browse files
vertex-sdk-botcopybara-github
authored andcommitted
feat: GenAI Client(evals) - auto-infer metric/candidate and validate inputs for generate_loss_clusters
PiperOrigin-RevId: 894079615
1 parent 09794ba commit bafab9f

6 files changed

Lines changed: 911 additions & 2 deletions

File tree

Lines changed: 76 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,76 @@
1+
# Copyright 2026 Google LLC
2+
#
3+
# Licensed under the Apache License, Version 2.0 (the "License");
4+
# you may not use this file except in compliance with the License.
5+
# You may obtain a copy of the License at
6+
#
7+
# http://www.apache.org/licenses/LICENSE-2.0
8+
#
9+
# Unless required by applicable law or agreed to in writing, software
10+
# distributed under the License is distributed on an "AS IS" BASIS,
11+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
# See the License for the specific language governing permissions and
13+
# limitations under the License.
14+
#
15+
# pylint: disable=protected-access,bad-continuation,missing-function-docstring
16+
17+
from tests.unit.vertexai.genai.replays import pytest_helper
18+
from vertexai import types
19+
import pytest
20+
21+
22+
def test_gen_loss_clusters(client):
23+
"""Tests that generate_loss_clusters() returns GenerateLossClustersResponse."""
24+
eval_result = types.EvaluationResult()
25+
response = client.evals.generate_loss_clusters(
26+
eval_result=eval_result,
27+
config=types.LossAnalysisConfig(
28+
metric="multi_turn_task_success_v1",
29+
candidate="travel-agent",
30+
),
31+
)
32+
assert isinstance(response, types.GenerateLossClustersResponse)
33+
assert len(response.results) == 1
34+
result = response.results[0]
35+
assert result.config.metric == "multi_turn_task_success_v1"
36+
assert result.config.candidate == "travel-agent"
37+
assert len(result.clusters) == 2
38+
assert result.clusters[0].cluster_id == "cluster-1"
39+
assert result.clusters[0].taxonomy_entry.l1_category == "Tool Calling"
40+
assert (
41+
result.clusters[0].taxonomy_entry.l2_category == "Missing Tool Invocation"
42+
)
43+
assert result.clusters[0].item_count == 3
44+
assert result.clusters[1].cluster_id == "cluster-2"
45+
assert result.clusters[1].taxonomy_entry.l1_category == "Hallucination"
46+
assert result.clusters[1].item_count == 2
47+
48+
49+
pytest_plugins = ("pytest_asyncio",)
50+
51+
52+
@pytest.mark.asyncio
53+
async def test_gen_loss_clusters_async(client):
54+
"""Tests that generate_loss_clusters() async returns GenerateLossClustersResponse."""
55+
eval_result = types.EvaluationResult()
56+
response = await client.aio.evals.generate_loss_clusters(
57+
eval_result=eval_result,
58+
config=types.LossAnalysisConfig(
59+
metric="multi_turn_task_success_v1",
60+
candidate="travel-agent",
61+
),
62+
)
63+
assert isinstance(response, types.GenerateLossClustersResponse)
64+
assert len(response.results) == 1
65+
result = response.results[0]
66+
assert result.config.metric == "multi_turn_task_success_v1"
67+
assert len(result.clusters) == 2
68+
assert result.clusters[0].cluster_id == "cluster-1"
69+
assert result.clusters[1].cluster_id == "cluster-2"
70+
71+
72+
pytestmark = pytest_helper.setup(
73+
file=__file__,
74+
globals_for_file=globals(),
75+
test_method="evals.generate_loss_clusters",
76+
)

tests/unit/vertexai/genai/test_evals.py

Lines changed: 277 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,7 @@
2929
from google.cloud.aiplatform import initializer as aiplatform_initializer
3030
from vertexai import _genai
3131
from vertexai._genai import _evals_data_converters
32+
from vertexai._genai import _evals_utils
3233
from vertexai._genai import _evals_metric_handlers
3334
from vertexai._genai import _evals_visualization
3435
from vertexai._genai import _evals_metric_loaders
@@ -265,6 +266,282 @@ def test_t_inline_results(self):
265266
assert payload[0]["candidate_results"][0]["score"] == 0.0
266267

267268

269+
class TestLossAnalysis:
270+
"""Unit tests for loss analysis types and visualization."""
271+
272+
def test_response_structure(self):
273+
response = common_types.GenerateLossClustersResponse(
274+
analysis_time="2026-04-01T10:00:00Z",
275+
results=[
276+
common_types.LossAnalysisResult(
277+
config=common_types.LossAnalysisConfig(
278+
metric="multi_turn_task_success_v1",
279+
candidate="travel-agent",
280+
),
281+
analysis_time="2026-04-01T10:00:00Z",
282+
clusters=[
283+
common_types.LossCluster(
284+
cluster_id="cluster-1",
285+
taxonomy_entry=common_types.LossTaxonomyEntry(
286+
l1_category="Tool Calling",
287+
l2_category="Missing Tool Invocation",
288+
description="The agent failed to invoke a required tool.",
289+
),
290+
item_count=3,
291+
),
292+
common_types.LossCluster(
293+
cluster_id="cluster-2",
294+
taxonomy_entry=common_types.LossTaxonomyEntry(
295+
l1_category="Hallucination",
296+
l2_category="Hallucination of Action",
297+
description="Verbally confirmed action without tool.",
298+
),
299+
item_count=2,
300+
),
301+
],
302+
)
303+
],
304+
)
305+
assert len(response.results) == 1
306+
assert response.analysis_time == "2026-04-01T10:00:00Z"
307+
result = response.results[0]
308+
assert result.config.metric == "multi_turn_task_success_v1"
309+
assert len(result.clusters) == 2
310+
assert result.clusters[0].cluster_id == "cluster-1"
311+
assert result.clusters[0].item_count == 3
312+
assert result.clusters[1].cluster_id == "cluster-2"
313+
314+
def test_response_show_with_results(self, capsys):
315+
response = common_types.GenerateLossClustersResponse(
316+
results=[
317+
common_types.LossAnalysisResult(
318+
config=common_types.LossAnalysisConfig(
319+
metric="test_metric",
320+
candidate="test-candidate",
321+
),
322+
clusters=[
323+
common_types.LossCluster(
324+
cluster_id="c1",
325+
taxonomy_entry=common_types.LossTaxonomyEntry(
326+
l1_category="Cat1",
327+
l2_category="SubCat1",
328+
),
329+
item_count=5,
330+
),
331+
],
332+
)
333+
],
334+
)
335+
response.show()
336+
captured = capsys.readouterr()
337+
assert "test_metric" in captured.out
338+
assert "c1" in captured.out
339+
340+
def test_loss_analysis_result_show(self, capsys):
341+
result = common_types.LossAnalysisResult(
342+
config=common_types.LossAnalysisConfig(
343+
metric="test_metric",
344+
candidate="test-candidate",
345+
),
346+
clusters=[
347+
common_types.LossCluster(
348+
cluster_id="c1",
349+
taxonomy_entry=common_types.LossTaxonomyEntry(
350+
l1_category="DirectCat",
351+
l2_category="DirectSubCat",
352+
),
353+
item_count=7,
354+
),
355+
],
356+
)
357+
result.show()
358+
captured = capsys.readouterr()
359+
assert "test_metric" in captured.out
360+
assert "c1" in captured.out
361+
362+
363+
def _make_eval_result(
364+
metrics=None,
365+
candidate_names=None,
366+
):
367+
"""Helper to create an EvaluationResult with the given metrics and candidates."""
368+
metrics = metrics or ["task_success_v1"]
369+
candidate_names = candidate_names or ["agent-1"]
370+
371+
metric_results = {}
372+
for m in metrics:
373+
metric_results[m] = common_types.EvalCaseMetricResult(metric_name=m)
374+
375+
eval_case_results = [
376+
common_types.EvalCaseResult(
377+
eval_case_index=0,
378+
response_candidate_results=[
379+
common_types.ResponseCandidateResult(
380+
response_index=0,
381+
metric_results=metric_results,
382+
)
383+
],
384+
)
385+
]
386+
metadata = common_types.EvaluationRunMetadata(
387+
candidate_names=candidate_names,
388+
)
389+
return common_types.EvaluationResult(
390+
eval_case_results=eval_case_results,
391+
metadata=metadata,
392+
)
393+
394+
395+
class TestResolveMetricName:
396+
"""Unit tests for _resolve_metric_name."""
397+
398+
def test_none_returns_none(self):
399+
assert _evals_utils._resolve_metric_name(None) is None
400+
401+
def test_string_passes_through(self):
402+
assert _evals_utils._resolve_metric_name("task_success_v1") == "task_success_v1"
403+
404+
def test_metric_object_extracts_name(self):
405+
metric = common_types.Metric(name="multi_turn_task_success_v1")
406+
assert (
407+
_evals_utils._resolve_metric_name(metric)
408+
== "multi_turn_task_success_v1"
409+
)
410+
411+
def test_object_with_name_attr(self):
412+
"""Tests that any object with a .name attribute works (e.g., LazyLoadedPrebuiltMetric)."""
413+
414+
class FakeMetric:
415+
name = "tool_use_quality_v1"
416+
417+
assert _evals_utils._resolve_metric_name(FakeMetric()) == "tool_use_quality_v1"
418+
419+
def test_lazy_loaded_prebuilt_metric_resolves_versioned_name(self):
420+
"""Tests that LazyLoadedPrebuiltMetric resolves to the versioned API spec name."""
421+
422+
class FakeLazyMetric:
423+
name = "MULTI_TURN_TASK_SUCCESS"
424+
425+
def _get_api_metric_spec_name(self):
426+
return "multi_turn_task_success_v1"
427+
428+
assert (
429+
_evals_utils._resolve_metric_name(FakeLazyMetric())
430+
== "multi_turn_task_success_v1"
431+
)
432+
433+
def test_lazy_loaded_prebuilt_metric_falls_back_to_name(self):
434+
"""Tests fallback to .name when _get_api_metric_spec_name returns None."""
435+
436+
class FakeLazyMetricNoSpec:
437+
name = "CUSTOM_METRIC"
438+
439+
def _get_api_metric_spec_name(self):
440+
return None
441+
442+
assert (
443+
_evals_utils._resolve_metric_name(FakeLazyMetricNoSpec())
444+
== "CUSTOM_METRIC"
445+
)
446+
447+
448+
class TestResolveLossAnalysisConfig:
449+
"""Unit tests for _resolve_loss_analysis_config."""
450+
451+
def test_auto_infer_single_metric_and_candidate(self):
452+
eval_result = _make_eval_result(
453+
metrics=["task_success_v1"], candidate_names=["agent-1"]
454+
)
455+
resolved = _evals_utils._resolve_loss_analysis_config(
456+
eval_result=eval_result
457+
)
458+
assert resolved.metric == "task_success_v1"
459+
assert resolved.candidate == "agent-1"
460+
461+
def test_explicit_metric_and_candidate(self):
462+
eval_result = _make_eval_result(
463+
metrics=["m1", "m2"], candidate_names=["c1", "c2"]
464+
)
465+
resolved = _evals_utils._resolve_loss_analysis_config(
466+
eval_result=eval_result, metric="m1", candidate="c2"
467+
)
468+
assert resolved.metric == "m1"
469+
assert resolved.candidate == "c2"
470+
471+
def test_config_provides_metric_and_candidate(self):
472+
eval_result = _make_eval_result(
473+
metrics=["m1"], candidate_names=["c1"]
474+
)
475+
config = common_types.LossAnalysisConfig(
476+
metric="m1", candidate="c1", predefined_taxonomy="my_taxonomy"
477+
)
478+
resolved = _evals_utils._resolve_loss_analysis_config(
479+
eval_result=eval_result, config=config
480+
)
481+
assert resolved.metric == "m1"
482+
assert resolved.candidate == "c1"
483+
assert resolved.predefined_taxonomy == "my_taxonomy"
484+
485+
def test_explicit_args_override_config(self):
486+
eval_result = _make_eval_result(
487+
metrics=["m1", "m2"], candidate_names=["c1", "c2"]
488+
)
489+
config = common_types.LossAnalysisConfig(metric="m1", candidate="c1")
490+
resolved = _evals_utils._resolve_loss_analysis_config(
491+
eval_result=eval_result, config=config, metric="m2", candidate="c2"
492+
)
493+
assert resolved.metric == "m2"
494+
assert resolved.candidate == "c2"
495+
496+
def test_error_multiple_metrics_no_explicit(self):
497+
eval_result = _make_eval_result(
498+
metrics=["m1", "m2"], candidate_names=["c1"]
499+
)
500+
with pytest.raises(ValueError, match="multiple metrics"):
501+
_evals_utils._resolve_loss_analysis_config(eval_result=eval_result)
502+
503+
def test_error_multiple_candidates_no_explicit(self):
504+
eval_result = _make_eval_result(
505+
metrics=["m1"], candidate_names=["c1", "c2"]
506+
)
507+
with pytest.raises(ValueError, match="multiple candidates"):
508+
_evals_utils._resolve_loss_analysis_config(eval_result=eval_result)
509+
510+
def test_error_invalid_metric(self):
511+
eval_result = _make_eval_result(
512+
metrics=["m1"], candidate_names=["c1"]
513+
)
514+
with pytest.raises(ValueError, match="not found in eval_result"):
515+
_evals_utils._resolve_loss_analysis_config(
516+
eval_result=eval_result, metric="nonexistent"
517+
)
518+
519+
def test_error_invalid_candidate(self):
520+
eval_result = _make_eval_result(
521+
metrics=["m1"], candidate_names=["c1"]
522+
)
523+
with pytest.raises(ValueError, match="not found in eval_result"):
524+
_evals_utils._resolve_loss_analysis_config(
525+
eval_result=eval_result, candidate="nonexistent"
526+
)
527+
528+
def test_no_candidates_defaults_to_candidate_1(self):
529+
eval_result = _make_eval_result(metrics=["m1"], candidate_names=[])
530+
eval_result = eval_result.model_copy(
531+
update={"metadata": common_types.EvaluationRunMetadata()}
532+
)
533+
resolved = _evals_utils._resolve_loss_analysis_config(
534+
eval_result=eval_result
535+
)
536+
assert resolved.metric == "m1"
537+
assert resolved.candidate == "candidate_1"
538+
539+
def test_no_eval_case_results_raises(self):
540+
eval_result = common_types.EvaluationResult()
541+
with pytest.raises(ValueError, match="no metric results"):
542+
_evals_utils._resolve_loss_analysis_config(eval_result=eval_result)
543+
544+
268545
class TestEvals:
269546
"""Unit tests for the GenAI client."""
270547

0 commit comments

Comments
 (0)