-
Notifications
You must be signed in to change notification settings - Fork 459
Expand file tree
/
Copy path_evals_common.py
More file actions
4171 lines (3694 loc) · 159 KB
/
Copy path_evals_common.py
File metadata and controls
4171 lines (3694 loc) · 159 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.
#
"""Common utilities for evals."""
import asyncio
import base64
import collections
import concurrent.futures
import contextlib
import datetime
import json
import logging
import os
import threading
import time
from typing import Any, Callable, Literal, Optional, Union, cast
import uuid
from google.api_core import exceptions as api_exceptions
from google.genai import errors as genai_errors
import agentplatform
from google.genai import types as genai_types
from google.genai._api_client import BaseApiClient
from google.genai._gaos.types.interactions import interaction as interaction_types
from google.genai._gaos.types.interactions import functioncallstep
from google.genai._gaos.types.interactions import functionresultstep
from google.genai._gaos.types.interactions import modeloutputstep
from google.genai._gaos.types.interactions import userinputstep
from google.genai.models import Models
import pandas as pd
from tqdm import tqdm
from pydantic import ValidationError
from . import _evals_builtin_tools
from . import _evals_constant
from . import _evals_data_converters
from . import _evals_metric_handlers
from . import _evals_metric_loaders
from . import _evals_utils
from . import _gcs_utils
from . import evals
from . import types
from . import _transformers as t
logger = logging.getLogger(__name__)
try:
import litellm
except ImportError:
litellm = None
_thread_local_data = threading.local()
MAX_WORKERS = 100
AGENT_MAX_WORKERS = 20
_MAX_INTERACTION_CHAIN_DEPTH = 10
# Default per-request timeout (milliseconds) for a user simulator model turn.
_USER_SIMULATOR_TIMEOUT_MS = 300000
# Per-request timeout (milliseconds) for individual Interactions API calls so a
# single create/poll cannot block forever.
_INTERACTION_REQUEST_TIMEOUT_MS = 60000
# Hard ceiling (seconds) for a single multi-turn simulated conversation.
_USER_SIMULATION_SCENARIO_TIMEOUT_SECONDS = 1200.0
# Expected, per-scenario failures during user simulation. These are recorded as
# an empty row so one bad scenario does not abort the whole batch; anything else
# propagates.
_USER_SIMULATION_SCENARIO_ERRORS = (
TimeoutError,
ValueError,
RuntimeError,
genai_errors.APIError,
api_exceptions.GoogleAPICallError,
)
CONTENT = _evals_constant.CONTENT
PARTS = _evals_constant.PARTS
USER_AUTHOR = _evals_constant.USER_AUTHOR
AGENT_DATA = _evals_constant.AGENT_DATA
def _local_timestamp() -> str:
"""Returns the current local time as 'M/D/YYYY, H:MM:SS AM/PM'.
Matches the Agent Platform UI's default experiment name timestamp format
(e.g. '6/1/2026, 1:12:29 PM').
"""
now = datetime.datetime.now()
hour_12 = now.hour % 12 or 12
meridiem = "AM" if now.hour < 12 else "PM"
return (
f"{now.month}/{now.day}/{now.year}, "
f"{hour_12}:{now.minute:02d}:{now.second:02d} {meridiem}"
)
@contextlib.contextmanager
def _temp_logger_level(logger_name: str, level: int) -> None: # type: ignore[misc]
"""Temporarily sets the level of a logger."""
logger_instance = logging.getLogger(logger_name)
original_level = logger_instance.getEffectiveLevel()
logger_instance.setLevel(level)
try:
yield
finally:
logger_instance.setLevel(original_level)
def _get_api_client_with_location(
api_client: BaseApiClient, location: Optional[str]
) -> BaseApiClient:
"""Returns a new API client with the specified location."""
if not location or location == api_client.location:
return api_client
logger.info(
"Model endpoint location set to %s, overriding client location %s for"
" this API call.",
location,
api_client.location,
)
return agentplatform.Client( # type: ignore[no-any-return]
project=api_client.project,
location=location,
credentials=api_client._credentials,
http_options=api_client._http_options,
)._api_client
def _get_agent_engine_instance(
agent_name: str, api_client: BaseApiClient
) -> Union[types.AgentEngine, Any]:
"""Gets or creates an agent engine instance for the current thread."""
if not hasattr(_thread_local_data, "agent_engine_instances"):
_thread_local_data.agent_engine_instances = {}
if agent_name not in _thread_local_data.agent_engine_instances:
client = agentplatform.Client(
project=api_client.project,
location=api_client.location,
)
_thread_local_data.agent_engine_instances[agent_name] = (
client.agent_engines.get(name=agent_name)
)
return _thread_local_data.agent_engine_instances[agent_name]
def _generate_content_with_retry(
api_client: BaseApiClient,
model: str,
contents: Union[genai_types.ContentListUnion, genai_types.ContentListUnionDict],
config: Optional[genai_types.GenerateContentConfig] = None,
max_retries: int = 3,
) -> Union[genai_types.GenerateContentResponse, dict[str, Any]]:
"""Generates content using the model's generate_content with retries."""
models_module = Models(api_client_=api_client)
for attempt in range(max_retries):
try:
response = models_module.generate_content(
model=model,
contents=contents,
config=config,
)
if not response.candidates:
logger.warning(
"Prompt blocked. Attempt %d/%d. Feedback: %s. Prompt: %s.",
attempt + 1,
max_retries,
response.prompt_feedback,
contents,
)
if attempt == max_retries - 1:
feedback_dict = {}
if response.prompt_feedback:
feedback_dict = response.prompt_feedback.model_dump(
mode="json", exclude_none=True
)
return {
"error": "Prompt blocked after retries",
"prompt_feedback": feedback_dict,
}
else:
candidate = response.candidates[0]
if candidate.finish_reason not in (
genai_types.FinishReason.STOP,
genai_types.FinishReason.MAX_TOKENS,
genai_types.FinishReason.FINISH_REASON_UNSPECIFIED,
):
logger.warning(
"Generate content did not finish successfully."
"Finish reason: %s. Finish message: %s."
"Retry attempt: %d/%d",
candidate.finish_reason,
candidate.finish_message,
attempt + 1,
max_retries,
)
if attempt == max_retries - 1:
return {
"error": (
"Generate content unsuccessful after retries:"
f" {candidate.finish_reason}"
),
"finish_reason": str(candidate.finish_reason),
"finish_message": candidate.finish_message or "",
}
else:
return response
except api_exceptions.ResourceExhausted as e:
logger.warning(
"Resource Exhausted error on attempt %d/%d: %s. Retrying in %s"
" seconds...",
attempt + 1,
max_retries,
e,
2**attempt,
)
if attempt == max_retries - 1:
return {"error": f"Resource exhausted after retries: {e}"}
time.sleep(2**attempt)
except Exception as e: # pylint: disable=broad-exception-caught
logger.error(
"Unexpected error during generate_content on attempt %d/%d: %s",
attempt + 1,
max_retries,
e,
)
if attempt == max_retries - 1:
return {"error": f"Failed after retries: {e}"}
time.sleep(1)
return {"error": f"Failed to generate content after {max_retries} retries"}
def _build_generate_content_config(
request_dict: Union[dict[str, Any], str],
global_config: Optional[genai_types.GenerateContentConfig] = None,
) -> genai_types.GenerateContentConfig:
"""Builds a GenerateContentConfig from the request dictionary or provided config."""
if global_config:
# If a global config is provided, apply it as a base config. Parts of
# the global config can be overridden by providing configs in the
# request.
merged_config_dict = global_config.model_dump(exclude_none=True)
else:
merged_config_dict = {}
if not isinstance(request_dict, dict):
return genai_types.GenerateContentConfig(**merged_config_dict)
for key in [
"system_instruction",
"tools",
"tools_config",
"safety_settings",
"labels",
]:
if key in request_dict:
merged_config_dict[key] = request_dict[key]
if "generation_config" in request_dict and isinstance(
request_dict["generation_config"], dict
):
merged_config_dict.update(request_dict["generation_config"])
if "labels" in request_dict:
merged_config_dict["labels"] = request_dict["labels"]
return genai_types.GenerateContentConfig(**merged_config_dict)
def _extract_contents_for_inference(
request_dict_or_raw_text: Any,
) -> Any:
"""Extracts contents from a request dictionary or returns the raw text."""
if not request_dict_or_raw_text:
raise ValueError("Prompt cannot be empty.")
if isinstance(request_dict_or_raw_text, dict):
contents_for_fn = request_dict_or_raw_text.get("contents", None)
if not contents_for_fn:
raise ValueError("Contents in the request cannot be empty.")
return contents_for_fn
else:
return request_dict_or_raw_text
def _eval_cases_to_dataframe(
eval_cases: list[types.EvalCase],
) -> pd.DataFrame:
"""Converts a list of EvalCase objects to a pandas DataFrame.
Each EvalCase is converted to a row in the DataFrame. Structured fields
like ``agent_data`` are preserved as-is (not flattened) so that downstream
agent execution paths can consume them directly.
Args:
eval_cases: The list of EvalCase objects to convert.
Returns:
A DataFrame with one row per EvalCase.
"""
rows = []
for case in eval_cases:
row: dict[str, Any] = {}
if case.prompt:
row[_evals_constant.PROMPT] = _evals_data_converters._get_content_text(
case.prompt
)
if case.responses and len(case.responses) > 0 and case.responses[0].response:
row[_evals_constant.RESPONSE] = _evals_data_converters._get_content_text(
case.responses[0].response
)
if case.reference and case.reference.response:
row[_evals_constant.REFERENCE] = _evals_data_converters._get_content_text(
case.reference.response
)
if case.agent_data:
row[AGENT_DATA] = case.agent_data
if case.intermediate_events:
row[_evals_constant.INTERMEDIATE_EVENTS] = [
{CONTENT: event.content}
for event in case.intermediate_events
if event.content
]
if case.conversation_history:
history_parts = []
for msg in case.conversation_history:
if msg.content:
role = msg.content.role or "user"
text = _evals_data_converters._get_content_text(msg.content)
history_parts.append(f"{role}: {text}")
if history_parts:
row[_evals_constant.CONVERSATION_HISTORY] = "\n".join(history_parts)
if case.user_scenario:
if case.user_scenario.starting_prompt:
row[_evals_constant.STARTING_PROMPT] = (
case.user_scenario.starting_prompt
)
if case.user_scenario.conversation_plan:
row[_evals_constant.CONVERSATION_PLAN] = (
case.user_scenario.conversation_plan
)
rows.append(row)
return pd.DataFrame(rows)
def _extract_prompt_from_agent_data(
agent_data: types.evals.AgentData,
) -> tuple[genai_types.Content, list[types.evals.AgentEvent]]:
"""Extracts the last user message and prior events from agent_data.
The last event across all turns must be authored by ``"user"``; it is
treated as the current prompt that the agent should respond to.
Everything before it is returned as conversation history.
Args:
agent_data: The AgentData containing conversation turns.
Returns:
A tuple of ``(last_user_content, history_events)`` where
``last_user_content`` is the ``Content`` of the final user event
and ``history_events`` is the ordered list of all prior
``AgentEvent`` objects.
Raises:
ValueError: If ``agent_data`` has no turns, no events, or the last
event is not a user event.
"""
if not agent_data.turns:
raise ValueError("agent_data must have at least one turn.")
all_events: list[types.evals.AgentEvent] = []
for turn in agent_data.turns:
if turn.events:
all_events.extend(turn.events)
if not all_events:
raise ValueError("agent_data turns contain no events.")
last_event = all_events[-1]
if last_event.author != USER_AUTHOR:
raise ValueError(
"agent_data must end with a user event, but the last event has"
f" author='{last_event.author}'."
)
if not last_event.content:
raise ValueError("The last user event in agent_data has no content.")
return last_event.content, all_events[:-1]
def _is_n_plus_1_inference(
agent_data: Union[types.evals.AgentData, dict[str, Any]],
) -> bool:
"""Returns True if agent_data represents an N+1 inference case.
An N+1 case means the trace is incomplete: N prior conversation turns
exist plus 1 final user query that the agent should respond to. This
is detected by checking whether the very last event across all turns
is authored by ``"user"``.
Returns ``False`` for completed traces (last event from the agent),
empty traces, or invalid data.
"""
if isinstance(agent_data, dict):
try:
agent_data = types.evals.AgentData.model_validate(agent_data)
except Exception: # pylint: disable=broad-exception-caught
return False
if not isinstance(agent_data, types.evals.AgentData):
return False
if not agent_data.turns:
return False
all_events: list[types.evals.AgentEvent] = []
for turn in agent_data.turns or []:
if turn.events:
all_events.extend(turn.events)
if not all_events:
return False
return all_events[-1].author == USER_AUTHOR
def _extract_response_from_completed_trace(
agent_data: types.evals.AgentData,
) -> list[dict[str, Any]]:
"""Extracts all events from a completed agent trace as event dicts.
For BYOD (bring-your-own-data) use cases where the agent trace is
already complete, this returns all events formatted as a list of
dicts compatible with ``_process_single_turn_agent_response``. The
last element is the final agent response; preceding elements become
intermediate events.
"""
event_dicts: list[dict[str, Any]] = []
for turn in agent_data.turns or []:
if not turn.events:
continue
for event in turn.events:
d: dict[str, Any] = {"author": event.author or "agent"}
if event.content:
d[CONTENT] = event.content.model_dump(exclude_none=True)
event_dicts.append(d)
return event_dicts
def _resolve_dataset(
api_client: BaseApiClient,
dataset: Union[types.EvaluationRunDataSource, types.EvaluationDataset],
dest: str,
parsed_agent_info: Optional[types.evals.AgentInfo] = None,
) -> types.EvaluationRunDataSource:
"""Resolves dataset for the evaluation run."""
if isinstance(dataset, types.EvaluationDataset):
# Resolve EvalCases with interactions_data_source by fetching
# each interaction and converting it to agent_data, then flowing
# through the normal DataFrame/GCS pipeline.
if dataset.eval_cases and _has_interactions_data_source(dataset.eval_cases):
resolved_cases = _resolve_interactions_to_eval_cases(
api_client, dataset.eval_cases
)
dataset = types.EvaluationDataset(eval_cases=resolved_cases)
candidate_name = _get_candidate_name(dataset, parsed_agent_info)
eval_df = dataset.eval_dataset_df
if eval_df is None and dataset.eval_cases:
eval_df = _eval_cases_to_dataframe(dataset.eval_cases)
eval_set = _create_evaluation_set_from_dataframe(
api_client,
dest,
eval_df,
candidate_name,
parsed_agent_info=parsed_agent_info,
)
dataset = types.EvaluationRunDataSource(evaluation_set=eval_set.name)
return dataset
def _get_default_prompt_template(
api_client: BaseApiClient,
inference_config: types.EvaluationRunInferenceConfigOrDict,
dataset: types.EvaluationRunDataSource,
) -> Any:
"""Resolves prompt template data for the evaluation run."""
if isinstance(inference_config, dict):
if inference_config.get("prompt_template"):
return inference_config["prompt_template"]
elif inference_config.prompt_template:
return inference_config.prompt_template
try:
evals_module = evals.Evals(api_client_=api_client)
eval_set = evals_module.get_evaluation_set(name=dataset.evaluation_set)
if eval_set and eval_set.evaluation_items:
eval_item = evals_module.get_evaluation_item(
name=eval_set.evaluation_items[0]
)
if (
eval_item
and eval_item.evaluation_request
and eval_item.evaluation_request.prompt
and eval_item.evaluation_request.prompt.prompt_template_data
and eval_item.evaluation_request.prompt.prompt_template_data.values
):
template_values = (
eval_item.evaluation_request.prompt.prompt_template_data.values
)
if template_values and "prompt" in template_values:
return "{prompt}"
except Exception as e:
logger.warning("Failed to get prompt template from evaluation set: %s", e)
return None
def _resolve_inference_configs(
api_client: BaseApiClient,
dataset: types.EvaluationRunDataSource,
inference_configs: Optional[
dict[str, types.EvaluationRunInferenceConfigOrDict]
] = None,
parsed_agent_info: Optional[types.evals.AgentInfo] = None,
) -> Optional[dict[str, types.EvaluationRunInferenceConfigOrDict]]:
"""Resolves inference configs for the evaluation run."""
# Resolve agent config
if parsed_agent_info and parsed_agent_info.name:
if inference_configs is None:
inference_configs = {}
# We might have used "candidate-1" as a placeholder key in the caller,
# let's migrate it to the agent name, or if it doesn't exist, just create it.
if "candidate-1" in inference_configs:
inference_configs[parsed_agent_info.name] = inference_configs.pop(
"candidate-1"
)
if parsed_agent_info.name not in inference_configs:
inference_configs[parsed_agent_info.name] = (
types.EvaluationRunInferenceConfig(
agent_configs=parsed_agent_info.agents
)
)
else:
config = inference_configs[parsed_agent_info.name]
if isinstance(config, dict):
config["agent_configs"] = parsed_agent_info.agents
else:
config.agent_configs = parsed_agent_info.agents
if inference_configs:
for inference_config in inference_configs.values():
model_val = (
inference_config.get("model")
if isinstance(inference_config, dict)
else inference_config.model
)
if model_val:
normalized_model = _normalize_inference_model_name(
model_val, api_client
)
if isinstance(inference_config, dict):
inference_config["model"] = normalized_model
else:
inference_config.model = normalized_model
prompt_template_val = (
inference_config.get("prompt_template")
if isinstance(inference_config, dict)
else inference_config.prompt_template
)
if not prompt_template_val:
default_prompt_template = _get_default_prompt_template(
api_client, inference_config, dataset
)
if default_prompt_template:
prompt_template_to_set = default_prompt_template
if not isinstance(
default_prompt_template, types.EvaluationRunPromptTemplate
):
prompt_template_to_set = types.EvaluationRunPromptTemplate(
prompt_template=default_prompt_template
)
if isinstance(inference_config, dict):
inference_config["prompt_template"] = (
prompt_template_to_set.model_dump(exclude_none=True)
)
else:
inference_config.prompt_template = (
prompt_template_to_set.model_dump(exclude_none=True)
)
return inference_configs
def _is_gemini_agent_resource(agent: str) -> bool:
"""Returns True if `agent` is a Gemini Agent resource name.
A Gemini Agent resource name has the format
`projects/{project}/locations/{location}/agents/{agent}`, as opposed to an
Agent Engine resource name which uses `.../reasoningEngines/{id}`.
"""
parts = agent.split("/")
return (
len(parts) == 6
and parts[0] == "projects"
and parts[2] == "locations"
and parts[4] == "agents"
and bool(parts[1])
and bool(parts[3])
and bool(parts[5])
)
def _step_to_agent_event(step: Any) -> Optional[types.evals.AgentEvent]:
"""Converts a typed GenAI SDK Interaction step to an AgentEvent.
Uses ``isinstance`` checks against the GenAI SDK step classes so that
attribute access stays in sync with SDK/proto changes.
Args:
step: A step from ``Interaction.steps`` (a GenAI SDK step type).
Returns:
An AgentEvent, or ``None`` if the step type is not handled.
"""
if isinstance(step, userinputstep.UserInputStep):
return _text_step_to_event(step, author="user", role="user")
elif isinstance(step, modeloutputstep.ModelOutputStep):
return _text_step_to_event(step, author="agent", role="model")
elif isinstance(step, functioncallstep.FunctionCallStep):
return _function_call_step_to_event(step)
elif isinstance(step, functionresultstep.FunctionResultStep):
return _function_response_step_to_event(step)
else:
logger.info("Skipping unhandled interaction step type: %s", type(step).__name__)
return None
def _function_response_step_to_event(
step: functionresultstep.FunctionResultStep,
) -> types.evals.AgentEvent:
"""Converts a FunctionResultStep to an AgentEvent."""
result = step.result
if isinstance(result, dict):
result_str = json.dumps(result)
elif isinstance(result, str):
result_str = result
else:
result_str = str(result) if result is not None else ""
return types.evals.AgentEvent( # pytype: disable=missing-parameter
author="user",
content=genai_types.Content(
role="user",
parts=[
genai_types.Part(
function_response=genai_types.FunctionResponse(
name=step.name or "",
response={"result": result_str},
id=step.call_id or "",
)
)
],
),
)
def _function_call_step_to_event(
step: functioncallstep.FunctionCallStep,
) -> types.evals.AgentEvent:
"""Converts a FunctionCallStep to an AgentEvent."""
return types.evals.AgentEvent( # pytype: disable=missing-parameter
author="agent",
content=genai_types.Content(
role="model",
parts=[
genai_types.Part(
function_call=genai_types.FunctionCall(
name=step.name or "",
args=step.arguments or {},
id=step.id or "",
)
)
],
),
)
def _text_step_to_event(
step: Any, *, author: str, role: str
) -> Optional[types.evals.AgentEvent]:
"""Converts a text-bearing step (UserInputStep / ModelOutputStep) to an AgentEvent.
Args:
step: A GenAI SDK step with a ``content`` attribute.
author: The event author (``"user"`` or ``"agent"``).
role: The content role (``"user"`` or ``"model"``).
Returns:
An AgentEvent, or ``None`` if no text parts were found.
"""
parts = []
for content_item in step.content or []:
if getattr(content_item, "text", None):
parts.append(genai_types.Part(text=content_item.text))
if not parts:
return None
return types.evals.AgentEvent( # pytype: disable=missing-parameter
author=author,
content=genai_types.Content(role=role, parts=parts),
)
def _interaction_steps_to_events(
steps: list[Any],
) -> list[tuple[types.evals.AgentEvent, type]]:
"""Converts a list of typed Interaction steps to AgentEvents.
Each step is mapped via ``_step_to_agent_event``. Steps whose type is
not handled are skipped with a log message. The originating SDK step
class is returned alongside each event so callers can determine turn
boundaries without inspecting event content.
Args:
steps: The ``steps`` list from a GenAI SDK ``Interaction`` object.
Returns:
A list of ``(AgentEvent, step_class)`` tuples.
"""
events: list[tuple[types.evals.AgentEvent, type]] = []
for step in steps:
event = _step_to_agent_event(step)
if event is not None:
events.append((event, type(step)))
return events
def _interaction_dict_to_agent_data(
interaction: dict[str, Any],
) -> types.evals.AgentData:
"""Converts an Interaction API JSON response to an AgentData object.
Parses the raw dict into a typed ``Interaction`` object (from the GenAI
SDK) so that step conversion uses ``isinstance`` checks and typed
attribute access. Steps are grouped into ConversationTurns -- each
``UserInputStep`` starts a new turn, so multi-turn conversations
produce multiple turns.
Args:
interaction: A dict from the Interactions API GET response.
Returns:
An AgentData object with one or more ConversationTurns.
"""
typed_interaction = interaction_types.Interaction.model_validate(interaction)
all_events = _interaction_steps_to_events(typed_interaction.steps or [])
# Group events into turns. Each UserInputStep starts a new turn.
grouped: list[list[types.evals.AgentEvent]] = []
for event, step_type in all_events:
if not grouped or step_type is userinputstep.UserInputStep:
grouped.append([])
grouped[-1].append(event)
if not grouped:
return types.evals.AgentData( # pytype: disable=missing-parameter
turns=[
types.evals.ConversationTurn( # pytype: disable=missing-parameter
turn_index=0, events=[]
)
]
)
return types.evals.AgentData( # pytype: disable=missing-parameter
turns=[
types.evals.ConversationTurn( # pytype: disable=missing-parameter
turn_index=i, events=events
)
for i, events in enumerate(grouped)
]
)
def _merge_text_parts_in_agent_data(
agent_data: types.evals.AgentData,
) -> None:
"""Merges consecutive text events and parts for cleaner trace display.
The Interaction API may return multiple consecutive ``model_output``
steps (one per paragraph) and/or multiple text content items within a
single step. ``_interaction_dict_to_agent_data`` maps each step to a
separate event, and each content item to a separate ``part``, causing
the trace renderer to display them as separate visual blocks.
This function performs two merges:
1. **Event merge** -- consecutive events from the same author that
contain only text parts are collapsed into a single event.
2. **Part merge** -- within each (possibly merged) event, consecutive
text-only parts are collapsed into a single part.
Mutates ``agent_data`` in place.
Args:
agent_data: An AgentData object to merge in place.
"""
for turn in agent_data.turns or []:
events = turn.events
if not events:
continue
# --- Pass 1: merge consecutive text-only events from the same author ---
merged_events: list[types.evals.AgentEvent] = []
for event in events:
parts = (event.content.parts if event.content else None) or []
is_text_only = parts and all(
p.text is not None
and p.function_call is None
and p.function_response is None
for p in parts
)
if (
merged_events
and is_text_only
and event.author == merged_events[-1].author
):
prev_content = merged_events[-1].content
prev_parts = (prev_content.parts if prev_content else None) or []
prev_parts.extend(parts)
continue
merged_events.append(event)
turn.events = merged_events
# --- Pass 2: merge consecutive text parts within each event ---
for event in turn.events:
content = event.content
if not content:
continue
parts = content.parts
if not parts or len(parts) <= 1:
continue
merged_parts: list[genai_types.Part] = []
text_buffer: list[str] = []
for part in parts:
if (
part.text is not None
and part.function_call is None
and part.function_response is None
):
text_buffer.append(part.text)
else:
if text_buffer:
merged_parts.append(
genai_types.Part(text="\n".join(text_buffer))
)
text_buffer = []
merged_parts.append(part)
if text_buffer:
merged_parts.append(genai_types.Part(text="\n".join(text_buffer)))
content.parts = merged_parts
_agent_tools_to_config_tools = _evals_builtin_tools.agent_tools_to_config_tools
def _fetch_agent_config_dict(
api_client: BaseApiClient,
agent_resource_name: str,
) -> types.evals.AgentConfig:
"""Fetches an agent's config from the Agent API and returns an AgentConfig.
Fetches the Agent resource via ``GET agents/{id}`` and extracts the
system instruction, description, base agent type, and tools. Built-in
tool types (``code_execution``, ``filesystem``, etc.) are expanded into
concrete ``FunctionDeclaration`` names and descriptions via the
display-only catalog in ``_evals_builtin_tools``.
Args:
api_client: The API client used to fetch the agent.
agent_resource_name: Full resource name of the agent, e.g.
``projects/p/locations/l/agents/my-agent``.
Returns:
An AgentConfig with ``agent_id`` and, when available,
``instruction``, ``description``, ``agent_type``, and ``tools``.
"""
agent_short_id = agent_resource_name.split("/")[-1] or "agent"
instruction: Optional[str] = None
description: Optional[str] = None
agent_type: Optional[str] = None
tools: Optional[list[genai_types.Tool]] = None
try:
agent_resp = api_client.request("get", f"agents/{agent_short_id}", {}, None)
if agent_resp.body:
agent_dict = json.loads(agent_resp.body)
instruction = agent_dict.get("system_instruction") or None
description = agent_dict.get("description") or None
agent_type = agent_dict.get("base_agent") or None
has_environment = bool(
agent_dict.get("environment_config")
or agent_dict.get("base_environment")
)
tools = _agent_tools_to_config_tools(
agent_dict.get("tools"), has_environment=has_environment
)
except Exception as e: # pylint: disable=broad-exception-caught
logger.warning(
"Failed to fetch agent config for '%s' (continuing without it): %s",
agent_resource_name,
e,
)
return types.evals.AgentConfig( # pytype: disable=missing-parameter
agent_id=agent_short_id,
instruction=instruction,
description=description,
agent_type=agent_type,
tools=tools,
)
def _get_resolved_location(api_client: Any) -> Optional[str]:
"""Returns the location configured on the API client."""
return getattr(api_client, "location", None)
class _InteractionsRestClient:
"""Minimal Interactions API client issued through the SDK api_client.
Calls go through `api_client.request()` (rather than the google.genai
`_gaos` client) so that the `ReplayApiClient` records and replays them.
Requests and responses are plain dicts.
"""
def __init__(self, api_client: BaseApiClient):
self._api_client = api_client
def create(self, request_dict: dict[str, Any]) -> dict[str, Any]:
response = self._api_client.request(
"post",
"interactions",
request_dict,
http_options={"timeout": _INTERACTION_REQUEST_TIMEOUT_MS},
)
return json.loads(response.body) if response.body else {}
def get(self, interaction_id: str) -> dict[str, Any]:
response = self._api_client.request(
"get",
f"interactions/{interaction_id}",
{},
http_options={"timeout": _INTERACTION_REQUEST_TIMEOUT_MS},
)
return json.loads(response.body) if response.body else {}
def _get_interactions_client(api_client: BaseApiClient) -> _InteractionsRestClient:
"""Returns an Interactions API client bound to `api_client`.
The client issues calls through the SDK's existing `api_client` (a
`BaseApiClient`, or a `ReplayApiClient` in tests) so that replay recording
captures the interaction calls.
Args:
api_client: The API client used to issue interaction calls.
Returns:
An `_InteractionsRestClient`.
"""
return _InteractionsRestClient(api_client)
def _agent_data_response_text(agent_data: types.evals.AgentData) -> Optional[str]:
"""Concatenates the text of all model-role events in an AgentData."""
text_parts: list[str] = []
for turn in agent_data.turns or []:
for event in turn.events or []:
content = event.content
if not content or content.role != _evals_constant.MODEL_AUTHOR:
continue
for part in content.parts or []:
if part.text:
text_parts.append(part.text)
return "".join(text_parts) or None