Skip to content

Commit eba7c46

Browse files
vertex-sdk-botcopybara-github
authored andcommitted
feat: GenAI Client(evals) - add user-facing generate_loss_clusters with LRO polling and replay tests
PiperOrigin-RevId: 893874547
1 parent 8710b02 commit eba7c46

7 files changed

Lines changed: 3841 additions & 2713 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() correctly calls the API and returns LossClusters."""
24+
eval_result = types.EvaluationResult()
25+
loss_clusters = 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 type(loss_clusters).__name__ == "LossClusters"
33+
assert len(loss_clusters.results) == 1
34+
result = loss_clusters.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 correctly calls the API and returns LossClusters."""
55+
eval_result = types.EvaluationResult()
56+
loss_clusters = 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 type(loss_clusters).__name__ == "LossClusters"
64+
assert len(loss_clusters.results) == 1
65+
result = loss_clusters.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: 131 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -29,13 +29,16 @@
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
3536
from vertexai._genai import _gcs_utils
3637
from vertexai._genai import _observability_data_converter
38+
from vertexai._genai import _transformers
3739
from vertexai._genai import evals
3840
from vertexai._genai import types as vertexai_genai_types
41+
from vertexai._genai.types import common as common_types
3942
from google.genai import client
4043
from google.genai import errors as genai_errors
4144
from google.genai import types as genai_types
@@ -218,6 +221,133 @@ def test_get_api_client_with_none_location(
218221
mock_vertexai_client.assert_not_called()
219222

220223

224+
class TestTransformers:
225+
"""Unit tests for transformers."""
226+
227+
def test_t_inline_results(self):
228+
eval_result = common_types.EvaluationResult(
229+
eval_case_results=[
230+
common_types.EvalCaseResult(
231+
eval_case_index=0,
232+
response_candidate_results=[
233+
common_types.ResponseCandidateResult(
234+
response_index=0,
235+
metric_results={
236+
"tool_use_quality": common_types.EvalCaseMetricResult(
237+
score=0.0,
238+
explanation="Failed tool use",
239+
)
240+
},
241+
)
242+
],
243+
)
244+
],
245+
evaluation_dataset=[
246+
common_types.EvaluationDataset(
247+
eval_cases=[
248+
common_types.EvalCase(
249+
prompt=genai_types.Content(
250+
parts=[genai_types.Part(text="test prompt")]
251+
)
252+
)
253+
]
254+
)
255+
],
256+
metadata=common_types.EvaluationRunMetadata(candidate_names=["gemini-pro"]),
257+
)
258+
259+
payload = _transformers.t_inline_results([eval_result])
260+
261+
assert len(payload) == 1
262+
assert payload[0]["metric"] == "tool_use_quality"
263+
assert payload[0]["request"]["prompt"]["text"] == "test prompt"
264+
assert len(payload[0]["candidate_results"]) == 1
265+
assert payload[0]["candidate_results"][0]["candidate"] == "gemini-pro"
266+
assert payload[0]["candidate_results"][0]["score"] == 0.0
267+
268+
269+
class TestLossClusters:
270+
"""Unit tests for LossClusters and postprocessing."""
271+
272+
def test_postprocess_loss_clusters_response(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+
loss_clusters = _evals_utils._postprocess_loss_clusters_response(response)
306+
assert isinstance(loss_clusters, _evals_utils.LossClusters)
307+
assert len(loss_clusters.results) == 1
308+
assert loss_clusters.analysis_time == "2026-04-01T10:00:00Z"
309+
result = loss_clusters.results[0]
310+
assert result.config.metric == "multi_turn_task_success_v1"
311+
assert len(result.clusters) == 2
312+
assert result.clusters[0].cluster_id == "cluster-1"
313+
assert result.clusters[0].item_count == 3
314+
assert result.clusters[1].cluster_id == "cluster-2"
315+
316+
def test_loss_clusters_show_no_clusters(self, capsys):
317+
response = common_types.GenerateLossClustersResponse(results=[])
318+
loss_clusters = _evals_utils._postprocess_loss_clusters_response(response)
319+
loss_clusters.show()
320+
captured = capsys.readouterr()
321+
assert "No loss clusters found" in captured.out
322+
323+
def test_loss_clusters_show_with_clusters(self, capsys):
324+
response = common_types.GenerateLossClustersResponse(
325+
results=[
326+
common_types.LossAnalysisResult(
327+
config=common_types.LossAnalysisConfig(
328+
metric="test_metric",
329+
candidate="test-candidate",
330+
),
331+
clusters=[
332+
common_types.LossCluster(
333+
cluster_id="c1",
334+
taxonomy_entry=common_types.LossTaxonomyEntry(
335+
l1_category="Cat1",
336+
l2_category="SubCat1",
337+
),
338+
item_count=5,
339+
),
340+
],
341+
)
342+
],
343+
)
344+
loss_clusters = _evals_utils._postprocess_loss_clusters_response(response)
345+
loss_clusters.show()
346+
captured = capsys.readouterr()
347+
assert "Cat1" in captured.out
348+
assert "SubCat1" in captured.out
349+
350+
221351
class TestEvals:
222352
"""Unit tests for the GenAI client."""
223353

@@ -1754,7 +1884,7 @@ def test_run_inference_with_litellm_openai_request_format(
17541884
self,
17551885
mock_api_client_fixture,
17561886
):
1757-
"""Tests inference with LiteLLM where the row contains an chat completion request body."""
1887+
"""Tests inference with LiteLLM where the row contains a chat completion request body."""
17581888
with mock.patch(
17591889
"vertexai._genai._evals_common.litellm"
17601890
) as mock_litellm, mock.patch(

0 commit comments

Comments
 (0)