Skip to content

Commit 5a67575

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 5a67575

7 files changed

Lines changed: 1150 additions & 64 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(

vertexai/_genai/_evals_utils.py

Lines changed: 117 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,9 +15,11 @@
1515
"""Utility functions for evals."""
1616

1717
import abc
18+
import asyncio
19+
import json
1820
import logging
1921
import os
20-
import json
22+
import time
2123
from typing import Any, Optional, Union
2224

2325
from google.genai._api_client import BaseApiClient
@@ -366,6 +368,120 @@ def _postprocess_user_scenarios_response(
366368
)
367369

368370

371+
class LossClusters:
372+
"""User-friendly wrapper for loss analysis results with visualization."""
373+
374+
def __init__(
375+
self,
376+
response: types.GenerateLossClustersResponse,
377+
):
378+
self._response = response
379+
self.results = response.results or []
380+
self.analysis_time = response.analysis_time
381+
382+
def show(self) -> None:
383+
"""Displays the loss clusters as a formatted pandas DataFrame."""
384+
rows = []
385+
for result in self.results:
386+
metric = result.config.metric if result.config else None
387+
candidate = result.config.candidate if result.config else None
388+
for cluster in result.clusters or []:
389+
entry = cluster.taxonomy_entry
390+
row = {
391+
"metric": metric,
392+
"candidate": candidate,
393+
"cluster_id": cluster.cluster_id,
394+
"l1_category": entry.l1_category if entry else None,
395+
"l2_category": entry.l2_category if entry else None,
396+
"description": entry.description if entry else None,
397+
"item_count": cluster.item_count,
398+
}
399+
rows.append(row)
400+
401+
if not rows:
402+
print("No loss clusters found.") # pylint: disable=print-function
403+
return
404+
405+
df = pd.DataFrame(rows)
406+
try:
407+
from IPython.display import display # pylint: disable=g-import-not-at-top
408+
409+
display(df)
410+
except ImportError:
411+
print(df.to_string()) # pylint: disable=print-function
412+
413+
414+
def _postprocess_loss_clusters_response(
415+
response: types.GenerateLossClustersResponse,
416+
) -> LossClusters:
417+
"""Wraps the GenerateLossClustersResponse in a LossClusters object."""
418+
return LossClusters(response=response)
419+
420+
421+
def _poll_operation(
422+
api_client: BaseApiClient,
423+
operation_name: str,
424+
poll_interval_seconds: float = 5.0,
425+
) -> types.GenerateLossClustersOperation:
426+
"""Polls a long-running operation until completion.
427+
428+
Args:
429+
api_client: The API client to use for polling.
430+
operation_name: The full resource name of the operation.
431+
poll_interval_seconds: Time between polls.
432+
433+
Returns:
434+
The completed operation.
435+
"""
436+
start_time = time.time()
437+
while True:
438+
response = api_client.request("get", operation_name, {}, None)
439+
response_dict = {} if not response.body else json.loads(response.body)
440+
operation = types.GenerateLossClustersOperation._from_response(
441+
response=response_dict, kwargs={}
442+
)
443+
if operation.done:
444+
return operation
445+
elapsed = int(time.time() - start_time)
446+
logger.info(
447+
"Loss analysis operation still running... Elapsed time: %d seconds",
448+
elapsed,
449+
)
450+
time.sleep(poll_interval_seconds)
451+
452+
453+
async def _poll_operation_async(
454+
api_client: BaseApiClient,
455+
operation_name: str,
456+
poll_interval_seconds: float = 5.0,
457+
) -> types.GenerateLossClustersOperation:
458+
"""Polls a long-running operation until completion (async).
459+
460+
Args:
461+
api_client: The API client to use for polling.
462+
operation_name: The full resource name of the operation.
463+
poll_interval_seconds: Time between polls.
464+
465+
Returns:
466+
The completed operation.
467+
"""
468+
start_time = time.time()
469+
while True:
470+
response = await api_client.async_request("get", operation_name, {}, None)
471+
response_dict = {} if not response.body else json.loads(response.body)
472+
operation = types.GenerateLossClustersOperation._from_response(
473+
response=response_dict, kwargs={}
474+
)
475+
if operation.done:
476+
return operation
477+
elapsed = int(time.time() - start_time)
478+
logger.info(
479+
"Loss analysis operation still running... Elapsed time: %d seconds",
480+
elapsed,
481+
)
482+
await asyncio.sleep(poll_interval_seconds)
483+
484+
369485
def _validate_dataset_agent_data(
370486
dataset: types.EvaluationDataset,
371487
inference_configs: Optional[dict[str, Any]] = None,

0 commit comments

Comments
 (0)