assassinlike commited on
Commit
0dc3c34
·
verified ·
1 Parent(s): cd470b7

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/__pycache__/__init__.cpython-311.pyc +0 -0
  2. data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/__init__.py +43 -0
  3. data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/__pycache__/__init__.cpython-311.pyc +0 -0
  4. data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/__pycache__/_agent_engines_utils.cpython-311.pyc +0 -0
  5. data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/__pycache__/_bigquery_utils.cpython-311.pyc +0 -0
  6. data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/__pycache__/_datasets_utils.cpython-311.pyc +0 -0
  7. data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/__pycache__/_evals_constant.cpython-311.pyc +0 -0
  8. data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/__pycache__/_evals_data_converters.cpython-311.pyc +0 -0
  9. data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/__pycache__/_evals_metric_handlers.cpython-311.pyc +0 -0
  10. data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/__pycache__/_evals_metric_loaders.cpython-311.pyc +0 -0
  11. data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/__pycache__/_evals_utils.cpython-311.pyc +0 -0
  12. data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/__pycache__/_gcs_utils.cpython-311.pyc +0 -0
  13. data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/__pycache__/_logging_utils.cpython-311.pyc +0 -0
  14. data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/__pycache__/_observability_data_converter.cpython-311.pyc +0 -0
  15. data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/__pycache__/_prompt_management_utils.cpython-311.pyc +0 -0
  16. data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/__pycache__/_prompt_optimizer_utils.cpython-311.pyc +0 -0
  17. data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/__pycache__/_skills_utils.cpython-311.pyc +0 -0
  18. data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/__pycache__/_transformers.cpython-311.pyc +0 -0
  19. data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/__pycache__/a2a_task_events.cpython-311.pyc +0 -0
  20. data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/__pycache__/a2a_tasks.cpython-311.pyc +0 -0
  21. data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/__pycache__/client.cpython-311.pyc +0 -0
  22. data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/__pycache__/datasets.cpython-311.pyc +0 -0
  23. data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/__pycache__/live.cpython-311.pyc +0 -0
  24. data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/__pycache__/live_agent_engines.cpython-311.pyc +0 -0
  25. data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/__pycache__/memory_revisions.cpython-311.pyc +0 -0
  26. data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/__pycache__/prompt_optimizer.cpython-311.pyc +0 -0
  27. data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/__pycache__/runtime_revisions.cpython-311.pyc +0 -0
  28. data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/__pycache__/runtimes.cpython-311.pyc +0 -0
  29. data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/__pycache__/sandbox_snapshots.cpython-311.pyc +0 -0
  30. data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/__pycache__/sandbox_templates.cpython-311.pyc +0 -0
  31. data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/__pycache__/sandboxes.cpython-311.pyc +0 -0
  32. data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/__pycache__/session_events.cpython-311.pyc +0 -0
  33. data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/__pycache__/sessions.cpython-311.pyc +0 -0
  34. data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/__pycache__/skill_revisions.cpython-311.pyc +0 -0
  35. data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/__pycache__/skills.cpython-311.pyc +0 -0
  36. data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/_agent_engines_utils.py +1996 -0
  37. data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/_bigquery_utils.py +49 -0
  38. data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/_datasets_utils.py +280 -0
  39. data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/_evals_common.py +0 -0
  40. data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/_evals_constant.py +78 -0
  41. data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/_evals_data_converters.py +918 -0
  42. data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/_evals_metric_handlers.py +1755 -0
  43. data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/_evals_metric_loaders.py +381 -0
  44. data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/_evals_utils.py +1043 -0
  45. data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/_evals_visualization.py +0 -0
  46. data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/_gcs_utils.py +192 -0
  47. data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/_logging_utils.py +47 -0
  48. data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/_observability_data_converter.py +186 -0
  49. data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/_prompt_management_utils.py +147 -0
  50. data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/_prompt_optimizer_utils.py +215 -0
data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/__pycache__/__init__.cpython-311.pyc ADDED
Binary file (1.46 kB). View file
 
data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/__init__.py ADDED
@@ -0,0 +1,43 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ """The agentplatform module."""
16
+
17
+ import importlib
18
+
19
+ from .client import Client
20
+
21
+ _evals = None
22
+
23
+
24
+ def __getattr__(name): # type: ignore[no-untyped-def]
25
+ if name == "evals":
26
+ global _evals
27
+ if _evals is None:
28
+ try:
29
+ _evals = importlib.import_module(".evals", __package__)
30
+ except ImportError as e:
31
+ raise ImportError(
32
+ "The 'evals' module requires additional dependencies. "
33
+ "Please install them using pip install "
34
+ "google-cloud-aiplatform[evaluation]"
35
+ ) from e
36
+ return _evals
37
+ raise AttributeError(f"module '{__name__}' has no attribute '{name}'")
38
+
39
+
40
+ __all__ = [
41
+ "Client",
42
+ "evals",
43
+ ]
data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/__pycache__/__init__.cpython-311.pyc ADDED
Binary file (1.15 kB). View file
 
data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/__pycache__/_agent_engines_utils.cpython-311.pyc ADDED
Binary file (88.3 kB). View file
 
data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/__pycache__/_bigquery_utils.cpython-311.pyc ADDED
Binary file (2.36 kB). View file
 
data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/__pycache__/_datasets_utils.cpython-311.pyc ADDED
Binary file (12.1 kB). View file
 
data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/__pycache__/_evals_constant.cpython-311.pyc ADDED
Binary file (1.55 kB). View file
 
data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/__pycache__/_evals_data_converters.cpython-311.pyc ADDED
Binary file (37.9 kB). View file
 
data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/__pycache__/_evals_metric_handlers.cpython-311.pyc ADDED
Binary file (74.7 kB). View file
 
data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/__pycache__/_evals_metric_loaders.cpython-311.pyc ADDED
Binary file (19.8 kB). View file
 
data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/__pycache__/_evals_utils.cpython-311.pyc ADDED
Binary file (46.1 kB). View file
 
data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/__pycache__/_gcs_utils.cpython-311.pyc ADDED
Binary file (9.4 kB). View file
 
data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/__pycache__/_logging_utils.cpython-311.pyc ADDED
Binary file (2.05 kB). View file
 
data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/__pycache__/_observability_data_converter.cpython-311.pyc ADDED
Binary file (8.22 kB). View file
 
data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/__pycache__/_prompt_management_utils.cpython-311.pyc ADDED
Binary file (5.32 kB). View file
 
data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/__pycache__/_prompt_optimizer_utils.cpython-311.pyc ADDED
Binary file (7.78 kB). View file
 
data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/__pycache__/_skills_utils.cpython-311.pyc ADDED
Binary file (6.48 kB). View file
 
data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/__pycache__/_transformers.cpython-311.pyc ADDED
Binary file (21.2 kB). View file
 
data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/__pycache__/a2a_task_events.cpython-311.pyc ADDED
Binary file (16.1 kB). View file
 
data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/__pycache__/a2a_tasks.cpython-311.pyc ADDED
Binary file (26.3 kB). View file
 
data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/__pycache__/client.cpython-311.pyc ADDED
Binary file (17 kB). View file
 
data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/__pycache__/datasets.cpython-311.pyc ADDED
Binary file (86.7 kB). View file
 
data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/__pycache__/live.cpython-311.pyc ADDED
Binary file (2.61 kB). View file
 
data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/__pycache__/live_agent_engines.cpython-311.pyc ADDED
Binary file (8.46 kB). View file
 
data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/__pycache__/memory_revisions.cpython-311.pyc ADDED
Binary file (15 kB). View file
 
data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/__pycache__/prompt_optimizer.cpython-311.pyc ADDED
Binary file (37 kB). View file
 
data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/__pycache__/runtime_revisions.cpython-311.pyc ADDED
Binary file (39.8 kB). View file
 
data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/__pycache__/runtimes.cpython-311.pyc ADDED
Binary file (2.68 kB). View file
 
data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/__pycache__/sandbox_snapshots.cpython-311.pyc ADDED
Binary file (32.1 kB). View file
 
data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/__pycache__/sandbox_templates.cpython-311.pyc ADDED
Binary file (33.9 kB). View file
 
data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/__pycache__/sandboxes.cpython-311.pyc ADDED
Binary file (50.4 kB). View file
 
data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/__pycache__/session_events.cpython-311.pyc ADDED
Binary file (18.3 kB). View file
 
data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/__pycache__/sessions.cpython-311.pyc ADDED
Binary file (42.4 kB). View file
 
data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/__pycache__/skill_revisions.cpython-311.pyc ADDED
Binary file (11.8 kB). View file
 
data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/__pycache__/skills.cpython-311.pyc ADDED
Binary file (54.8 kB). View file
 
data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/_agent_engines_utils.py ADDED
@@ -0,0 +1,1996 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2025 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
+ """Utility functions for agent engines."""
16
+
17
+ import abc
18
+ import asyncio
19
+ import base64
20
+ from importlib import metadata as importlib_metadata
21
+ import inspect
22
+ import io
23
+ import json
24
+ import logging
25
+ import os
26
+ import re
27
+ import sys
28
+ import tarfile
29
+ import time
30
+ import types
31
+ import typing
32
+ from typing import (
33
+ Any,
34
+ AsyncIterator,
35
+ Callable,
36
+ Coroutine,
37
+ Dict,
38
+ Iterator,
39
+ List,
40
+ Mapping,
41
+ Optional,
42
+ Protocol,
43
+ Sequence,
44
+ Set,
45
+ TypedDict,
46
+ Union,
47
+ )
48
+
49
+ import httpx
50
+
51
+ import proto
52
+
53
+ from google.api_core import exceptions
54
+ from google.genai import types as google_genai_types
55
+ from google.protobuf import struct_pb2
56
+ from google.protobuf import json_format
57
+
58
+ from . import types as genai_types
59
+
60
+
61
+ if sys.version_info >= (3, 10):
62
+ from typing import TypeAlias
63
+ else:
64
+ from typing_extensions import TypeAlias
65
+
66
+
67
+ try:
68
+ _BUILTIN_MODULE_NAMES: Sequence[str] = sys.builtin_module_names
69
+ except AttributeError:
70
+ _BUILTIN_MODULE_NAMES: Sequence[str] = [] # type: ignore[no-redef]
71
+
72
+ try:
73
+ _PACKAGE_DISTRIBUTIONS: Mapping[str, Sequence[str]] = (
74
+ importlib_metadata.packages_distributions()
75
+ )
76
+ except AttributeError:
77
+ _PACKAGE_DISTRIBUTIONS: Mapping[str, Sequence[str]] = {} # type: ignore[no-redef]
78
+
79
+ try:
80
+ # sys.stdlib_module_names is available from Python 3.10 onwards.
81
+ _STDLIB_MODULE_NAMES: frozenset[str] = sys.stdlib_module_names
82
+ except AttributeError:
83
+ _STDLIB_MODULE_NAMES: frozenset[str] = frozenset() # type: ignore[no-redef]
84
+
85
+
86
+ if typing.TYPE_CHECKING:
87
+ from google.cloud import storage # type: ignore[attr-defined]
88
+
89
+ _StorageBucket: TypeAlias = storage.Bucket
90
+ else:
91
+ try:
92
+ from google.cloud import storage # type: ignore[attr-defined]
93
+
94
+ _StorageBucket: type[Any] = storage.Bucket
95
+ except (ImportError, AttributeError):
96
+ _StorageBucket: type[Any] = Any # type: ignore[no-redef]
97
+
98
+
99
+ if typing.TYPE_CHECKING:
100
+ import packaging
101
+
102
+ _SpecifierSet = packaging.specifiers.SpecifierSet
103
+ else:
104
+ try:
105
+ import packaging
106
+
107
+ _SpecifierSet: type[Any] = packaging.specifiers.SpecifierSet
108
+ except (ImportError, AttributeError):
109
+ _SpecifierSet: type[Any] = Any # type: ignore[no-redef]
110
+
111
+
112
+ try:
113
+ from a2a.types import (
114
+ AgentCard,
115
+ TransportProtocol,
116
+ Message,
117
+ TaskIdParams,
118
+ TaskQueryParams,
119
+ )
120
+ from a2a.client import ClientConfig, ClientFactory
121
+
122
+ AgentCard = AgentCard
123
+ TransportProtocol = TransportProtocol
124
+ Message = Message
125
+ ClientConfig = ClientConfig
126
+ ClientFactory = ClientFactory
127
+ TaskIdParams = TaskIdParams
128
+ TaskQueryParams = TaskQueryParams
129
+ except (ImportError, AttributeError):
130
+ AgentCard = None
131
+ TransportProtocol = None
132
+ Message = None
133
+ ClientConfig = None
134
+ ClientFactory = None
135
+ TaskIdParams = None
136
+ TaskQueryParams = None
137
+
138
+ _ACTIONS_KEY = "actions"
139
+ _ACTION_APPEND = "append"
140
+ _AGENT_FRAMEWORK_ATTR = "agent_framework"
141
+ _ASYNC_API_MODE = "async"
142
+ _ASYNC_STREAM_API_MODE = "async_stream"
143
+ _BIDI_STREAM_API_MODE = "bidi_stream"
144
+ _BASE_MODULES = set(_BUILTIN_MODULE_NAMES).union(_STDLIB_MODULE_NAMES)
145
+ _BLOB_FILENAME = "agent_engine.pkl"
146
+ _DEFAULT_AGENT_FRAMEWORK = "custom"
147
+ _SUPPORTED_AGENT_FRAMEWORKS = frozenset(
148
+ [
149
+ "google-adk",
150
+ "langchain",
151
+ "langgraph",
152
+ "ag2",
153
+ "llama-index",
154
+ "custom",
155
+ "a2a",
156
+ ]
157
+ )
158
+ _DEFAULT_ASYNC_METHOD_NAME = "async_query"
159
+ _DEFAULT_ASYNC_METHOD_RETURN_TYPE = "Coroutine[Any]"
160
+ _DEFAULT_ASYNC_STREAM_METHOD_NAME = "async_stream_query"
161
+ _DEFAULT_ASYNC_STREAM_METHOD_RETURN_TYPE = "AsyncIterable[Any]"
162
+ _DEFAULT_GCS_DIR_NAME = "agent_engine"
163
+ _DEFAULT_METHOD_DOCSTRING_TEMPLATE = """
164
+ Runs the Agent Engine to serve the user request.
165
+ This will be based on the `.{method_name}(...)` of the python object that
166
+ was passed in when creating the Agent Engine. The method will invoke the
167
+ `{default_method_name}` API client of the python object.
168
+ Args:
169
+ **kwargs:
170
+ Optional. The arguments of the `.{method_name}(...)` method.
171
+ Returns:
172
+ {return_type}: The response from serving the user request.
173
+ """
174
+ _DEFAULT_METHOD_NAME = "query"
175
+ _DEFAULT_METHOD_RETURN_TYPE = "dict[str, Any]"
176
+ _DEFAULT_STREAM_METHOD_RETURN_TYPE = "Iterable[Any]"
177
+ _DEFAULT_REQUIRED_PACKAGES = frozenset(["cloudpickle", "pydantic"])
178
+ _DEFAULT_STREAM_METHOD_NAME = "stream_query"
179
+ _DEFAULT_BIDI_STREAM_METHOD_NAME = "bidi_stream_query"
180
+ _EXTRA_PACKAGES_FILE = "dependencies.tar.gz"
181
+ _FAILED_TO_REGISTER_API_METHODS_WARNING_TEMPLATE = (
182
+ "Failed to register API methods. Please follow the guide to "
183
+ "register the API methods: "
184
+ "https://cloud.google.com/vertex-ai/generative-ai/docs/agent-engine/develop/custom#custom-methods. "
185
+ "Error: {%s}"
186
+ )
187
+ _INSTALLATION_SUBDIR = "installation_scripts"
188
+ _METHOD_NAME_KEY_IN_SCHEMA = "name"
189
+ _MODE_KEY_IN_SCHEMA = "api_mode"
190
+ _REQUIREMENTS_FILE = "requirements.txt"
191
+ _STANDARD_API_MODE = ""
192
+ _STREAM_API_MODE = "stream"
193
+ _A2A_EXTENSION_MODE = "a2a_extension"
194
+ _A2A_AGENT_CARD = "a2a_agent_card"
195
+ _WARNINGS_KEY = "warnings"
196
+ _WARNING_MISSING = "missing"
197
+ _WARNING_INCOMPATIBLE = "incompatible"
198
+
199
+ _DEFAULT_METHOD_NAME_MAP = {
200
+ _STANDARD_API_MODE: _DEFAULT_METHOD_NAME,
201
+ _ASYNC_API_MODE: _DEFAULT_ASYNC_METHOD_NAME,
202
+ _STREAM_API_MODE: _DEFAULT_STREAM_METHOD_NAME,
203
+ _ASYNC_STREAM_API_MODE: _DEFAULT_ASYNC_STREAM_METHOD_NAME,
204
+ }
205
+ _DEFAULT_METHOD_RETURN_TYPE_MAP = {
206
+ _STANDARD_API_MODE: _DEFAULT_METHOD_RETURN_TYPE,
207
+ _ASYNC_API_MODE: _DEFAULT_ASYNC_METHOD_RETURN_TYPE,
208
+ _STREAM_API_MODE: _DEFAULT_STREAM_METHOD_RETURN_TYPE,
209
+ _ASYNC_STREAM_API_MODE: _DEFAULT_ASYNC_STREAM_METHOD_RETURN_TYPE,
210
+ }
211
+
212
+
213
+ logger = logging.getLogger("agentplatform_genai.agentengines")
214
+
215
+
216
+ @typing.runtime_checkable
217
+ class Queryable(Protocol):
218
+ """Protocol for Agent Engines that can be queried."""
219
+
220
+ @abc.abstractmethod
221
+ def query(self, **kwargs): # type: ignore[no-untyped-def]
222
+ """Runs the Agent Engine to serve the user query."""
223
+
224
+
225
+ @typing.runtime_checkable
226
+ class AsyncQueryable(Protocol):
227
+ """Protocol for Agent Engines that can be queried asynchronously."""
228
+
229
+ @abc.abstractmethod
230
+ def async_query(self, **kwargs): # type: ignore[no-untyped-def]
231
+ """Runs the Agent Engine to serve the user query asynchronously."""
232
+
233
+
234
+ @typing.runtime_checkable
235
+ class AsyncStreamQueryable(Protocol):
236
+ """Protocol for Agent Engines that can stream responses asynchronously."""
237
+
238
+ @abc.abstractmethod
239
+ async def async_stream_query(self, **kwargs) -> AsyncIterator[Any]: # type: ignore[no-untyped-def]
240
+ """Asynchronously stream responses to serve the user query."""
241
+
242
+
243
+ @typing.runtime_checkable
244
+ class StreamQueryable(Protocol):
245
+ """Protocol for Agent Engines that can stream responses."""
246
+
247
+ @abc.abstractmethod
248
+ def stream_query(self, **kwargs) -> Iterator[Any]: # type: ignore[no-untyped-def]
249
+ """Stream responses to serve the user query."""
250
+
251
+
252
+ @typing.runtime_checkable
253
+ class BidiStreamQueryable(Protocol):
254
+ """Protocol for Agent Engines that can stream requests and responses."""
255
+
256
+ @abc.abstractmethod
257
+ async def bidi_stream_query(
258
+ self, input_queue: asyncio.Queue[Any]
259
+ ) -> AsyncIterator[Any]:
260
+ """Stream requests and responses to serve the user queries."""
261
+
262
+
263
+ @typing.runtime_checkable
264
+ class Cloneable(Protocol):
265
+ """Protocol for Agent Engines that can be cloned."""
266
+
267
+ @abc.abstractmethod
268
+ def clone(self) -> Any:
269
+ """Return a clone of the object."""
270
+
271
+
272
+ @typing.runtime_checkable
273
+ class OperationRegistrable(Protocol):
274
+ """Protocol for agents that have registered operations."""
275
+
276
+ @abc.abstractmethod
277
+ def register_operations(self, **kwargs: Any) -> dict[str, list[str]]:
278
+ """Register the user provided operations (modes and methods)."""
279
+ pass
280
+
281
+
282
+ if typing.TYPE_CHECKING:
283
+ from google.adk.agents import BaseAgent
284
+
285
+ ADKAgent: TypeAlias = BaseAgent
286
+ else:
287
+ try:
288
+ from google.adk.agents import BaseAgent
289
+
290
+ ADKAgent: Optional[TypeAlias] = BaseAgent
291
+ except (ImportError, AttributeError):
292
+ ADKAgent = None # type: ignore[no-redef]
293
+
294
+ _AgentEngineInterface = Union[
295
+ ADKAgent,
296
+ AsyncQueryable,
297
+ AsyncStreamQueryable,
298
+ OperationRegistrable,
299
+ Queryable,
300
+ StreamQueryable,
301
+ BidiStreamQueryable,
302
+ ]
303
+
304
+
305
+ class _ModuleAgentAttributes(TypedDict, total=False):
306
+ module_name: str
307
+ agent_name: str
308
+ register_operations: Dict[str, list[str]]
309
+ sys_paths: Optional[Sequence[str]]
310
+ agent: _AgentEngineInterface
311
+
312
+
313
+ class ModuleAgent(Cloneable, OperationRegistrable):
314
+ """Agent that is defined by a module and an agent name.
315
+
316
+ This agent is instantiated by importing a module and instantiating an agent
317
+ from that module. It also allows to register operations that are defined in
318
+ the agent.
319
+ """
320
+
321
+ def __init__(
322
+ self,
323
+ *,
324
+ module_name: str,
325
+ agent_name: str,
326
+ register_operations: Dict[str, list[str]],
327
+ sys_paths: Optional[Sequence[str]] = None,
328
+ ):
329
+ """Initializes a module-based agent.
330
+
331
+ Args:
332
+ module_name (str):
333
+ Required. The name of the module to import.
334
+ agent_name (str):
335
+ Required. The name of the agent in the module to instantiate.
336
+ register_operations (Dict[str, list[str]]):
337
+ Required. A dictionary of API modes to a list of method names.
338
+ sys_paths (Sequence[str]):
339
+ Optional. The system paths to search for the module. It should
340
+ be relative to the directory where the code will be running.
341
+ I.e. it should correspond to the directory being passed to
342
+ `extra_packages=...` in the create method. It will be appended
343
+ to the system path in the sequence being specified here, and
344
+ only be appended if it is not already in the system path.
345
+ """
346
+ self._tmpl_attrs: _ModuleAgentAttributes = {
347
+ "module_name": module_name,
348
+ "agent_name": agent_name,
349
+ "register_operations": register_operations,
350
+ "sys_paths": sys_paths,
351
+ }
352
+
353
+ def clone(self) -> "ModuleAgent":
354
+ """Return a clone of the agent."""
355
+ return ModuleAgent(
356
+ module_name=self._tmpl_attrs.get("module_name"),
357
+ agent_name=self._tmpl_attrs.get("agent_name"),
358
+ register_operations=self._tmpl_attrs.get("register_operations"),
359
+ sys_paths=self._tmpl_attrs.get("sys_paths"),
360
+ )
361
+
362
+ def register_operations(self, **kwargs: Any) -> dict[str, list[str]]:
363
+ reg_operations = self._tmpl_attrs.get("register_operations")
364
+ if reg_operations is None:
365
+ raise ValueError("Register operations is not set.")
366
+ return reg_operations
367
+
368
+ def set_up(self) -> None:
369
+ """Sets up the agent for execution of queries at runtime.
370
+
371
+ It runs the code to import the agent from the module, and registers the
372
+ operations of the agent.
373
+ """
374
+ sys_paths = self._tmpl_attrs.get("sys_paths")
375
+ if isinstance(sys_paths, Sequence):
376
+ import sys
377
+
378
+ for sys_path in sys_paths:
379
+ abs_path = os.path.abspath(sys_path)
380
+ if abs_path not in sys.path:
381
+ sys.path.append(abs_path)
382
+
383
+ import importlib
384
+
385
+ module = importlib.import_module(self._tmpl_attrs.get("module_name"))
386
+ try:
387
+ importlib.reload(module)
388
+ except Exception as e:
389
+ logger.warning(
390
+ f"Failed to reload module {self._tmpl_attrs.get('module_name')}: {e}"
391
+ )
392
+ agent_name = self._tmpl_attrs.get("agent_name")
393
+ try:
394
+ agent = getattr(module, agent_name)
395
+ except AttributeError as e:
396
+ raise AttributeError(
397
+ f"Agent {agent_name} not found in module "
398
+ f"{self._tmpl_attrs.get('module_name')}"
399
+ ) from e
400
+ self._tmpl_attrs["agent"] = agent
401
+ if hasattr(agent, "set_up"):
402
+ agent.set_up()
403
+ for operations in self.register_operations().values():
404
+ for operation in operations:
405
+ op = _wrap_agent_operation(agent=agent, operation=operation)
406
+ setattr(self, operation, types.MethodType(op, self))
407
+
408
+
409
+ class _RequirementsValidationActions(TypedDict):
410
+ append: Set[str]
411
+
412
+
413
+ class _RequirementsValidationWarnings(TypedDict):
414
+ missing: Set[str]
415
+ incompatible: Set[str]
416
+
417
+
418
+ class _RequirementsValidationResult(TypedDict):
419
+ warnings: _RequirementsValidationWarnings
420
+ actions: _RequirementsValidationActions
421
+
422
+
423
+ AgentEngineOperationUnion = Union[
424
+ genai_types.AgentEngineOperation,
425
+ genai_types.AgentEngineMemoryOperation,
426
+ genai_types.AgentEngineGenerateMemoriesOperation,
427
+ ]
428
+
429
+
430
+ class GetOperationFunction(Protocol):
431
+ def __call__(
432
+ self, *, operation_name: str, **kwargs: Any
433
+ ) -> AgentEngineOperationUnion:
434
+ pass
435
+
436
+
437
+ class GetAsyncOperationFunction(Protocol):
438
+ async def __call__(
439
+ self, *, operation_name: str, **kwargs: Any
440
+ ) -> AgentEngineOperationUnion:
441
+ pass
442
+
443
+
444
+ def _get_reasoning_engine_id(operation_name: str = "", resource_name: str = "") -> str:
445
+ """Returns reasoning engine ID from operation name or resource name."""
446
+ if not resource_name and not operation_name:
447
+ raise ValueError("Resource name or operation name cannot be empty.")
448
+
449
+ if resource_name:
450
+ match = re.match(
451
+ r"^projects/[^/]+/locations/[^/]+/reasoningEngines/([^/]+)$",
452
+ resource_name,
453
+ )
454
+ if match:
455
+ return match.group(1)
456
+ else:
457
+ raise ValueError(
458
+ "Failed to parse reasoning engine ID from resource name: "
459
+ f"`{resource_name}`"
460
+ )
461
+
462
+ if not operation_name:
463
+ raise ValueError("Operation name cannot be empty.")
464
+
465
+ match = re.match(
466
+ r"^projects/[^/]+/locations/[^/]+/reasoningEngines/([^/]+)/operations/[^/]+$",
467
+ operation_name,
468
+ )
469
+ if match:
470
+ return match.group(1)
471
+ raise ValueError(
472
+ "Failed to parse reasoning engine ID from operation name: "
473
+ f"`{operation_name}`"
474
+ )
475
+
476
+
477
+ async def _await_async_operation(
478
+ *,
479
+ operation_name: str,
480
+ get_operation_fn: GetAsyncOperationFunction,
481
+ poll_interval_seconds: float = 10,
482
+ ) -> Any:
483
+ """Waits for the operation for creating an agent engine to complete.
484
+
485
+ Args:
486
+ operation_name (str):
487
+ Required. The name of the operation for creating the Agent Engine.
488
+ poll_interval_seconds (float):
489
+ The number of seconds to wait between each poll.
490
+ get_operation_fn (Callable[[str], Awaitable[Any]]):
491
+ Optional. The async function to use for getting the operation. If not
492
+ provided, `self._get_agent_operation` will be used.
493
+
494
+ Returns:
495
+ The operation that has completed (i.e. `operation.done==True`).
496
+ """
497
+ operation = await get_operation_fn(operation_name=operation_name)
498
+ while not operation.done:
499
+ await asyncio.sleep(poll_interval_seconds)
500
+ operation = await get_operation_fn(operation_name=operation.name)
501
+
502
+ return operation
503
+
504
+
505
+ def _await_operation(
506
+ *,
507
+ operation_name: str,
508
+ get_operation_fn: GetOperationFunction,
509
+ poll_interval_seconds: float = 10,
510
+ ) -> Any:
511
+ """Waits for the operation for creating an agent engine to complete.
512
+
513
+ Args:
514
+ operation_name (str):
515
+ Required. The name of the operation for creating the Agent Engine.
516
+ poll_interval_seconds (float):
517
+ The number of seconds to wait between each poll.
518
+ get_operation_fn (Callable[[str], Any]):
519
+ Optional. The function to use for getting the operation. If not
520
+ provided, `self._get_agent_operation` will be used.
521
+
522
+ Returns:
523
+ The operation that has completed (i.e. `operation.done==True`).
524
+ """
525
+ operation = get_operation_fn(operation_name=operation_name)
526
+ while not operation.done:
527
+ time.sleep(poll_interval_seconds)
528
+ operation = get_operation_fn(operation_name=operation.name)
529
+
530
+ return operation
531
+
532
+
533
+ def _compare_requirements(
534
+ *,
535
+ requirements: Mapping[str, str],
536
+ constraints: Union[Sequence[str], Mapping[str, Optional["_SpecifierSet"]]],
537
+ required_packages: Optional[Iterator[str]] = None,
538
+ ) -> _RequirementsValidationResult:
539
+ """Compares the requirements with the constraints.
540
+
541
+ Args:
542
+ requirements (Mapping[str, str]):
543
+ Required. The packages (and their versions) to compare with the constraints.
544
+ This is assumed to be the result of `scan_requirements`.
545
+ constraints (Union[Sequence[str], Mapping[str, SpecifierSet]]):
546
+ Required. The package constraints to compare against. This is assumed
547
+ to be the result of `parse_constraints`.
548
+ required_packages (Iterator[str]):
549
+ Optional. The set of packages that are required to be in the
550
+ constraints. It defaults to the set of packages that are required
551
+ for deployment on Agent Engine.
552
+
553
+ Returns:
554
+ dict[str, dict[str, Any]]: The comparison result as a dictionary containing:
555
+ * warnings:
556
+ * missing: The set of packages that are not in the constraints.
557
+ * incompatible: The set of packages that are in the constraints
558
+ but have versions that are not in the constraint specifier.
559
+ * actions:
560
+ * append: The set of packages that are not in the constraints
561
+ but should be appended to the constraints.
562
+ """
563
+ packaging_version = _import_packaging_version_or_raise()
564
+ if required_packages is None:
565
+ required_packages = _DEFAULT_REQUIRED_PACKAGES # type: ignore[assignment]
566
+ result = _RequirementsValidationResult(
567
+ warnings=_RequirementsValidationWarnings(missing=set(), incompatible=set()),
568
+ actions=_RequirementsValidationActions(append=set()),
569
+ )
570
+ if isinstance(constraints, list):
571
+ constraints = _parse_constraints(constraints=constraints)
572
+ for package, package_version in requirements.items():
573
+ if package not in constraints:
574
+ result[_WARNINGS_KEY][_WARNING_MISSING].add(package) # type: ignore[literal-required]
575
+ if package in required_packages: # type: ignore[operator]
576
+ result[_ACTIONS_KEY][_ACTION_APPEND].add( # type: ignore[literal-required]
577
+ f"{package}=={package_version}"
578
+ )
579
+ continue
580
+ if package_version:
581
+ package_specifier = constraints[package] # type: ignore[call-overload]
582
+ if not package_specifier:
583
+ continue
584
+ if packaging_version.Version(package_version) not in package_specifier:
585
+ result[_WARNINGS_KEY][_WARNING_INCOMPATIBLE].add( # type: ignore[literal-required]
586
+ f"{package}=={package_version} (required: {str(package_specifier)})"
587
+ )
588
+ return result
589
+
590
+
591
+ def _generate_class_methods_spec_or_raise(
592
+ *,
593
+ agent: _AgentEngineInterface,
594
+ operations: Dict[str, List[str]],
595
+ ) -> List[proto.Message]:
596
+ """Generates a ReasoningEngineSpec based on the registered operations.
597
+
598
+ Args:
599
+ agent: The AgentEngine instance.
600
+ operations: A dictionary of API modes and method names.
601
+
602
+ Returns:
603
+ A list of ReasoningEngineSpec.ClassMethod messages.
604
+
605
+ Raises:
606
+ ValueError: If a method defined in `register_operations` is not found on
607
+ the AgentEngine.
608
+ """
609
+ if isinstance(agent, ModuleAgent):
610
+ # We do a dry-run of setting up the agent engine to have the operations
611
+ # needed for registration.
612
+ agent: ModuleAgent = agent.clone() # type: ignore[no-redef]
613
+ try:
614
+ agent.set_up()
615
+ except Exception as e:
616
+ raise ValueError(f"Failed to set up agent {agent}: {e}") from e
617
+ class_methods_spec = []
618
+ for mode, method_names in operations.items():
619
+ for method_name in method_names:
620
+ if not hasattr(agent, method_name):
621
+ raise ValueError(
622
+ f"Method `{method_name}` defined in `register_operations`"
623
+ " not found on agent."
624
+ )
625
+
626
+ method = getattr(agent, method_name)
627
+ try:
628
+ schema_dict = _generate_schema(method, schema_name=method_name)
629
+ except Exception as e:
630
+ logger.warning(f"failed to generate schema for {method_name}: {e}")
631
+ continue
632
+
633
+ class_method = _to_proto(schema_dict)
634
+ class_method[_MODE_KEY_IN_SCHEMA] = mode
635
+ if hasattr(agent, "agent_card"):
636
+ class_method[_A2A_AGENT_CARD] = json_format.MessageToJson(
637
+ getattr(agent, "agent_card")
638
+ )
639
+ class_methods_spec.append(class_method)
640
+
641
+ return class_methods_spec
642
+
643
+
644
+ def _class_methods_to_class_methods_spec(
645
+ class_methods: List[dict[str, Any]],
646
+ ) -> List[proto.Message]:
647
+ """Converts a list of class methods to a list of ReasoningEngineSpec.ClassMethod messages."""
648
+ return [_to_proto(class_method) for class_method in class_methods]
649
+
650
+
651
+ def _is_pydantic_serializable(param: inspect.Parameter) -> bool:
652
+ """Checks if the parameter is pydantic serializable."""
653
+
654
+ if param.annotation == inspect.Parameter.empty:
655
+ return True
656
+
657
+ if "ForwardRef" in repr(param.annotation):
658
+ return True
659
+
660
+ if isinstance(param.annotation, str):
661
+ return False
662
+
663
+ pydantic = _import_pydantic_or_raise()
664
+ try:
665
+ pydantic.TypeAdapter(param.annotation)
666
+ return True
667
+ except Exception:
668
+ return False
669
+
670
+
671
+ def _generate_schema(
672
+ f: Callable[..., Any],
673
+ *,
674
+ schema_name: Optional[str] = None,
675
+ descriptions: Mapping[str, str] = {},
676
+ required: Sequence[str] = [],
677
+ ) -> Dict[str, Any]:
678
+ """Generates the OpenAPI Schema for a callable object.
679
+
680
+ Only positional and keyword arguments of the function `f` will be supported
681
+ in the OpenAPI Schema that is generated. I.e. `*args` and `**kwargs` will
682
+ not be present in the OpenAPI schema returned from this function. For those
683
+ cases, you can either include it in the docstring for `f`, or modify the
684
+ OpenAPI schema returned from this function to include additional arguments.
685
+
686
+ Args:
687
+ f (Callable):
688
+ Required. The function to generate an OpenAPI Schema for.
689
+ schema_name (str):
690
+ Optional. The name for the OpenAPI schema. If unspecified, the name
691
+ of the Callable will be used.
692
+ descriptions (Mapping[str, str]):
693
+ Optional. A `{name: description}` mapping for annotating input
694
+ arguments of the function with user-provided descriptions. It
695
+ defaults to an empty dictionary (i.e. there will not be any
696
+ description for any of the inputs).
697
+ required (Sequence[str]):
698
+ Optional. For the user to specify the set of required arguments in
699
+ function calls to `f`. If specified, it will be automatically
700
+ inferred from `f`.
701
+
702
+ Returns:
703
+ dict[str, Any]: The OpenAPI Schema for the function `f` in JSON format.
704
+ """
705
+ pydantic = _import_pydantic_or_raise()
706
+ defaults = dict(inspect.signature(f).parameters)
707
+ fields_dict = {
708
+ name: (
709
+ # 1. We infer the argument type here: use Any rather than None so
710
+ # it will not try to auto-infer the type based on the default value.
711
+ (
712
+ param.annotation
713
+ if param.annotation != inspect.Parameter.empty
714
+ and "ForwardRef" not in repr(param.annotation)
715
+ else Any
716
+ ),
717
+ pydantic.Field(
718
+ # 2. We do not support default values for now.
719
+ # default=(
720
+ # param.default if param.default != inspect.Parameter.empty
721
+ # else None
722
+ # ),
723
+ # 3. We support user-provided descriptions.
724
+ description=descriptions.get(name, None),
725
+ ),
726
+ )
727
+ for name, param in defaults.items()
728
+ # We do not support *args or **kwargs
729
+ if param.kind
730
+ in (
731
+ inspect.Parameter.POSITIONAL_OR_KEYWORD,
732
+ inspect.Parameter.KEYWORD_ONLY,
733
+ inspect.Parameter.POSITIONAL_ONLY,
734
+ )
735
+ # For a bidi endpoint, it requires an asyncio.Queue as the input, but
736
+ # it is not JSON serializable. We hence exclude it from the schema.
737
+ and param.annotation != asyncio.Queue and _is_pydantic_serializable(param)
738
+ }
739
+ parameters = pydantic.create_model(f.__name__, **fields_dict).schema()
740
+ # Postprocessing
741
+ # 4. Suppress unnecessary title generation:
742
+ # * https://github.com/pydantic/pydantic/issues/1051
743
+ # * http://cl/586221780
744
+ parameters.pop("title", "")
745
+ for name, function_arg in parameters.get("properties", {}).items():
746
+ function_arg.pop("title", "")
747
+ annotation = defaults[name].annotation
748
+ # 5. Nullable fields:
749
+ # * https://github.com/pydantic/pydantic/issues/1270
750
+ # * https://stackoverflow.com/a/58841311
751
+ # * https://github.com/pydantic/pydantic/discussions/4872
752
+ if typing.get_origin(annotation) is Union and type(None) in typing.get_args(
753
+ annotation
754
+ ):
755
+ # for "typing.Optional" arguments, function_arg might be a
756
+ # dictionary like
757
+ #
758
+ # {'anyOf': [{'type': 'integer'}, {'type': 'null'}]
759
+ for schema in function_arg.pop("anyOf", []):
760
+ schema_type = schema.get("type")
761
+ if schema_type and schema_type != "null":
762
+ function_arg["type"] = schema_type
763
+ break
764
+ function_arg["nullable"] = True
765
+ # 6. Annotate required fields.
766
+ if required:
767
+ # We use the user-provided "required" fields if specified.
768
+ parameters["required"] = required
769
+ else:
770
+ # Otherwise we infer it from the function signature.
771
+ parameters["required"] = [
772
+ k
773
+ for k in defaults
774
+ if (
775
+ defaults[k].default == inspect.Parameter.empty
776
+ and defaults[k].kind
777
+ in (
778
+ inspect.Parameter.POSITIONAL_OR_KEYWORD,
779
+ inspect.Parameter.KEYWORD_ONLY,
780
+ inspect.Parameter.POSITIONAL_ONLY,
781
+ )
782
+ )
783
+ ]
784
+ schema = dict(name=f.__name__, description=f.__doc__, parameters=parameters)
785
+ if schema_name:
786
+ schema["name"] = schema_name
787
+ return schema
788
+
789
+
790
+ def _get_agent_framework(
791
+ *,
792
+ agent_framework: Optional[str],
793
+ agent: _AgentEngineInterface,
794
+ ) -> Union[str, Any]:
795
+ """Gets the agent framework to use.
796
+
797
+ The agent framework is determined in the following order of priority:
798
+ 1. The `agent_framework` passed to this function.
799
+ 2. The `agent_framework` attribute on the `agent` object.
800
+ 3. The default framework, "custom".
801
+
802
+ Args:
803
+ agent_framework (str):
804
+ The agent framework provided by the user.
805
+ agent (_AgentEngineInterface):
806
+ The agent engine instance.
807
+
808
+ Returns:
809
+ str: The name of the agent framework to use.
810
+ """
811
+ if agent_framework is not None and agent_framework in _SUPPORTED_AGENT_FRAMEWORKS:
812
+ logger.info(f"Using agent framework: {agent_framework}")
813
+ return agent_framework
814
+ if hasattr(agent, _AGENT_FRAMEWORK_ATTR):
815
+ agent_framework_attr = getattr(agent, _AGENT_FRAMEWORK_ATTR)
816
+ if (
817
+ agent_framework_attr is not None
818
+ and isinstance(agent_framework_attr, str)
819
+ and agent_framework_attr in _SUPPORTED_AGENT_FRAMEWORKS
820
+ ):
821
+ logger.info(f"Using agent framework: {agent_framework_attr}")
822
+ return agent_framework_attr
823
+ logger.info(
824
+ f"The provided agent framework {agent_framework} is not supported."
825
+ f" Defaulting to {_DEFAULT_AGENT_FRAMEWORK}."
826
+ )
827
+ return _DEFAULT_AGENT_FRAMEWORK
828
+
829
+
830
+ def _get_gcs_bucket(
831
+ *,
832
+ project: str,
833
+ location: str,
834
+ staging_bucket: str,
835
+ credentials: Optional[Any] = None,
836
+ ) -> _StorageBucket:
837
+ """Gets or creates the GCS bucket."""
838
+ storage = _import_cloud_storage_or_raise()
839
+ storage_client = storage.Client(project=project, credentials=credentials)
840
+ staging_bucket = staging_bucket.replace("gs://", "")
841
+ try:
842
+ gcs_bucket = storage_client.get_bucket(staging_bucket)
843
+ logger.info(f"Using bucket {staging_bucket}")
844
+ except exceptions.NotFound:
845
+ new_bucket = storage_client.bucket(staging_bucket)
846
+ gcs_bucket = storage_client.create_bucket(new_bucket, location=location)
847
+ logger.info(f"Creating bucket {staging_bucket} in {location=}")
848
+ return gcs_bucket
849
+
850
+
851
+ def _get_registered_operations(
852
+ *,
853
+ agent: _AgentEngineInterface,
854
+ ) -> dict[str, list[str]]:
855
+ """Retrieves registered operations for a AgentEngine."""
856
+ if isinstance(agent, OperationRegistrable):
857
+ return agent.register_operations()
858
+
859
+ operations = {}
860
+ if isinstance(agent, Queryable):
861
+ operations[_STANDARD_API_MODE] = [_DEFAULT_METHOD_NAME]
862
+ if isinstance(agent, AsyncQueryable):
863
+ operations[_ASYNC_API_MODE] = [_DEFAULT_ASYNC_METHOD_NAME]
864
+ if isinstance(agent, StreamQueryable):
865
+ operations[_STREAM_API_MODE] = [_DEFAULT_STREAM_METHOD_NAME]
866
+ if isinstance(agent, AsyncStreamQueryable):
867
+ operations[_ASYNC_STREAM_API_MODE] = [_DEFAULT_ASYNC_STREAM_METHOD_NAME]
868
+ if isinstance(agent, BidiStreamQueryable):
869
+ operations[_BIDI_STREAM_API_MODE] = [_DEFAULT_BIDI_STREAM_METHOD_NAME]
870
+ return operations
871
+
872
+
873
+ def _import_cloudpickle_or_raise() -> types.ModuleType:
874
+ """Tries to import the cloudpickle module."""
875
+ try:
876
+ import cloudpickle # noqa:F401
877
+ except ImportError as e:
878
+ raise ImportError(
879
+ "cloudpickle is not installed. Please call "
880
+ "'pip install google-cloud-aiplatform[agent_engines]'."
881
+ ) from e
882
+ return cloudpickle # type: ignore[no-any-return]
883
+
884
+
885
+ def _import_cloud_storage_or_raise() -> types.ModuleType:
886
+ """Tries to import the Cloud Storage module."""
887
+ try:
888
+ from google.cloud import storage # type: ignore[attr-defined]
889
+ except ImportError as e:
890
+ raise ImportError(
891
+ "Cloud Storage is not installed. Please call "
892
+ "'pip install google-cloud-aiplatform[agent_engines]'."
893
+ ) from e
894
+ return storage # type: ignore[no-any-return]
895
+
896
+
897
+ def _import_packaging_requirements_or_raise() -> types.ModuleType:
898
+ """Tries to import the packaging.requirements module."""
899
+ try:
900
+ from packaging import requirements
901
+ except ImportError as e:
902
+ raise ImportError(
903
+ "packaging.requirements is not installed. Please call "
904
+ "'pip install google-cloud-aiplatform[agent_engines]'."
905
+ ) from e
906
+ return requirements
907
+
908
+
909
+ def _import_packaging_version_or_raise() -> types.ModuleType:
910
+ """Tries to import the packaging.requirements module."""
911
+ try:
912
+ from packaging import version
913
+ except ImportError as e:
914
+ raise ImportError(
915
+ "packaging.version is not installed. Please call "
916
+ "'pip install google-cloud-aiplatform[agent_engines]'."
917
+ ) from e
918
+ return version
919
+
920
+
921
+ def _import_pydantic_or_raise() -> types.ModuleType:
922
+ """Tries to import the pydantic module."""
923
+ try:
924
+ import pydantic
925
+
926
+ _ = pydantic.Field
927
+ except AttributeError:
928
+ from pydantic import v1 as pydantic # type: ignore[no-redef]
929
+ except ImportError as e:
930
+ raise ImportError(
931
+ "pydantic is not installed. Please call "
932
+ "'pip install google-cloud-aiplatform[agent_engines]'."
933
+ ) from e
934
+ return pydantic
935
+
936
+
937
+ def _parse_constraints(
938
+ *,
939
+ constraints: Sequence[str],
940
+ ) -> Mapping[str, Optional["_SpecifierSet"]]:
941
+ """Parses a list of constraints into a dict of requirements.
942
+
943
+ Args:
944
+ constraints (list[str]):
945
+ Required. The list of package requirements to parse. This is assumed
946
+ to come from the `requirements.txt` file.
947
+
948
+ Returns:
949
+ dict[str, SpecifierSet]: The specifiers for each package.
950
+ """
951
+ requirements = _import_packaging_requirements_or_raise()
952
+ result: Dict[str, Optional[_SpecifierSet]] = {}
953
+ for constraint in constraints:
954
+ try:
955
+ if constraint.endswith(".whl"):
956
+ constraint = os.path.basename(constraint)
957
+ requirement = requirements.Requirement(constraint)
958
+ except Exception as e:
959
+ logger.warning(f"Failed to parse constraint: {constraint}. Exception: {e}")
960
+ continue
961
+ result[requirement.name] = requirement.specifier or None
962
+ return result
963
+
964
+
965
+ def _prepare(
966
+ *,
967
+ agent: Optional[_AgentEngineInterface],
968
+ requirements: Optional[Sequence[str]],
969
+ extra_packages: Optional[Sequence[str]],
970
+ project: str,
971
+ location: str,
972
+ staging_bucket: str,
973
+ gcs_dir_name: str,
974
+ credentials: Optional[Any] = None,
975
+ ) -> None:
976
+ """Prepares the agent engine for creation or updates in Vertex AI.
977
+
978
+ This involves packaging and uploading artifacts to Cloud Storage. Note that
979
+ 1. This does not actually update the Agent Engine in Vertex AI.
980
+ 2. This will only generate and upload a pickled object if specified.
981
+ 3. This will only generate and upload the dependencies.tar.gz file if
982
+ extra_packages is non-empty.
983
+
984
+ Args:
985
+ agent: The agent engine to be prepared.
986
+ requirements (Sequence[str]): The set of PyPI dependencies needed.
987
+ extra_packages (Sequence[str]): The set of extra user-provided packages.
988
+ project (str): The project for the staging bucket.
989
+ location (str): The location for the staging bucket.
990
+ staging_bucket (str): The staging bucket name in the form "gs://...".
991
+ gcs_dir_name (str): The GCS bucket directory under `staging_bucket` to use
992
+ for staging the artifacts needed.
993
+ credentials: The credentials to use for the storage client.
994
+ """
995
+ if agent is None:
996
+ return
997
+ gcs_bucket = _get_gcs_bucket(
998
+ project=project,
999
+ location=location,
1000
+ staging_bucket=staging_bucket,
1001
+ credentials=credentials,
1002
+ )
1003
+ _upload_agent_engine(
1004
+ agent=agent,
1005
+ gcs_bucket=gcs_bucket,
1006
+ gcs_dir_name=gcs_dir_name,
1007
+ )
1008
+ if requirements is not None:
1009
+ _upload_requirements(
1010
+ requirements=requirements,
1011
+ gcs_bucket=gcs_bucket,
1012
+ gcs_dir_name=gcs_dir_name,
1013
+ )
1014
+ if extra_packages is not None:
1015
+ _upload_extra_packages(
1016
+ extra_packages=extra_packages,
1017
+ gcs_bucket=gcs_bucket,
1018
+ gcs_dir_name=gcs_dir_name,
1019
+ )
1020
+
1021
+
1022
+ def _register_api_methods_or_raise(
1023
+ *,
1024
+ agent_engine: genai_types.AgentEngine | genai_types.AgentEngineRuntimeRevision,
1025
+ wrap_operation_fn: Optional[
1026
+ dict[str, Callable[[str, str], Callable[..., Any]]]
1027
+ ] = None,
1028
+ ) -> None:
1029
+ """Registers Agent Engine API methods based on operation schemas.
1030
+
1031
+ This function iterates through operation schemas provided by the
1032
+ `agent_engine`. Each schema defines an API mode and method name.
1033
+ It dynamically creates and registers methods on the `agent_engine`
1034
+ to handle API calls based on the specified API mode.
1035
+ Currently, only standard API mode `` is supported.
1036
+
1037
+ Args:
1038
+ agent_engine: The AgentEngine to augment with API methods.
1039
+ wrap_operation_fn: A dictionary of API modes and method wrapping
1040
+ functions.
1041
+
1042
+ Raises:
1043
+ ValueError: If the API mode is not supported or if the operation schema
1044
+ is missing any required fields (e.g. `api_mode` or `name`).
1045
+ """
1046
+ operation_schemas = agent_engine.operation_schemas()
1047
+ if not operation_schemas:
1048
+ return
1049
+ for operation_schema in operation_schemas:
1050
+ if _MODE_KEY_IN_SCHEMA not in operation_schema:
1051
+ raise ValueError(
1052
+ f"Operation schema {operation_schema} does not"
1053
+ f" contain an `{_MODE_KEY_IN_SCHEMA}` field."
1054
+ )
1055
+ api_mode = operation_schema.get(_MODE_KEY_IN_SCHEMA)
1056
+ # For bidi stream api mode, we don't need to wrap the operation.
1057
+ if api_mode == _BIDI_STREAM_API_MODE:
1058
+ continue
1059
+
1060
+ if _METHOD_NAME_KEY_IN_SCHEMA not in operation_schema:
1061
+ raise ValueError(
1062
+ f"Operation schema {operation_schema} does not"
1063
+ f" contain a `{_METHOD_NAME_KEY_IN_SCHEMA}` field."
1064
+ )
1065
+ method_name = operation_schema.get(_METHOD_NAME_KEY_IN_SCHEMA)
1066
+ if not isinstance(method_name, str):
1067
+ raise ValueError(
1068
+ "Operation schema has a non-string value for"
1069
+ f" `{_METHOD_NAME_KEY_IN_SCHEMA}`: {method_name}"
1070
+ )
1071
+ method_description = operation_schema.get(
1072
+ "description",
1073
+ _DEFAULT_METHOD_DOCSTRING_TEMPLATE.format(
1074
+ method_name=method_name,
1075
+ default_method_name=_DEFAULT_METHOD_NAME_MAP.get(
1076
+ api_mode, _DEFAULT_METHOD_NAME
1077
+ ),
1078
+ return_type=_DEFAULT_METHOD_RETURN_TYPE_MAP.get(
1079
+ api_mode,
1080
+ _DEFAULT_METHOD_RETURN_TYPE,
1081
+ ),
1082
+ ),
1083
+ )
1084
+ _wrap_operation_map = {
1085
+ _STANDARD_API_MODE: _wrap_query_operation,
1086
+ _ASYNC_API_MODE: _wrap_async_query_operation,
1087
+ _STREAM_API_MODE: _wrap_stream_query_operation,
1088
+ _ASYNC_STREAM_API_MODE: _wrap_async_stream_query_operation,
1089
+ _A2A_EXTENSION_MODE: _wrap_a2a_operation,
1090
+ }
1091
+ if isinstance(wrap_operation_fn, dict) and api_mode in wrap_operation_fn:
1092
+ # Override the default function with user-specified function if it exists.
1093
+ _wrap_operation = wrap_operation_fn[api_mode]
1094
+ elif api_mode in _wrap_operation_map:
1095
+ _wrap_operation = _wrap_operation_map[api_mode] # type: ignore[assignment]
1096
+ else:
1097
+ supported_api_modes = ", ".join(
1098
+ f"`{mode}`" for mode in sorted(_wrap_operation_map.keys())
1099
+ )
1100
+ raise ValueError(
1101
+ f"Unsupported api mode: `{api_mode}`,"
1102
+ f" Supported modes are: {supported_api_modes}."
1103
+ )
1104
+
1105
+ # Bind the method to the object.
1106
+ if api_mode == _A2A_EXTENSION_MODE:
1107
+ agent_card = operation_schema.get(_A2A_AGENT_CARD)
1108
+ method = _wrap_operation(
1109
+ method_name=method_name, agent_card=agent_card
1110
+ ) # type: ignore[call-arg]
1111
+ else:
1112
+ method = _wrap_operation(method_name=method_name) # type: ignore[call-arg]
1113
+ method.__name__ = method_name
1114
+ if method_description and isinstance(method_description, str):
1115
+ method.__doc__ = method_description
1116
+ setattr(agent_engine, method_name, types.MethodType(method, agent_engine))
1117
+
1118
+
1119
+ def _scan_requirements(
1120
+ *,
1121
+ obj: Any,
1122
+ ignore_modules: Optional[Sequence[str]] = None,
1123
+ package_distributions: Optional[Mapping[str, Sequence[str]]] = None,
1124
+ inspect_getmembers_kwargs: Optional[Mapping[str, Any]] = None,
1125
+ ) -> Mapping[str, str]:
1126
+ """Scans the object for modules and returns the requirements discovered.
1127
+
1128
+ This is not a comprehensive scan of the object, and only detects for common
1129
+ cases based on the members of the object returned by `dir(obj)`.
1130
+
1131
+ Args:
1132
+ obj (Any):
1133
+ Required. The object to scan for package requirements.
1134
+ ignore_modules (Sequence[str]):
1135
+ Optional. The set of modules to ignore. It defaults to the set of
1136
+ built-in and stdlib modules.
1137
+ package_distributions (Mapping[str, Sequence[str]]):
1138
+ Optional. The mapping of module names to the set of packages that
1139
+ contain them. It defaults to the set of packages from
1140
+ `importlib_metadata.packages_distributions()`.
1141
+ inspect_getmembers_kwargs (Mapping[str, Any]):
1142
+ Optional. The keyword arguments to pass to `inspect.getmembers`. It
1143
+ defaults to an empty dictionary.
1144
+
1145
+ Returns:
1146
+ Sequence[str]: The list of requirements that were discovered.
1147
+ """
1148
+ if ignore_modules is None:
1149
+ ignore_modules = _BASE_MODULES # type: ignore[assignment]
1150
+ if package_distributions is None:
1151
+ package_distributions = _PACKAGE_DISTRIBUTIONS
1152
+ modules_found = set(_DEFAULT_REQUIRED_PACKAGES)
1153
+ inspect_getmembers_kwargs = inspect_getmembers_kwargs or {}
1154
+ for _, attr in inspect.getmembers(obj, **inspect_getmembers_kwargs):
1155
+ if not attr or inspect.isbuiltin(attr) or not hasattr(attr, "__module__"):
1156
+ continue
1157
+ module_name = (attr.__module__ or "").split(".")[0]
1158
+ if module_name and module_name not in ignore_modules: # type: ignore[operator]
1159
+ for module in package_distributions.get(module_name, []):
1160
+ modules_found.add(module)
1161
+ return {module: importlib_metadata.version(module) for module in modules_found}
1162
+
1163
+
1164
+ def _to_dict(message: proto.Message) -> Dict[str, Any]:
1165
+ """Converts the contents of the protobuf message to JSON format.
1166
+
1167
+ Args:
1168
+ message (proto.Message):
1169
+ Required. The proto message to be converted to a JSON dictionary.
1170
+
1171
+ Returns:
1172
+ dict[str, Any]: A dictionary containing the contents of the proto.
1173
+ """
1174
+ try:
1175
+ # Best effort attempt to convert the message into a JSON dictionary.
1176
+ result: Dict[str, Any] = json.loads(
1177
+ json_format.MessageToJson(
1178
+ message._pb,
1179
+ preserving_proto_field_name=True,
1180
+ )
1181
+ )
1182
+ except AttributeError:
1183
+ result: Dict[str, Any] = json.loads( # type: ignore[no-redef]
1184
+ json_format.MessageToJson(
1185
+ message,
1186
+ preserving_proto_field_name=True,
1187
+ )
1188
+ )
1189
+ return result
1190
+
1191
+
1192
+ def _to_proto(
1193
+ obj: Union[Dict[str, Any], proto.Message],
1194
+ message: Optional[proto.Message] = None,
1195
+ ) -> proto.Message:
1196
+ """Parses a JSON-like object into a message.
1197
+
1198
+ If the object is already a message, this will return the object as-is. If
1199
+ the object is a JSON Dict, this will parse and merge the object into the
1200
+ message.
1201
+
1202
+ Args:
1203
+ obj (Union[dict[str, Any], proto.Message]):
1204
+ Required. The object to convert to a proto message.
1205
+ message (proto.Message):
1206
+ Optional. A protocol buffer message to merge the obj into. It
1207
+ defaults to Struct() if unspecified.
1208
+
1209
+ Returns:
1210
+ proto.Message: The same message passed as argument.
1211
+ """
1212
+ if message is None:
1213
+ message = struct_pb2.Struct()
1214
+ if isinstance(obj, (proto.Message, struct_pb2.Struct)):
1215
+ return obj
1216
+ try:
1217
+ json_format.ParseDict(obj, message._pb)
1218
+ except AttributeError:
1219
+ json_format.ParseDict(obj, message)
1220
+ return message
1221
+
1222
+
1223
+ def _upload_agent_engine(
1224
+ *,
1225
+ agent: _AgentEngineInterface,
1226
+ gcs_bucket: _StorageBucket,
1227
+ gcs_dir_name: str,
1228
+ ) -> None:
1229
+ """Uploads the agent engine to GCS."""
1230
+ cloudpickle = _import_cloudpickle_or_raise()
1231
+ blob = gcs_bucket.blob(f"{gcs_dir_name}/{_BLOB_FILENAME}")
1232
+ with blob.open("wb") as f:
1233
+ try:
1234
+ cloudpickle.dump(agent, f)
1235
+ except Exception as e:
1236
+ url = "https://cloud.google.com/vertex-ai/generative-ai/docs/agent-engine/develop/custom#deployment-considerations"
1237
+ error_msg = f"Failed to serialize agent engine. Visit {url} for details."
1238
+ if "google._upb._message" in str(e) or "Descriptor" in str(e):
1239
+ error_msg += (
1240
+ " This is often caused by protobuf objects (like Part, AgentCard) "
1241
+ "being imported at the global module level. Please move these "
1242
+ "imports inside the functions or methods where they are used. "
1243
+ "Alternatively, you can import the entire module: "
1244
+ "`from a2a import types`."
1245
+ )
1246
+ raise TypeError(error_msg) from e
1247
+ with blob.open("rb") as f:
1248
+ try:
1249
+ _ = cloudpickle.load(f)
1250
+ except Exception as e:
1251
+ raise TypeError("Agent engine serialized to an invalid format") from e
1252
+ dir_name = f"gs://{gcs_bucket.name}/{gcs_dir_name}"
1253
+ logger.info(f"Wrote to {dir_name}/{_BLOB_FILENAME}")
1254
+
1255
+
1256
+ def _upload_requirements(
1257
+ *,
1258
+ requirements: Sequence[str],
1259
+ gcs_bucket: _StorageBucket,
1260
+ gcs_dir_name: str,
1261
+ ) -> None:
1262
+ """Uploads the requirements file to GCS."""
1263
+ blob = gcs_bucket.blob(f"{gcs_dir_name}/{_REQUIREMENTS_FILE}")
1264
+ blob.upload_from_string("\n".join(requirements))
1265
+ dir_name = f"gs://{gcs_bucket.name}/{gcs_dir_name}"
1266
+ logger.info(f"Writing to {dir_name}/{_REQUIREMENTS_FILE}")
1267
+
1268
+
1269
+ def _upload_extra_packages(
1270
+ *,
1271
+ extra_packages: Sequence[str],
1272
+ gcs_bucket: _StorageBucket,
1273
+ gcs_dir_name: str,
1274
+ ) -> None:
1275
+ """Uploads extra packages to GCS."""
1276
+ logger.info("Creating in-memory tarfile of extra_packages")
1277
+ tar_fileobj = io.BytesIO()
1278
+ with tarfile.open(fileobj=tar_fileobj, mode="w|gz") as tar:
1279
+ for file in extra_packages:
1280
+ tar.add(file)
1281
+ tar_fileobj.seek(0)
1282
+ blob = gcs_bucket.blob(f"{gcs_dir_name}/{_EXTRA_PACKAGES_FILE}")
1283
+ blob.upload_from_string(tar_fileobj.read())
1284
+ dir_name = f"gs://{gcs_bucket.name}/{gcs_dir_name}"
1285
+ logger.info(f"Writing to {dir_name}/{_EXTRA_PACKAGES_FILE}")
1286
+
1287
+
1288
+ def _create_base64_encoded_tarball(
1289
+ *,
1290
+ source_packages: Sequence[str],
1291
+ ) -> str:
1292
+ """Creates a base64 encoded tarball from the source packages."""
1293
+ logger.info("Creating in-memory tarfile of source_packages")
1294
+ tar_fileobj = io.BytesIO()
1295
+ project_dir = os.path.realpath(os.getcwd())
1296
+ with tarfile.open(fileobj=tar_fileobj, mode="w|gz") as tar:
1297
+ for file in source_packages:
1298
+ real_file_path = os.path.realpath(file)
1299
+ if real_file_path != project_dir and not real_file_path.startswith(
1300
+ project_dir + os.sep
1301
+ ):
1302
+ raise ValueError(
1303
+ f"File path '{file}' is outside the project directory "
1304
+ f"'{project_dir}'."
1305
+ )
1306
+ tar.add(file)
1307
+ tar_fileobj.seek(0)
1308
+ tarball_bytes = tar_fileobj.read()
1309
+ return base64.b64encode(tarball_bytes).decode("utf-8")
1310
+
1311
+
1312
+ def _validate_packages_or_raise(
1313
+ *,
1314
+ packages: Sequence[str],
1315
+ build_options: Optional[Dict[str, Sequence[str]]] = None,
1316
+ ) -> Sequence[str]:
1317
+ """Tries to validates the packages."""
1318
+ packages = packages or []
1319
+ if build_options and _INSTALLATION_SUBDIR in build_options:
1320
+ _validate_installation_scripts_or_raise(
1321
+ script_paths=build_options[_INSTALLATION_SUBDIR],
1322
+ packages=packages,
1323
+ )
1324
+ for package in packages:
1325
+ if not os.path.exists(package):
1326
+ raise FileNotFoundError(f"Package specified but not found: {package=}")
1327
+ return packages
1328
+
1329
+
1330
+ def _validate_installation_scripts_or_raise(
1331
+ *,
1332
+ script_paths: Sequence[str],
1333
+ packages: Sequence[str],
1334
+ ) -> None:
1335
+ """Validates the installation scripts' path explicitly provided by the user.
1336
+
1337
+ Args:
1338
+ script_paths (Sequence[str]):
1339
+ Required. The paths to the installation scripts.
1340
+ packages (Sequence[str]):
1341
+ Required. The user-provided packages.
1342
+
1343
+ Raises:
1344
+ ValueError: If a user-defined script is not under the expected
1345
+ subdirectory, or not in `packages`, or if a package is
1346
+ in the installation scripts subdirectory, but is not specified as an
1347
+ installation script.
1348
+ """
1349
+ for script_path in script_paths:
1350
+ if not script_path.startswith(_INSTALLATION_SUBDIR):
1351
+ logger.warning(
1352
+ f"User-defined installation script '{script_path}' is not in "
1353
+ f"the expected '{_INSTALLATION_SUBDIR}' subdirectory. "
1354
+ f"Ensure it is placed in '{_INSTALLATION_SUBDIR}' within your "
1355
+ f"'extra_packages' or 'source_packages'."
1356
+ )
1357
+ raise ValueError(
1358
+ f"Required installation script '{script_path}' "
1359
+ f"is not under '{_INSTALLATION_SUBDIR}'"
1360
+ )
1361
+
1362
+ if script_path not in packages:
1363
+ logger.warning(
1364
+ f"User-defined installation script '{script_path}' is not in "
1365
+ f"'extra_packages' or 'source_packages'. Ensure it is added to "
1366
+ f"'extra_packages' or 'source_packages'."
1367
+ )
1368
+ raise ValueError(
1369
+ f"User-defined installation script '{script_path}' "
1370
+ f"does not exist in 'extra_packages' or 'source_packages'."
1371
+ )
1372
+
1373
+ for package in packages:
1374
+ if package.startswith(_INSTALLATION_SUBDIR) and package not in script_paths:
1375
+ logger.warning(
1376
+ f"Package '{package}' is in the installation "
1377
+ "scripts subdirectory, but is not specified as an installation "
1378
+ "script in `build_options`. "
1379
+ "Ensure it is added to installation_scripts for "
1380
+ "automatic execution."
1381
+ )
1382
+ raise ValueError(
1383
+ f"Package '{package}' is in the installation "
1384
+ "scripts subdirectory, but is not specified as an installation "
1385
+ "script in `build_options`."
1386
+ )
1387
+ return
1388
+
1389
+
1390
+ def _validate_staging_bucket_or_raise(*, staging_bucket: str) -> str:
1391
+ """Tries to validate the staging bucket."""
1392
+ if not staging_bucket:
1393
+ raise ValueError(
1394
+ "Please provide a `staging_bucket` in `client.agent_engines.create(...)`."
1395
+ )
1396
+ if not staging_bucket.startswith("gs://"):
1397
+ raise ValueError(f"{staging_bucket=} must start with `gs://`")
1398
+ return staging_bucket
1399
+
1400
+
1401
+ def _validate_requirements_or_warn(
1402
+ *,
1403
+ obj: Any,
1404
+ requirements: List[str],
1405
+ ) -> List[str]:
1406
+ """Compiles the requirements into a list of requirements."""
1407
+ requirements = requirements.copy()
1408
+ try:
1409
+ current_requirements = _scan_requirements(obj=obj)
1410
+ logger.info(f"Identified the following requirements: {current_requirements}")
1411
+ constraints = _parse_constraints(constraints=requirements)
1412
+ missing_requirements = _compare_requirements(
1413
+ requirements=current_requirements,
1414
+ constraints=constraints,
1415
+ )
1416
+ for warning_type, warnings in missing_requirements["warnings"].items():
1417
+ if warnings:
1418
+ logger.warning(
1419
+ f"The following requirements are {warning_type}: {warnings}"
1420
+ )
1421
+ for action_type, actions in missing_requirements["actions"].items():
1422
+ if actions and action_type == _ACTION_APPEND:
1423
+ for action in actions: # type: ignore[attr-defined]
1424
+ requirements.append(action)
1425
+ logger.info(f"The following requirements are appended: {actions}")
1426
+ except Exception as e:
1427
+ logger.warning(f"Failed to compile requirements: {e}")
1428
+ return requirements
1429
+
1430
+
1431
+ def _validate_requirements_or_raise(
1432
+ *,
1433
+ agent: Any,
1434
+ requirements: Optional[Sequence[str]] = None,
1435
+ ) -> Sequence[str]:
1436
+ """Tries to validate the requirements."""
1437
+ if requirements is None:
1438
+ requirements = []
1439
+ elif isinstance(requirements, str):
1440
+ try:
1441
+ logger.info(f"Reading requirements from {requirements=}")
1442
+ with open(requirements) as f:
1443
+ requirements = f.read().splitlines()
1444
+ logger.info(f"Read the following lines: {requirements}")
1445
+ except IOError as err:
1446
+ raise IOError(f"Failed to read requirements from {requirements=}") from err
1447
+ requirements = _validate_requirements_or_warn(
1448
+ obj=agent,
1449
+ requirements=requirements,
1450
+ )
1451
+ logger.info(f"The final list of requirements: {requirements}")
1452
+ return requirements
1453
+
1454
+
1455
+ def _validate_agent_or_raise(
1456
+ *,
1457
+ agent: _AgentEngineInterface,
1458
+ ) -> _AgentEngineInterface:
1459
+ """Tries to validate the agent engine.
1460
+
1461
+ The agent engine must have one of the following:
1462
+ * a callable method named `query`
1463
+ * a callable method named `stream_query`
1464
+ * a callable method named `async_stream_query`
1465
+ * a callable method named `bidi_stream_query`
1466
+ * a callable method named `register_operations`
1467
+
1468
+ Args:
1469
+ agent: The agent to be validated.
1470
+
1471
+ Returns:
1472
+ The validated agent engine.
1473
+
1474
+ Raises:
1475
+ TypeError: If `agent_engine` has no callable method named `query`,
1476
+ `stream_query` or `register_operations`.
1477
+ ValueError: If `agent_engine` has an invalid `query`, `stream_query` or
1478
+ `register_operations` signature.
1479
+ """
1480
+ try:
1481
+ from google.adk.agents import BaseAgent
1482
+
1483
+ if isinstance(agent, BaseAgent):
1484
+ logger.info("Deploying google.adk.agents.Agent as an application.")
1485
+ from agentplatform import agent_engines
1486
+
1487
+ agent = agent_engines.AdkApp(agent=agent)
1488
+ except Exception:
1489
+ pass
1490
+ is_queryable = isinstance(agent, Queryable) and callable(agent.query)
1491
+ is_async_queryable = isinstance(agent, AsyncQueryable) and callable(
1492
+ agent.async_query
1493
+ )
1494
+ is_stream_queryable = isinstance(agent, StreamQueryable) and callable(
1495
+ agent.stream_query
1496
+ )
1497
+ is_async_stream_queryable = isinstance(agent, AsyncStreamQueryable) and callable(
1498
+ agent.async_stream_query
1499
+ )
1500
+ is_bidi_stream_queryable = isinstance(agent, BidiStreamQueryable) and callable(
1501
+ agent.bidi_stream_query
1502
+ )
1503
+ is_operation_registrable = isinstance(agent, OperationRegistrable) and callable(
1504
+ agent.register_operations
1505
+ )
1506
+
1507
+ if not (
1508
+ is_queryable
1509
+ or is_async_queryable
1510
+ or is_stream_queryable
1511
+ or is_operation_registrable
1512
+ or is_bidi_stream_queryable
1513
+ or is_async_stream_queryable
1514
+ ):
1515
+ raise TypeError(
1516
+ "agent_engine has none of the following callable methods: "
1517
+ "`query`, `async_query`, `stream_query`, `async_stream_query`, "
1518
+ "`bidi_stream_query`, or `register_operations`."
1519
+ )
1520
+
1521
+ if is_queryable:
1522
+ try:
1523
+ inspect.signature(getattr(agent, "query"))
1524
+ except ValueError as err:
1525
+ raise ValueError(
1526
+ "Invalid query signature. This might be due to a missing "
1527
+ "`self` argument in the agent.query method."
1528
+ ) from err
1529
+
1530
+ if is_async_queryable:
1531
+ try:
1532
+ inspect.signature(getattr(agent, "async_query"))
1533
+ except ValueError as err:
1534
+ raise ValueError(
1535
+ "Invalid async_query signature. This might be due to a missing "
1536
+ "`self` argument in the agent.async_query method."
1537
+ ) from err
1538
+
1539
+ if is_stream_queryable:
1540
+ try:
1541
+ inspect.signature(getattr(agent, "stream_query"))
1542
+ except ValueError as err:
1543
+ raise ValueError(
1544
+ "Invalid stream_query signature. This might be due to a missing"
1545
+ " `self` argument in the agent.stream_query method."
1546
+ ) from err
1547
+
1548
+ if is_async_stream_queryable:
1549
+ try:
1550
+ inspect.signature(getattr(agent, "async_stream_query"))
1551
+ except ValueError as err:
1552
+ raise ValueError(
1553
+ "Invalid async_stream_query signature. This might be due to a "
1554
+ " missing `self` argument in the agent.async_stream_query method."
1555
+ ) from err
1556
+
1557
+ if is_bidi_stream_queryable:
1558
+ try:
1559
+ inspect.signature(getattr(agent, "bidi_stream_query"))
1560
+ except ValueError as err:
1561
+ raise ValueError(
1562
+ "Invalid bidi_stream_query signature. This might be due to a "
1563
+ " missing `self` argument in the agent.bidi_stream_query method."
1564
+ ) from err
1565
+
1566
+ if is_operation_registrable:
1567
+ try:
1568
+ inspect.signature(getattr(agent, "register_operations"))
1569
+ except ValueError as err:
1570
+ raise ValueError(
1571
+ "Invalid register_operations signature. This might be due to a "
1572
+ "missing `self` argument in the agent.register_operations method."
1573
+ ) from err
1574
+
1575
+ if isinstance(agent, Cloneable):
1576
+ # Avoid undeployable states.
1577
+ agent = agent.clone()
1578
+ return agent
1579
+
1580
+
1581
+ def _wrap_agent_operation(*, agent: Any, operation: str) -> Callable[..., Any]:
1582
+ """Wraps an agent operation into a method (works for all API modes)."""
1583
+
1584
+ def _method(self, **kwargs) -> Any: # type: ignore[no-untyped-def]
1585
+ if not self._tmpl_attrs.get("agent"):
1586
+ self.set_up()
1587
+ return getattr(self._tmpl_attrs["agent"], operation)(**kwargs)
1588
+
1589
+ _method.__name__ = operation
1590
+ _method.__doc__ = getattr(agent, operation).__doc__
1591
+ return _method
1592
+
1593
+
1594
+ def _wrap_query_operation(*, method_name: str) -> Callable[..., Any]:
1595
+ """Wraps an Agent Engine method, creating a callable for `query` API.
1596
+
1597
+ This function creates a callable object that executes the specified
1598
+ Agent Engine method using the `query` API. It handles the creation of
1599
+ the API request and the processing of the API response.
1600
+
1601
+ Args:
1602
+ method_name: The name of the Agent Engine method to call.
1603
+ doc: Documentation string for the method.
1604
+
1605
+ Returns:
1606
+ A callable object that executes the method on the Agent Engine via
1607
+ the `query` API.
1608
+ """
1609
+
1610
+ def _method(self: genai_types.AgentEngine, **kwargs) -> Any: # type: ignore[no-untyped-def]
1611
+ if not self.api_client:
1612
+ raise ValueError("api_client is not initialized.")
1613
+ if not self.api_resource:
1614
+ raise ValueError("api_resource is not initialized.")
1615
+ response = self.api_client._query(
1616
+ name=self.api_resource.name,
1617
+ config={
1618
+ "class_method": method_name,
1619
+ "input": kwargs,
1620
+ "include_all_fields": True,
1621
+ },
1622
+ )
1623
+ return response.output
1624
+
1625
+ return _method
1626
+
1627
+
1628
+ def _wrap_async_query_operation(
1629
+ *, method_name: str
1630
+ ) -> Callable[..., Coroutine[Any, Any, Any]]:
1631
+ """Wraps an Agent Engine method, creating an async callable for `query` API.
1632
+
1633
+ This function creates a callable object that executes the specified
1634
+ Agent Engine method asynchronously using the `query` API. It handles the
1635
+ creation of the API request and the processing of the API response.
1636
+
1637
+ Args:
1638
+ method_name: The name of the Agent Engine method to call.
1639
+ doc: Documentation string for the method.
1640
+
1641
+ Returns:
1642
+ A callable object that executes the method on the Agent Engine via
1643
+ the `query` API.
1644
+ """
1645
+
1646
+ async def _method(
1647
+ self: genai_types.AgentEngine, **kwargs: Any
1648
+ ) -> Union[Coroutine[Any, Any, Any], Any]:
1649
+ if not self.api_async_client:
1650
+ raise ValueError("api_async_client is not initialized.")
1651
+ if not self.api_resource:
1652
+ raise ValueError("api_resource is not initialized.")
1653
+ response = await self.api_async_client._query(
1654
+ name=self.api_resource.name,
1655
+ config={
1656
+ "class_method": method_name,
1657
+ "input": kwargs,
1658
+ "include_all_fields": True,
1659
+ },
1660
+ )
1661
+ return response.output
1662
+
1663
+ return _method
1664
+
1665
+
1666
+ def _wrap_stream_query_operation(*, method_name: str) -> Callable[..., Iterator[Any]]:
1667
+ """Wraps an Agent Engine method, creating a callable for `stream_query` API.
1668
+
1669
+ This function creates a callable object that executes the specified
1670
+ Agent Engine method using the `stream_query` API. It handles the
1671
+ creation of the API request and the processing of the API response.
1672
+
1673
+ Args:
1674
+ method_name: The name of the Agent Engine method to call.
1675
+ doc: Documentation string for the method.
1676
+
1677
+ Returns:
1678
+ A callable object that executes the method on the Agent Engine via
1679
+ the `stream_query` API.
1680
+ """
1681
+
1682
+ def _method(self: genai_types.AgentEngine, **kwargs) -> Iterator[Any]: # type: ignore[no-untyped-def]
1683
+ if not self.api_client:
1684
+ raise ValueError("api_client is not initialized.")
1685
+ if not self.api_resource:
1686
+ raise ValueError("api_resource is not initialized.")
1687
+ for http_response in self.api_client._stream_query(
1688
+ name=self.api_resource.name,
1689
+ config={
1690
+ "class_method": method_name,
1691
+ "input": kwargs,
1692
+ "include_all_fields": True,
1693
+ },
1694
+ ):
1695
+ for line in _yield_parsed_json(http_response=http_response):
1696
+ if line is not None:
1697
+ yield line
1698
+
1699
+ return _method
1700
+
1701
+
1702
+ def _wrap_async_stream_query_operation(
1703
+ *, method_name: str
1704
+ ) -> Callable[..., AsyncIterator[Any]]:
1705
+ """Wraps an Agent Engine method, creating an async callable for `stream_query` API.
1706
+
1707
+ This function creates a callable object that executes the specified
1708
+ Agent Engine method using the `stream_query` API. It handles the
1709
+ creation of the API request and the processing of the API response.
1710
+
1711
+ Args:
1712
+ method_name: The name of the Agent Engine method to call.
1713
+ doc: Documentation string for the method.
1714
+
1715
+ Returns:
1716
+ A callable object that executes the method on the Agent Engine via
1717
+ the `stream_query` API.
1718
+ """
1719
+
1720
+ async def _method(self: genai_types.AgentEngine, **kwargs) -> AsyncIterator[Any]: # type: ignore[no-untyped-def]
1721
+ if not self.api_client:
1722
+ raise ValueError("api_client is not initialized.")
1723
+ if not self.api_resource:
1724
+ raise ValueError("api_resource is not initialized.")
1725
+ async for http_response in self.api_client._async_stream_query(
1726
+ name=self.api_resource.name,
1727
+ config={
1728
+ "class_method": method_name,
1729
+ "input": kwargs,
1730
+ "include_all_fields": True,
1731
+ },
1732
+ ):
1733
+ for line in _yield_parsed_json(http_response=http_response):
1734
+ if line is not None:
1735
+ yield line
1736
+
1737
+ return _method
1738
+
1739
+
1740
+ def _wrap_a2a_operation(method_name: str, agent_card: str) -> Callable[..., list[Any]]:
1741
+ """Wraps an Agent Engine method, creating a callable for A2A API.
1742
+
1743
+ Args:
1744
+ method_name: The name of the Agent Engine method to call.
1745
+ agent_card: The agent card to use for the A2A API call.
1746
+ Example:
1747
+ {'additionalInterfaces': None,
1748
+ 'capabilities': {'extensions': None,
1749
+ 'pushNotifications': None,
1750
+ 'stateTransitionHistory': None,
1751
+ 'streaming': False},
1752
+ 'defaultInputModes': ['text'],
1753
+ 'defaultOutputModes': ['text'],
1754
+ 'description': (
1755
+ 'A helpful assistant agent that can answer questions.'
1756
+ ),
1757
+ 'documentationUrl': None,
1758
+ 'iconUrl': None,
1759
+ 'name': 'Q&A Agent',
1760
+ 'preferredTransport': 'JSONRPC',
1761
+ 'protocolVersion': '0.3.0',
1762
+ 'provider': None,
1763
+ 'security': None,
1764
+ 'securitySchemes': None,
1765
+ 'signatures': None,
1766
+ 'skills': [{
1767
+ 'description': (
1768
+ 'A helpful assistant agent that can answer questions.'
1769
+ ),
1770
+ 'examples': ['Who is leading 2025 F1 Standings?',
1771
+ 'Where can i find an active volcano?'],
1772
+ 'id': 'question_answer',
1773
+ 'inputModes': None,
1774
+ 'name': 'Q&A Agent',
1775
+ 'outputModes': None,
1776
+ 'security': None,
1777
+ 'tags': ['Question-Answer']}],
1778
+ 'supportsAuthenticatedExtendedCard': True,
1779
+ 'url': 'http://localhost:8080/',
1780
+ 'version': '1.0.0'}
1781
+ Returns:
1782
+ A callable object that executes the method on the Agent Engine via
1783
+ the A2A API.
1784
+ """
1785
+
1786
+ async def _method(self, **kwargs) -> Any: # type: ignore[no-untyped-def]
1787
+ """Wraps an Agent Engine method, creating a callable for A2A API."""
1788
+ if not self.api_client:
1789
+ raise ValueError("api_client is not initialized.")
1790
+ if not self.api_resource:
1791
+ raise ValueError("api_resource is not initialized.")
1792
+ a2a_agent_card = AgentCard(**json.loads(agent_card))
1793
+ # A2A + AE integration currently only supports Rest API.
1794
+ if (
1795
+ a2a_agent_card.preferred_transport
1796
+ and a2a_agent_card.preferred_transport != TransportProtocol.http_json
1797
+ ):
1798
+ raise ValueError(
1799
+ "Only HTTP+JSON is supported for preferred transport on agent card "
1800
+ )
1801
+
1802
+ # Set preferred transport to HTTP+JSON if not set.
1803
+ if not hasattr(a2a_agent_card, "preferred_transport"):
1804
+ a2a_agent_card.preferred_transport = TransportProtocol.http_json
1805
+
1806
+ if not hasattr(a2a_agent_card.capabilities, "streaming"):
1807
+ a2a_agent_card.capabilities.streaming = False
1808
+
1809
+ # agent_card is set on the class_methods before set_up is invoked.
1810
+ # Ensure that the agent_card url is set correctly before the client is created.
1811
+ base_url = self.api_client._api_client._http_options.base_url.rstrip("/")
1812
+ api_version = self.api_client._api_client._http_options.api_version
1813
+ a2a_agent_card.url = f"{base_url}/{api_version}/{self.api_resource.name}/a2a"
1814
+
1815
+ # Using a2a client, inject the auth token from the global config.
1816
+ config = ClientConfig(
1817
+ supported_transports=[
1818
+ TransportProtocol.http_json,
1819
+ ],
1820
+ use_client_preference=True,
1821
+ httpx_client=httpx.AsyncClient(
1822
+ headers={
1823
+ "Authorization": (
1824
+ f"Bearer {self.api_client._api_client._credentials.token}"
1825
+ )
1826
+ },
1827
+ timeout=(
1828
+ self.api_client._api_client._http_options.timeout / 1000.0
1829
+ if self.api_client._api_client._http_options.timeout
1830
+ else None
1831
+ ),
1832
+ ),
1833
+ )
1834
+ factory = ClientFactory(config)
1835
+ client = factory.create(a2a_agent_card)
1836
+
1837
+ if method_name == "on_message_send":
1838
+ response = client.send_message(Message(**kwargs))
1839
+ chunks = []
1840
+ async for chunk in response:
1841
+ chunks.append(chunk)
1842
+ return chunks
1843
+ elif method_name == "on_get_task":
1844
+ response = await client.get_task(TaskQueryParams(**kwargs))
1845
+ elif method_name == "on_cancel_task":
1846
+ response = await client.cancel_task(TaskIdParams(**kwargs))
1847
+ elif method_name == "handle_authenticated_agent_card":
1848
+ response = await client.get_card()
1849
+ else:
1850
+ raise ValueError(f"Unknown method name: {method_name}")
1851
+
1852
+ return response
1853
+
1854
+ return _method # type: ignore[return-value]
1855
+
1856
+
1857
+ def _yield_parsed_json(http_response: google_genai_types.HttpResponse) -> Iterator[Any]:
1858
+ """Converts the body of the HTTP Response message to JSON format.
1859
+
1860
+ Args:
1861
+ http_response (google.genai.types.HttpResponse):
1862
+ Required. The httpbody body to be converted to JSON object(s).
1863
+
1864
+ Yields:
1865
+ Any: A JSON object or line of the original body or None.
1866
+ """
1867
+ if not http_response.body:
1868
+ yield None
1869
+ return
1870
+
1871
+ # Handle the case of multiple dictionaries delimited by newlines.
1872
+ for line in http_response.body.split("\n"):
1873
+ if line:
1874
+ try:
1875
+ line = json.loads(line)
1876
+ except Exception as e:
1877
+ logger.warning(f"failed to parse json: {line}. Exception: {e}")
1878
+ yield line
1879
+
1880
+
1881
+ def _validate_resource_limits_or_raise(resource_limits: dict[str, str]) -> None:
1882
+ """Validates the resource limits.
1883
+
1884
+ Checks that the resource limits are a dict with 'cpu' and 'memory' keys.
1885
+ Checks that the 'cpu' value is one of 1, 2, 4, 6, 8.
1886
+ Checks that the 'memory' value is a string ending with 'Gi'.
1887
+ Checks that the memory size is smaller than 32Gi.
1888
+ Checks that the memory size requires at least the specified number of CPUs.
1889
+
1890
+ Args:
1891
+ resource_limits: The resource limits to be validated.
1892
+
1893
+ Raises:
1894
+ TypeError: If the resource limits are not a dict.
1895
+ KeyError: If the resource limits do not contain 'cpu' and 'memory' keys.
1896
+ ValueError: If the 'cpu' value is not one of 1, 2, 4, 6, 8.
1897
+ ValueError: If the 'memory' value is not a string ending with 'Gi'.
1898
+ ValueError: If the memory size is too large.
1899
+ ValueError: If the memory size requires more CPUs than the specified
1900
+ 'cpu' value.
1901
+ """
1902
+ if not isinstance(resource_limits, dict):
1903
+ raise TypeError(f"resource_limits must be a dict. Got {type(resource_limits)}")
1904
+ if "cpu" not in resource_limits or "memory" not in resource_limits:
1905
+ raise KeyError("resource_limits must contain 'cpu' and 'memory' keys.")
1906
+
1907
+ cpu = int(resource_limits["cpu"])
1908
+ memory_str = resource_limits["memory"]
1909
+
1910
+ if cpu not in [1, 2, 4, 6, 8]:
1911
+ raise ValueError(
1912
+ "resource_limits['cpu'] must be one of 1, 2, 4, 6, 8. Got" f" {cpu}"
1913
+ )
1914
+
1915
+ if not isinstance(memory_str, str) or not memory_str.endswith("Gi"):
1916
+ raise ValueError(
1917
+ "resource_limits['memory'] must be a string ending with 'Gi'."
1918
+ f" Got {memory_str}"
1919
+ )
1920
+
1921
+ try:
1922
+ memory_gb = int(memory_str[:-2])
1923
+ except ValueError:
1924
+ raise ValueError(
1925
+ f"Invalid memory value: {memory_str}. Must be an integer"
1926
+ " followed by 'Gi'."
1927
+ )
1928
+
1929
+ # https://cloud.google.com/run/docs/configuring/memory-limits
1930
+ if memory_gb > 32:
1931
+ raise ValueError(
1932
+ f"Memory size of {memory_str} is too large. Must be smaller than 32Gi."
1933
+ )
1934
+ if memory_gb > 24:
1935
+ min_cpu = 8
1936
+ elif memory_gb > 16:
1937
+ min_cpu = 6
1938
+ elif memory_gb > 8:
1939
+ min_cpu = 4
1940
+ elif memory_gb > 4:
1941
+ min_cpu = 2
1942
+ else:
1943
+ min_cpu = 1
1944
+
1945
+ if cpu < min_cpu:
1946
+ raise ValueError(
1947
+ f"Memory size of {memory_str} requires at least {min_cpu} CPUs."
1948
+ f" Got {cpu}"
1949
+ )
1950
+
1951
+
1952
+ def _is_adk_agent(agent_engine: _AgentEngineInterface) -> bool:
1953
+ """Checks if the agent engine is an ADK agent.
1954
+
1955
+ Args:
1956
+ agent_engine: The agent engine to check.
1957
+
1958
+ Returns:
1959
+ True if the agent engine is an ADK agent, False otherwise.
1960
+ """
1961
+
1962
+ from agentplatform.agent_engines.templates import adk
1963
+
1964
+ return isinstance(agent_engine, adk.AdkApp)
1965
+
1966
+
1967
+ def _add_telemetry_enablement_env(
1968
+ env_vars: Optional[Dict[str, Union[str, Any]]]
1969
+ ) -> Optional[Dict[str, Union[str, Any]]]:
1970
+ """Adds telemetry enablement env var to the env vars.
1971
+
1972
+ This is in order to achieve default-on telemetry.
1973
+ If the telemetry enablement env var is already set, we do not override it.
1974
+
1975
+ Args:
1976
+ env_vars: The env vars to add the telemetry enablement env var to.
1977
+
1978
+ Returns:
1979
+ The env vars with the telemetry enablement env var added.
1980
+ """
1981
+
1982
+ GOOGLE_CLOUD_AGENT_ENGINE_ENABLE_TELEMETRY = (
1983
+ "GOOGLE_CLOUD_AGENT_ENGINE_ENABLE_TELEMETRY"
1984
+ )
1985
+ env_to_add = {GOOGLE_CLOUD_AGENT_ENGINE_ENABLE_TELEMETRY: "unspecified"}
1986
+
1987
+ if env_vars is None:
1988
+ return env_to_add
1989
+
1990
+ if not isinstance(env_vars, dict):
1991
+ raise TypeError(f"env_vars must be a dict, but got {type(env_vars)}.")
1992
+
1993
+ if GOOGLE_CLOUD_AGENT_ENGINE_ENABLE_TELEMETRY in env_vars:
1994
+ return env_vars
1995
+
1996
+ return env_vars | env_to_add
data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/_bigquery_utils.py ADDED
@@ -0,0 +1,49 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2025 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
+
16
+ import logging
17
+
18
+ from google.cloud import bigquery
19
+ from google.genai._api_client import BaseApiClient
20
+ import pandas as pd
21
+
22
+
23
+ logger = logging.getLogger(__name__)
24
+
25
+
26
+ class BigQueryUtils:
27
+ """Handles BigQuery operations."""
28
+
29
+ def __init__(self, api_client: BaseApiClient):
30
+ self.api_client = api_client
31
+ self.bigquery_client = bigquery.Client(
32
+ project=self.api_client.project,
33
+ credentials=self.api_client._credentials,
34
+ )
35
+
36
+ def load_bigquery_to_dataframe(self, table_uri: str) -> "pd.DataFrame":
37
+ """Loads data from a BigQuery table into a DataFrame."""
38
+ table = self.bigquery_client.get_table(table_uri)
39
+ return self.bigquery_client.list_rows(table).to_dataframe()
40
+
41
+ def upload_dataframe_to_bigquery(
42
+ self, df: "pd.DataFrame", bq_table_uri: str
43
+ ) -> None:
44
+ """Uploads a Pandas DataFrame to a BigQuery table."""
45
+ job = self.bigquery_client.load_table_from_dataframe(df, bq_table_uri)
46
+ job.result()
47
+ logger.info(
48
+ f"DataFrame successfully uploaded to BigQuery table: {bq_table_uri}"
49
+ )
data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/_datasets_utils.py ADDED
@@ -0,0 +1,280 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2025 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
+ """Utility functions for multimodal dataset."""
16
+
17
+ import asyncio
18
+ import datetime
19
+ from typing import Any, Type, TypeVar
20
+ import uuid
21
+
22
+ import google.auth.credentials
23
+ from agentplatform._genai.types import common
24
+ from google.genai import _common
25
+
26
+
27
+ METADATA_SCHEMA_URI = (
28
+ "gs://google-cloud-aiplatform/schema/dataset/metadata/multimodal_1.0.0.yaml"
29
+ )
30
+ _BQ_MULTIREGIONS = {"us", "eu"}
31
+ _DEFAULT_BQ_DATASET_PREFIX = "vertex_datasets"
32
+ _DEFAULT_BQ_TABLE_PREFIX = "multimodal_dataset"
33
+
34
+ T = TypeVar("T", bound=_common.BaseModel)
35
+
36
+
37
+ def create_from_response(
38
+ model_type: Type[T],
39
+ response: dict[str, Any],
40
+ config: Any | None = None,
41
+ ) -> T:
42
+ """Creates a model from a response."""
43
+ kwargs = (
44
+ {
45
+ "config": {
46
+ "response_schema": getattr(config, "response_schema", None),
47
+ "response_json_schema": getattr(config, "response_json_schema", None),
48
+ "include_all_fields": getattr(config, "include_all_fields", None),
49
+ }
50
+ }
51
+ if config
52
+ else {}
53
+ )
54
+ return model_type._from_response(response=response, kwargs=kwargs)
55
+
56
+
57
+ def validate_multimodal_dataset_bigquery_uri(
58
+ multimodal_dataset: common.MultimodalDataset,
59
+ ) -> None:
60
+ """Validates that a multimodal dataset has a bigquery uri or raises ValueError."""
61
+ if (
62
+ not hasattr(multimodal_dataset, "metadata")
63
+ or multimodal_dataset.metadata is None
64
+ ):
65
+ raise ValueError("Multimodal dataset metadata is required.")
66
+ if (
67
+ not hasattr(multimodal_dataset.metadata, "input_config")
68
+ or multimodal_dataset.metadata.input_config is None
69
+ ):
70
+ raise ValueError("Multimodal dataset input config is required.")
71
+ if (
72
+ not hasattr(multimodal_dataset.metadata.input_config, "bigquery_source")
73
+ or multimodal_dataset.metadata.input_config.bigquery_source is None
74
+ ):
75
+ raise ValueError("Multimodal dataset input config bigquery source is required.")
76
+ if (
77
+ not hasattr(multimodal_dataset.metadata.input_config.bigquery_source, "uri")
78
+ or multimodal_dataset.metadata.input_config.bigquery_source.uri is None
79
+ ):
80
+ raise ValueError(
81
+ "Multimodal dataset input config bigquery source uri is required."
82
+ )
83
+ if not str(multimodal_dataset.metadata.input_config.bigquery_source.uri).startswith(
84
+ "bq://"
85
+ ):
86
+ raise ValueError(
87
+ "Multimodal dataset bigquery source uri must start with 'bq://'."
88
+ )
89
+
90
+
91
+ def _try_import_bigframes() -> Any:
92
+ """Tries to import `bigframes`."""
93
+ try:
94
+ import bigframes
95
+ import bigframes.pandas
96
+ import bigframes.bigquery
97
+
98
+ return bigframes
99
+ except ImportError as exc:
100
+ raise ImportError(
101
+ "`bigframes` is not installed. Please call 'pip install bigframes'."
102
+ ) from exc
103
+
104
+
105
+ def _try_import_bigquery() -> Any:
106
+ """Tries to import `bigquery`."""
107
+ try:
108
+ from google.cloud import bigquery
109
+
110
+ return bigquery
111
+ except ImportError as exc:
112
+ raise ImportError(
113
+ "`bigquery` is not installed. Please call 'pip install"
114
+ " google-cloud-bigquery'."
115
+ ) from exc
116
+
117
+
118
+ def _bq_dataset_location_allowed(
119
+ vertex_location: str, bq_dataset_location: str
120
+ ) -> bool:
121
+ if bq_dataset_location == vertex_location:
122
+ return True
123
+ if bq_dataset_location in _BQ_MULTIREGIONS:
124
+ return vertex_location.startswith(bq_dataset_location)
125
+ return False
126
+
127
+
128
+ def _normalize_and_validate_table_id(
129
+ *,
130
+ table_id: str,
131
+ project: str,
132
+ location: str,
133
+ credentials: google.auth.credentials.Credentials,
134
+ ) -> str:
135
+ bigquery = _try_import_bigquery()
136
+
137
+ table_ref = bigquery.TableReference.from_string(table_id, default_project=project)
138
+ if table_ref.project != project:
139
+ raise ValueError(
140
+ "The BigQuery table "
141
+ f"`{table_ref.project}.{table_ref.dataset_id}.{table_ref.table_id}`"
142
+ " must be in the same project as the multimodal dataset."
143
+ f" The multimodal dataset is in `{project}`, but the BigQuery table"
144
+ f" is in `{table_ref.project}`."
145
+ )
146
+
147
+ dataset_ref = bigquery.DatasetReference(
148
+ project=table_ref.project, dataset_id=table_ref.dataset_id
149
+ )
150
+ client = bigquery.Client(project=project, credentials=credentials)
151
+ bq_dataset = client.get_dataset(dataset_ref=dataset_ref)
152
+ if not _bq_dataset_location_allowed(location, bq_dataset.location):
153
+ raise ValueError(
154
+ "The BigQuery dataset"
155
+ f" `{dataset_ref.project}.{dataset_ref.dataset_id}` must be in the"
156
+ " same location as the multimodal dataset. The multimodal dataset"
157
+ f" is in `{location}`, but the BigQuery dataset is in"
158
+ f" `{bq_dataset.location}`."
159
+ )
160
+ return f"{table_ref.project}.{table_ref.dataset_id}.{table_ref.table_id}"
161
+
162
+
163
+ async def _normalize_and_validate_table_id_async(
164
+ *,
165
+ table_id: str,
166
+ project: str,
167
+ location: str,
168
+ credentials: google.auth.credentials.Credentials,
169
+ ) -> str:
170
+ bigquery = _try_import_bigquery()
171
+
172
+ table_ref = bigquery.TableReference.from_string(table_id, default_project=project)
173
+ if table_ref.project != project:
174
+ raise ValueError(
175
+ "The BigQuery table "
176
+ f"`{table_ref.project}.{table_ref.dataset_id}.{table_ref.table_id}`"
177
+ " must be in the same project as the multimodal dataset."
178
+ f" The multimodal dataset is in `{project}`, but the BigQuery table"
179
+ f" is in `{table_ref.project}`."
180
+ )
181
+
182
+ dataset_ref = bigquery.DatasetReference(
183
+ project=table_ref.project, dataset_id=table_ref.dataset_id
184
+ )
185
+ client = bigquery.Client(project=project, credentials=credentials)
186
+ bq_dataset = await asyncio.to_thread(client.get_dataset, dataset_ref=dataset_ref)
187
+ if not _bq_dataset_location_allowed(location, bq_dataset.location):
188
+ raise ValueError(
189
+ "The BigQuery dataset"
190
+ f" `{dataset_ref.project}.{dataset_ref.dataset_id}` must be in the"
191
+ " same location as the multimodal dataset. The multimodal dataset"
192
+ f" is in `{location}`, but the BigQuery dataset is in"
193
+ f" `{bq_dataset.location}`."
194
+ )
195
+ return f"{table_ref.project}.{table_ref.dataset_id}.{table_ref.table_id}"
196
+
197
+
198
+ def _create_default_bigquery_dataset_if_not_exists(
199
+ *,
200
+ project: str,
201
+ location: str,
202
+ credentials: google.auth.credentials.Credentials,
203
+ ) -> str:
204
+ bigquery = _try_import_bigquery()
205
+
206
+ bigquery_client = bigquery.Client(project=project, credentials=credentials)
207
+ location_str = location.lower().replace("-", "_")
208
+ dataset_id = bigquery.DatasetReference(
209
+ project, f"{_DEFAULT_BQ_DATASET_PREFIX}_{location_str}"
210
+ )
211
+ dataset = bigquery.Dataset(dataset_ref=dataset_id)
212
+ dataset.location = location
213
+ bigquery_client.create_dataset(dataset, exists_ok=True)
214
+ return f"{dataset_id.project}.{dataset_id.dataset_id}"
215
+
216
+
217
+ async def _create_default_bigquery_dataset_if_not_exists_async(
218
+ *,
219
+ project: str,
220
+ location: str,
221
+ credentials: google.auth.credentials.Credentials,
222
+ ) -> str:
223
+ bigquery = _try_import_bigquery()
224
+
225
+ bigquery_client = bigquery.Client(project=project, credentials=credentials)
226
+ location_str = location.lower().replace("-", "_")
227
+ dataset_id = bigquery.DatasetReference(
228
+ project, f"{_DEFAULT_BQ_DATASET_PREFIX}_{location_str}"
229
+ )
230
+ dataset = bigquery.Dataset(dataset_ref=dataset_id)
231
+ dataset.location = location
232
+ await asyncio.to_thread(bigquery_client.create_dataset, dataset, exists_ok=True)
233
+ return f"{dataset_id.project}.{dataset_id.dataset_id}"
234
+
235
+
236
+ def _generate_target_table_id(dataset_id: str) -> str:
237
+ return f"{dataset_id}.{_DEFAULT_BQ_TABLE_PREFIX}_{str(uuid.uuid4())}"
238
+
239
+
240
+ def generate_multimodal_dataset_display_name() -> str:
241
+ """Generates a display name with a timestamp."""
242
+ return f"MultimodalDataset {datetime.datetime.now().isoformat(sep=' ')}"
243
+
244
+
245
+ def save_dataframe_to_bigquery(
246
+ dataframe: "bigframes.pandas.DataFrame", # type: ignore # noqa: F821
247
+ target_table_id: str,
248
+ bq_client: "bigquery.Client", # type: ignore # noqa: F821
249
+ ) -> None:
250
+ # `to_gbq` does not support cross-region use cases. We use `copy_table` as a workaround.
251
+ temp_table_id = dataframe.to_gbq()
252
+ copy_job = bq_client.copy_table(
253
+ sources=temp_table_id,
254
+ destination=target_table_id,
255
+ )
256
+ copy_job.result()
257
+ bq_client.delete_table(temp_table_id)
258
+
259
+
260
+ async def save_dataframe_to_bigquery_async(
261
+ dataframe: "bigframes.pandas.DataFrame", # type: ignore # noqa: F821
262
+ target_table_id: str,
263
+ bq_client: "bigquery.Client", # type: ignore # noqa: F821
264
+ ) -> None:
265
+ # `to_gbq` does not support cross-region use cases. We use `copy_table` as a workaround.
266
+ temp_table_id = await asyncio.to_thread(dataframe.to_gbq)
267
+ copy_job = await asyncio.to_thread(
268
+ bq_client.copy_table,
269
+ sources=temp_table_id,
270
+ destination=target_table_id,
271
+ )
272
+ await asyncio.to_thread(copy_job.result)
273
+ await asyncio.to_thread(bq_client.delete_table, temp_table_id)
274
+
275
+
276
+ def resolve_dataset_name(resource_name_or_id: str, project: str, location: str) -> str:
277
+ """Resolves a dataset name or ID to a full resource name."""
278
+ if "/" not in resource_name_or_id:
279
+ return f"projects/{project}/locations/{location}/datasets/{resource_name_or_id}"
280
+ return resource_name_or_id
data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/_evals_common.py ADDED
The diff for this file is too large to render. See raw diff
 
data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/_evals_constant.py ADDED
@@ -0,0 +1,78 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2025 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
+ """Constants for evals module."""
16
+
17
+ SUPPORTED_PREDEFINED_METRICS = frozenset(
18
+ {
19
+ "general_quality_v1",
20
+ "text_quality_v1",
21
+ "instruction_following_v1",
22
+ "grounding_v1",
23
+ "safety_v1",
24
+ "multi_turn_general_quality_v1",
25
+ "multi_turn_text_quality_v1",
26
+ "multi_turn_tool_use_quality_v1",
27
+ "multi_turn_trajectory_quality_v1",
28
+ "multi_turn_task_success_v1",
29
+ "final_response_match_v2",
30
+ "final_response_reference_free_v1",
31
+ "final_response_quality_v1",
32
+ "hallucination_v1",
33
+ "tool_use_quality_v1",
34
+ "gecko_text2image_v1",
35
+ "gecko_text2video_v1",
36
+ }
37
+ )
38
+
39
+ SUPPORTED_VERTEX_MAAS_MODEL_PREFIXES = frozenset(
40
+ {
41
+ "meta/", # Meta/Llama
42
+ "deepseek-ai/", # DeepSeek AI
43
+ "qwen/", # Qwen
44
+ "openai/", # OpenAI (GPT-OSS)
45
+ "claude-", # Anthropic (Claude)
46
+ "mistral-", # Mistral AI
47
+ "jamba-", # AI21 (Jamba)
48
+ }
49
+ )
50
+ INTERMEDIATE_EVENTS = "intermediate_events"
51
+ RESPONSE = "response"
52
+ PROMPT = "prompt"
53
+ REFERENCE = "reference"
54
+ SESSION_INPUT = "session_inputs"
55
+ CONTEXT = "context"
56
+ CONTENT = "content"
57
+ PARTS = "parts"
58
+ USER_AUTHOR = "user"
59
+ AGENT_DATA = "agent_data"
60
+ STARTING_PROMPT = "starting_prompt"
61
+ CONVERSATION_PLAN = "conversation_plan"
62
+ HISTORY = "history"
63
+ CONVERSATION_HISTORY = "conversation_history"
64
+
65
+ COMMON_DATASET_COLUMNS = frozenset(
66
+ {
67
+ INTERMEDIATE_EVENTS,
68
+ PROMPT,
69
+ REFERENCE,
70
+ SESSION_INPUT,
71
+ CONTEXT,
72
+ HISTORY,
73
+ CONVERSATION_HISTORY,
74
+ STARTING_PROMPT,
75
+ CONVERSATION_PLAN,
76
+ AGENT_DATA,
77
+ }
78
+ )
data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/_evals_data_converters.py ADDED
@@ -0,0 +1,918 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2025 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
+ """Dataset converters for evals."""
16
+
17
+ import copy
18
+ import json
19
+ import logging
20
+ from typing import Any, Optional, Union
21
+
22
+ from google.genai import _common
23
+ from google.genai import types as genai_types
24
+ from pydantic import ValidationError
25
+ from typing_extensions import override
26
+
27
+ from . import _evals_utils
28
+ from . import _observability_data_converter
29
+ from . import types
30
+
31
+
32
+ logger = logging.getLogger("agentplatform_genai._evals_data_converters")
33
+
34
+
35
+ class EvalDatasetSchema(_common.CaseInSensitiveEnum):
36
+ """Represents the schema of an evaluation dataset."""
37
+
38
+ GEMINI = "gemini"
39
+ FLATTEN = "flatten"
40
+ OPENAI = "openai"
41
+ OBSERVABILITY = "observability"
42
+ UNKNOWN = "unknown"
43
+
44
+
45
+ _PLACEHOLDER_RESPONSE_TEXT = "Error: Missing response for this candidate"
46
+
47
+
48
+ def _create_placeholder_response_candidate(
49
+ text: str = _PLACEHOLDER_RESPONSE_TEXT,
50
+ ) -> types.ResponseCandidate:
51
+ """Creates a ResponseCandidate with placeholder text."""
52
+ return types.ResponseCandidate(
53
+ response=genai_types.Content(parts=[genai_types.Part(text=text)])
54
+ )
55
+
56
+
57
+ class _GeminiEvalDataConverter(_evals_utils.EvalDataConverter):
58
+ """Converter for dataset in the Gemini format."""
59
+
60
+ def _parse_request(self, request_data: dict[str, Any]) -> tuple[
61
+ genai_types.Content,
62
+ genai_types.Content,
63
+ list[types.evals.Message],
64
+ types.ResponseCandidate,
65
+ ]:
66
+ """Parses a request from a Gemini dataset."""
67
+ system_instruction = genai_types.Content()
68
+ prompt = genai_types.Content()
69
+ reference = types.ResponseCandidate()
70
+ conversation_history = []
71
+
72
+ if "system_instruction" in request_data:
73
+ system_instruction = genai_types.Content.model_validate(
74
+ request_data["system_instruction"]
75
+ )
76
+ for turn_id, content_dict in enumerate(request_data.get("contents", [])):
77
+ if not isinstance(content_dict, dict):
78
+ raise TypeError(
79
+ "Expected a dictionary for content at turn %s, but got %s: %s"
80
+ % (turn_id, type(content_dict).__name__, content_dict)
81
+ )
82
+ if "parts" not in content_dict:
83
+ raise ValueError(
84
+ "Missing 'parts' key in content structure at turn %s: %s"
85
+ % (turn_id, content_dict)
86
+ )
87
+ conversation_history.append(
88
+ types.evals.Message(
89
+ turn_id=str(turn_id),
90
+ content=genai_types.Content.model_validate(content_dict),
91
+ )
92
+ )
93
+ if conversation_history:
94
+ last_message = conversation_history.pop()
95
+ last_message_role = (
96
+ last_message.content.role if last_message.content else "user"
97
+ )
98
+ if last_message_role in ["user", None]:
99
+ prompt = (
100
+ last_message.content
101
+ if last_message.content
102
+ else genai_types.Content()
103
+ )
104
+ elif last_message_role == "model":
105
+ reference = types.ResponseCandidate(response=last_message.content)
106
+ if conversation_history:
107
+ second_to_last_message = conversation_history.pop()
108
+ prompt = (
109
+ second_to_last_message.content
110
+ if second_to_last_message.content
111
+ else genai_types.Content()
112
+ )
113
+ else:
114
+ prompt = genai_types.Content()
115
+
116
+ return prompt, system_instruction, conversation_history, reference
117
+
118
+ @override
119
+ def convert(self, raw_data: list[dict[str, Any]]) -> types.EvaluationDataset:
120
+ """Converts a list of raw data into an EvaluationDataset."""
121
+ eval_cases = []
122
+
123
+ for i, item in enumerate(raw_data):
124
+ eval_case_id = "gemini_eval_case_%s" % i
125
+ request_data = item.get("request", {})
126
+ response_data = item.get("response", {})
127
+
128
+ (
129
+ prompt,
130
+ system_instruction,
131
+ conversation_history,
132
+ reference,
133
+ ) = self._parse_request(request_data)
134
+
135
+ responses = []
136
+ if isinstance(response_data, str):
137
+ responses.append(
138
+ types.ResponseCandidate(
139
+ response=genai_types.Content(
140
+ parts=[genai_types.Part(text=response_data)]
141
+ )
142
+ )
143
+ )
144
+ elif isinstance(response_data, dict):
145
+ try:
146
+ generate_content_response = (
147
+ genai_types.GenerateContentResponse.model_validate(
148
+ response_data
149
+ )
150
+ )
151
+ if generate_content_response.candidates:
152
+ candidate = generate_content_response.candidates[0]
153
+ if candidate.content:
154
+ responses.append(
155
+ types.ResponseCandidate(
156
+ response=genai_types.Content.model_validate(
157
+ candidate.content
158
+ )
159
+ )
160
+ )
161
+ else:
162
+ responses.append(_create_placeholder_response_candidate())
163
+ except Exception:
164
+ responses.append(_create_placeholder_response_candidate())
165
+ else:
166
+ responses.append(_create_placeholder_response_candidate())
167
+
168
+ eval_case = types.EvalCase(
169
+ eval_case_id=eval_case_id,
170
+ prompt=prompt,
171
+ responses=responses,
172
+ reference=reference,
173
+ system_instruction=system_instruction,
174
+ conversation_history=conversation_history,
175
+ )
176
+ eval_cases.append(eval_case)
177
+
178
+ return types.EvaluationDataset(eval_cases=eval_cases)
179
+
180
+
181
+ class _FlattenEvalDataConverter(_evals_utils.EvalDataConverter):
182
+ """Converter for datasets in a structured table format."""
183
+
184
+ def convert(self, raw_data: list[dict[str, Any]]) -> types.EvaluationDataset:
185
+ """Converts a list of raw data into an EvaluationDataset."""
186
+ eval_cases = []
187
+ for i, item_dict in enumerate(raw_data):
188
+ if not isinstance(item_dict, dict):
189
+ raise TypeError(
190
+ "Expected a dictionary for item at index %s, but got %s: %s"
191
+ % (i, type(item_dict).__name__, item_dict)
192
+ )
193
+ item = copy.deepcopy(item_dict)
194
+ eval_case_id = "eval_case_%s" % i
195
+ prompt_data = item.pop("prompt", None)
196
+ if not prompt_data:
197
+ prompt_data = item.pop("source", None)
198
+
199
+ conversation_history_data = item.pop("conversation_history", None)
200
+ if conversation_history_data is None:
201
+ conversation_history_data = item.pop("history", None)
202
+ response_data = item.pop("response", None)
203
+ reference_data = item.pop("reference", None)
204
+ system_instruction_data = item.pop("instruction", None)
205
+ rubric_groups_data = item.pop("rubric_groups", None)
206
+ intermediate_events_data = item.pop("intermediate_events", None)
207
+ agent_data_raw = item.pop("agent_data", None)
208
+
209
+ if not response_data and not agent_data_raw:
210
+ raise ValueError(
211
+ "Response is required but missing for %s." % eval_case_id
212
+ )
213
+ if not prompt_data and not agent_data_raw:
214
+ raise ValueError(
215
+ "Prompt is required but missing for %s." % eval_case_id
216
+ )
217
+
218
+ prompt: Optional[genai_types.Content] = None
219
+ if isinstance(prompt_data, str):
220
+ prompt = genai_types.Content(parts=[genai_types.Part(text=prompt_data)])
221
+ elif isinstance(prompt_data, dict):
222
+ prompt = genai_types.Content.model_validate(prompt_data)
223
+ elif isinstance(prompt_data, genai_types.Content):
224
+ prompt = prompt_data
225
+ elif not agent_data_raw:
226
+ raise ValueError(
227
+ "Invalid prompt type for case %s: %s" % (i, type(prompt_data))
228
+ )
229
+
230
+ conversation_history: Optional[list[types.evals.Message]] = None
231
+ if isinstance(conversation_history_data, list):
232
+ conversation_history = []
233
+ for turn_id, content in enumerate(conversation_history_data):
234
+ if isinstance(content, genai_types.Content):
235
+ conversation_history.append(
236
+ types.evals.Message(
237
+ turn_id=str(turn_id),
238
+ content=content,
239
+ )
240
+ )
241
+ elif isinstance(content, dict):
242
+ try:
243
+ validated_content = genai_types.Content.model_validate(
244
+ content
245
+ )
246
+ conversation_history.append(
247
+ types.evals.Message(
248
+ turn_id=str(turn_id),
249
+ content=validated_content,
250
+ )
251
+ )
252
+ except ValidationError as e:
253
+ logger.warning(
254
+ "Item at index %s in 'history' column for case "
255
+ " %s is a dict but could not be validated as"
256
+ " genai_types.Content: %s",
257
+ turn_id,
258
+ eval_case_id,
259
+ e,
260
+ )
261
+ else:
262
+ logger.warning(
263
+ "Invalid type in 'history' column for case %s at index %s. "
264
+ "Expected genai_types.Content or dict, but got %s. "
265
+ "Skipping this history item.",
266
+ eval_case_id,
267
+ turn_id,
268
+ type(content),
269
+ )
270
+
271
+ responses: Optional[list[types.ResponseCandidate]] = None
272
+ if isinstance(response_data, dict):
273
+ responses = [
274
+ types.ResponseCandidate(
275
+ response=genai_types.Content.model_validate(response_data)
276
+ )
277
+ ]
278
+ elif isinstance(response_data, str):
279
+ responses = [
280
+ types.ResponseCandidate(
281
+ response=genai_types.Content(
282
+ parts=[genai_types.Part(text=response_data)]
283
+ )
284
+ )
285
+ ]
286
+ elif isinstance(response_data, genai_types.Content):
287
+ responses = [types.ResponseCandidate(response=response_data)]
288
+ elif not agent_data_raw:
289
+ raise ValueError(
290
+ "Invalid response type for case %s: %s" % (i, type(response_data))
291
+ )
292
+
293
+ reference: Optional[types.ResponseCandidate] = None
294
+ if reference_data:
295
+ if isinstance(reference_data, dict):
296
+ reference = types.ResponseCandidate(
297
+ response=genai_types.Content.model_validate(reference_data)
298
+ )
299
+ elif isinstance(reference_data, str):
300
+ reference = types.ResponseCandidate(
301
+ response=genai_types.Content(
302
+ parts=[genai_types.Part(text=reference_data)]
303
+ )
304
+ )
305
+ elif isinstance(reference_data, genai_types.Content):
306
+ reference = types.ResponseCandidate(response=reference_data)
307
+
308
+ system_instruction: Optional[genai_types.Content] = None
309
+ if system_instruction_data:
310
+ if isinstance(system_instruction_data, dict):
311
+ system_instruction = genai_types.Content.model_validate(
312
+ system_instruction_data
313
+ )
314
+ elif isinstance(system_instruction_data, str):
315
+ system_instruction = genai_types.Content(
316
+ parts=[genai_types.Part(text=system_instruction_data)]
317
+ )
318
+ elif isinstance(system_instruction_data, genai_types.Content):
319
+ system_instruction = system_instruction_data
320
+
321
+ rubric_groups: Optional[dict[str, types.RubricGroup]] = None
322
+ if rubric_groups_data:
323
+ if isinstance(rubric_groups_data, dict):
324
+ rubric_groups = {}
325
+ for key, value in rubric_groups_data.items():
326
+ if isinstance(value, list):
327
+ try:
328
+ validated_rubrics = [
329
+ (
330
+ types.evals.Rubric.model_validate(r)
331
+ if isinstance(r, dict)
332
+ else r
333
+ )
334
+ for r in value
335
+ ]
336
+ if all(
337
+ isinstance(r, types.evals.Rubric)
338
+ for r in validated_rubrics
339
+ ):
340
+ rubric_groups[key] = types.RubricGroup(
341
+ rubrics=validated_rubrics
342
+ )
343
+ else:
344
+ logger.warning(
345
+ "Invalid item type in rubric list for group '%s' in case %s.",
346
+ key,
347
+ i,
348
+ )
349
+ except Exception as e:
350
+ logger.warning(
351
+ "Failed to validate rubrics for group '%s' in case %s: %s",
352
+ key,
353
+ i,
354
+ e,
355
+ )
356
+ elif isinstance(value, types.RubricGroup):
357
+ rubric_groups[key] = value
358
+ elif isinstance(value, dict):
359
+ try:
360
+ rubric_groups[key] = types.RubricGroup.model_validate(
361
+ value
362
+ )
363
+ except Exception as e:
364
+ logger.warning(
365
+ "Failed to validate RubricGroup dict for group '%s' in case %s: %s",
366
+ key,
367
+ i,
368
+ e,
369
+ )
370
+ else:
371
+ logger.warning(
372
+ "Invalid type for rubric group '%s' in case %s."
373
+ " Expected list of rubrics, dict, or RubricGroup.",
374
+ key,
375
+ i,
376
+ )
377
+ else:
378
+ logger.warning(
379
+ "Invalid type for rubric_groups in case %s. Expected dict.",
380
+ i,
381
+ )
382
+
383
+ intermediate_events: Optional[list[types.evals.Event]] = None
384
+ if intermediate_events_data:
385
+ if isinstance(intermediate_events_data, list):
386
+ intermediate_events = []
387
+ for event in intermediate_events_data:
388
+ if isinstance(event, dict):
389
+ try:
390
+ validated_event = types.evals.Event.model_validate(
391
+ event
392
+ )
393
+ intermediate_events.append(validated_event)
394
+ except Exception as e:
395
+ logger.warning(
396
+ "Failed to validate intermediate event dict for"
397
+ " case %s: %s",
398
+ i,
399
+ e,
400
+ )
401
+ elif isinstance(event, types.evals.Event):
402
+ intermediate_events.append(event)
403
+ else:
404
+ logger.warning(
405
+ "Invalid type for intermediate_event in case"
406
+ " %s. Expected list of dicts or list of"
407
+ " types.evals.Event objects.",
408
+ i,
409
+ )
410
+ else:
411
+ logger.warning(
412
+ "Invalid type for intermediate_events in case %s. Expected"
413
+ " list of types.evals.Event objects.",
414
+ i,
415
+ )
416
+
417
+ agent_data: Optional[types.evals.AgentData] = None
418
+ if agent_data_raw:
419
+ if isinstance(agent_data_raw, str):
420
+ try:
421
+ agent_data_dict = json.loads(agent_data_raw)
422
+ agent_data = types.evals.AgentData.model_validate(
423
+ agent_data_dict
424
+ )
425
+ except json.JSONDecodeError:
426
+ logger.warning(
427
+ "Could not decode agent_data JSON string for case %s.", i
428
+ )
429
+ except ValidationError as e:
430
+ logger.warning(
431
+ "Failed to validate agent_data for case %s: %s", i, e
432
+ )
433
+ elif isinstance(agent_data_raw, dict):
434
+ try:
435
+ agent_data = types.evals.AgentData.model_validate(
436
+ agent_data_raw
437
+ )
438
+ except ValidationError as e:
439
+ logger.warning(
440
+ "Failed to validate agent_data for case %s: %s", i, e
441
+ )
442
+ elif isinstance(agent_data_raw, types.evals.AgentData):
443
+ agent_data = agent_data_raw
444
+ else:
445
+ logger.warning(
446
+ "Invalid type for agent_data in case %s. Expected str, dict"
447
+ " or types.evals.AgentData object. Got %s",
448
+ i,
449
+ type(agent_data_raw),
450
+ )
451
+
452
+ eval_case = types.EvalCase(
453
+ eval_case_id=eval_case_id,
454
+ prompt=prompt,
455
+ responses=responses,
456
+ reference=reference,
457
+ conversation_history=conversation_history,
458
+ system_instruction=system_instruction,
459
+ rubric_groups=rubric_groups,
460
+ intermediate_events=intermediate_events,
461
+ agent_data=agent_data,
462
+ **item, # Pass remaining columns as extra fields to EvalCase.
463
+ # They can be used for custom metric prompt templates.
464
+ )
465
+ eval_cases.append(eval_case)
466
+
467
+ return types.EvaluationDataset(eval_cases=eval_cases)
468
+
469
+
470
+ class _OpenAIDataConverter(_evals_utils.EvalDataConverter):
471
+ """Converter for dataset in OpenAI's Chat Completion format."""
472
+
473
+ def _parse_messages(self, messages: list[dict[str, Any]]) -> tuple[
474
+ Optional[genai_types.Content],
475
+ list[types.evals.Message],
476
+ Optional[genai_types.Content],
477
+ Optional[types.ResponseCandidate],
478
+ ]:
479
+ """Parses a list of messages into instruction, history, prompt, and reference."""
480
+ system_instruction = None
481
+ prompt = None
482
+ reference = None
483
+ conversation_history = []
484
+
485
+ if messages and messages[0].get("role") in ["system", "developer"]:
486
+ system_instruction = genai_types.Content(
487
+ parts=[genai_types.Part(text=messages[0].get("content"))]
488
+ )
489
+ messages = messages[1:]
490
+
491
+ for turn_id, msg in enumerate(messages):
492
+ role = msg.get("role", "user")
493
+ content = msg.get("content", "")
494
+ conversation_history.append(
495
+ types.evals.Message(
496
+ turn_id=str(turn_id),
497
+ content=genai_types.Content(
498
+ parts=[genai_types.Part(text=content)], role=role
499
+ ),
500
+ author=role,
501
+ )
502
+ )
503
+
504
+ if conversation_history:
505
+ last_message = conversation_history.pop()
506
+ if last_message.content and last_message.content.role == "user":
507
+ prompt = last_message.content
508
+ elif last_message.content and last_message.content.role == "assistant":
509
+ reference = types.ResponseCandidate(response=last_message.content)
510
+ if conversation_history:
511
+ second_to_last_message = conversation_history.pop()
512
+ prompt = second_to_last_message.content
513
+
514
+ return system_instruction, conversation_history, prompt, reference
515
+
516
+ @override
517
+ def convert(self, raw_data: list[dict[str, Any]]) -> types.EvaluationDataset:
518
+ """Converts a list of OpenAI ChatCompletion data into an EvaluationDataset."""
519
+ eval_cases = []
520
+ for i, item in enumerate(raw_data):
521
+ eval_case_id = "openai_eval_case_%s" % i
522
+
523
+ if "request" not in item or "response" not in item:
524
+ logger.warning(
525
+ "Skipping case %s due to missing 'request' or 'response' key.", i
526
+ )
527
+ continue
528
+
529
+ request_data = item.get("request", {})
530
+ response_data_raw = item.get("response", {})
531
+
532
+ response_data = {}
533
+ if isinstance(response_data_raw, str):
534
+ try:
535
+ loaded_json = json.loads(response_data_raw)
536
+ if isinstance(loaded_json, dict):
537
+ response_data = loaded_json
538
+ else:
539
+ logger.warning(
540
+ "Decoded response JSON is not a dictionary for case"
541
+ " %s. Type: %s",
542
+ i,
543
+ type(loaded_json),
544
+ )
545
+ except json.JSONDecodeError:
546
+ logger.warning(
547
+ "Could not decode response JSON string for case %s."
548
+ " Treating as empty response.",
549
+ i,
550
+ )
551
+ elif isinstance(response_data_raw, dict):
552
+ response_data = response_data_raw
553
+
554
+ messages = request_data.get("messages", [])
555
+ choices = response_data.get("choices", [])
556
+
557
+ (
558
+ system_instruction,
559
+ conversation_history,
560
+ prompt,
561
+ reference,
562
+ ) = self._parse_messages(messages)
563
+
564
+ if prompt is None and reference is None:
565
+ logger.warning(
566
+ "Could not determine a user prompt or reference for case %s."
567
+ " Skipping.",
568
+ i,
569
+ )
570
+ continue
571
+
572
+ responses = []
573
+ if (
574
+ choices
575
+ and isinstance(choices, list)
576
+ and isinstance(choices[0], dict)
577
+ and choices[0].get("message")
578
+ ):
579
+ response_content = choices[0]["message"].get("content", "")
580
+ responses.append(
581
+ types.ResponseCandidate(
582
+ response=genai_types.Content(
583
+ parts=[genai_types.Part(text=response_content)]
584
+ )
585
+ )
586
+ )
587
+ else:
588
+ responses.append(_create_placeholder_response_candidate())
589
+
590
+ other_fields = {
591
+ k: v for k, v in item.items() if k not in ["request", "response"]
592
+ }
593
+
594
+ eval_case = types.EvalCase(
595
+ eval_case_id=eval_case_id,
596
+ prompt=prompt,
597
+ responses=responses,
598
+ reference=reference,
599
+ system_instruction=system_instruction,
600
+ conversation_history=conversation_history,
601
+ **other_fields,
602
+ )
603
+ eval_cases.append(eval_case)
604
+
605
+ return types.EvaluationDataset(eval_cases=eval_cases)
606
+
607
+
608
+ def auto_detect_dataset_schema(
609
+ raw_dataset: list[dict[str, Any]],
610
+ ) -> Union[EvalDatasetSchema, str]:
611
+ """Detects the schema of a raw dataset."""
612
+ if not raw_dataset:
613
+ return EvalDatasetSchema.UNKNOWN
614
+
615
+ first_item = raw_dataset[0]
616
+ keys = set(first_item.keys())
617
+
618
+ if "format" in keys:
619
+ format_content = first_item.get("format", "")
620
+ if isinstance(format_content, str) and format_content == "observability":
621
+ return EvalDatasetSchema.OBSERVABILITY
622
+
623
+ if "request" in keys and "response" in keys:
624
+ request_content = first_item.get("request", {})
625
+ if isinstance(request_content, dict) and "contents" in request_content:
626
+ contents_list = request_content.get("contents")
627
+ if (
628
+ contents_list
629
+ and isinstance(contents_list, list)
630
+ and isinstance(contents_list[0], dict)
631
+ ):
632
+ if "parts" in contents_list[0]:
633
+ return EvalDatasetSchema.GEMINI
634
+
635
+ if "request" in keys and "response" in keys:
636
+ request_content = first_item.get("request", {})
637
+ if isinstance(request_content, dict) and "messages" in request_content:
638
+ messages_list = request_content.get("messages")
639
+ if (
640
+ messages_list
641
+ and isinstance(messages_list, list)
642
+ and isinstance(messages_list[0], dict)
643
+ ):
644
+ if "role" in messages_list[0] and "content" in messages_list[0]:
645
+ return EvalDatasetSchema.OPENAI
646
+
647
+ if "agent_data" in keys:
648
+ return EvalDatasetSchema.FLATTEN
649
+
650
+ if {"prompt", "response"}.issubset(keys) or {
651
+ "response",
652
+ "reference",
653
+ }.issubset(keys):
654
+ return EvalDatasetSchema.FLATTEN
655
+ else:
656
+ return EvalDatasetSchema.UNKNOWN
657
+
658
+
659
+ _CONVERTER_REGISTRY = {
660
+ EvalDatasetSchema.GEMINI: _GeminiEvalDataConverter,
661
+ EvalDatasetSchema.FLATTEN: _FlattenEvalDataConverter,
662
+ EvalDatasetSchema.OPENAI: _OpenAIDataConverter,
663
+ EvalDatasetSchema.OBSERVABILITY: _observability_data_converter.ObservabilityDataConverter,
664
+ }
665
+
666
+
667
+ def get_dataset_converter(
668
+ dataset_schema: EvalDatasetSchema,
669
+ ) -> _evals_utils.EvalDataConverter:
670
+ """Returns the appropriate dataset converter for the given schema."""
671
+ if dataset_schema in _CONVERTER_REGISTRY:
672
+ return _CONVERTER_REGISTRY[dataset_schema]() # type: ignore[abstract]
673
+ else:
674
+ raise ValueError("Unsupported dataset schema: %s" % dataset_schema)
675
+
676
+
677
+ def _get_content_text(content: genai_types.Content) -> str:
678
+ """Safely extracts text from all parts of a content.
679
+
680
+ If the content has multiple parts, text from all parts is concatenated.
681
+ If a part is not text, it is ignored. If no text parts are found,
682
+ an empty string is returned.
683
+ """
684
+ text_parts = []
685
+ if (
686
+ content
687
+ and hasattr(content, "parts")
688
+ and isinstance(content.parts, list)
689
+ and content.parts
690
+ ):
691
+ for part in content.parts:
692
+ if hasattr(part, "text") and part.text is not None:
693
+ text_parts.append(str(part.text))
694
+ return "".join(text_parts)
695
+
696
+
697
+ def _get_text_from_reference(
698
+ reference: Optional[types.ResponseCandidate],
699
+ ) -> Optional[str]:
700
+ """Safely extracts text from a reference field."""
701
+ if reference and hasattr(reference, "response") and reference.response:
702
+ return _get_content_text(reference.response)
703
+ return None
704
+
705
+
706
+ def _validate_case_consistency(
707
+ base_case: types.EvalCase,
708
+ current_case: types.EvalCase,
709
+ case_idx: int,
710
+ dataset_idx: int,
711
+ ) -> None:
712
+ """Logs warnings if prompt or reference mismatches occur."""
713
+ if base_case.prompt != current_case.prompt:
714
+ base_prompt_text_preview = _get_content_text(base_case.prompt)[:50]
715
+ current_prompt_text_preview = _get_content_text(current_case.prompt)[:50]
716
+ logger.warning(
717
+ "Prompt mismatch for case index %d between base dataset (0)"
718
+ " and dataset %d. Using prompt from base. Base prompt"
719
+ " preview: '%s...', Dataset"
720
+ " %d prompt preview: '%s...'",
721
+ case_idx,
722
+ dataset_idx,
723
+ base_prompt_text_preview,
724
+ dataset_idx,
725
+ current_prompt_text_preview,
726
+ )
727
+
728
+ base_ref_text = _get_text_from_reference(base_case.reference)
729
+ current_ref_text = _get_text_from_reference(current_case.reference)
730
+
731
+ if bool(base_case.reference) != bool(current_case.reference):
732
+ logger.warning(
733
+ "Reference presence mismatch for case index %d between base"
734
+ " dataset (0) and dataset %d. Using reference (or lack"
735
+ " thereof) from base.",
736
+ case_idx,
737
+ dataset_idx,
738
+ )
739
+ elif base_ref_text != current_ref_text:
740
+ logger.warning(
741
+ "Reference text mismatch for case index %d between base"
742
+ " dataset (0) and dataset %d. Using reference from base. "
743
+ " Base ref: '%s...', Current ref:"
744
+ " '%s...'",
745
+ case_idx,
746
+ dataset_idx,
747
+ str(base_ref_text)[:50],
748
+ str(current_ref_text)[:50],
749
+ )
750
+
751
+
752
+ def merge_evaluation_datasets(
753
+ datasets: list[types.EvaluationDataset],
754
+ agent_info: Optional[types.evals.AgentInfo] = None,
755
+ ) -> types.EvaluationDataset:
756
+ """Merges multiple EvaluationDatasets into a single EvaluationDataset.
757
+
758
+ Assumes that each dataset has responses corresponding to the same set of
759
+ prompts, in the same order. The prompt, reference, system_instruction, and
760
+ conversation_history are taken from the first dataset.
761
+ """
762
+ if not datasets:
763
+ raise ValueError("Input 'datasets' cannot be empty.")
764
+
765
+ num_expected_cases = 0
766
+ if datasets[0].eval_cases:
767
+ num_expected_cases = len(datasets[0].eval_cases)
768
+
769
+ if num_expected_cases == 0:
770
+ logger.warning(
771
+ "The first dataset has no evaluation cases. Result will be empty."
772
+ )
773
+ return types.EvaluationDataset(eval_cases=[])
774
+
775
+ for i, ds in enumerate(datasets):
776
+ current_len = len(ds.eval_cases) if ds.eval_cases else 0
777
+ if current_len != num_expected_cases:
778
+ raise ValueError(
779
+ "All datasets must have the same number of evaluation cases. "
780
+ "Base dataset (0) has %s, but dataset %s has %s."
781
+ % (num_expected_cases, i, current_len)
782
+ )
783
+
784
+ merged_eval_cases: list[types.EvalCase] = []
785
+ base_parsed_dataset = datasets[0]
786
+
787
+ for case_idx in range(num_expected_cases):
788
+ base_eval_case: types.EvalCase = (
789
+ base_parsed_dataset.eval_cases[case_idx]
790
+ if base_parsed_dataset.eval_cases
791
+ else types.EvalCase()
792
+ )
793
+ candidate_responses: list[types.ResponseCandidate] = []
794
+
795
+ if base_eval_case.responses:
796
+ candidate_responses.append(base_eval_case.responses[0])
797
+ elif base_eval_case.agent_data:
798
+ candidate_responses.append(_create_placeholder_response_candidate(""))
799
+ else:
800
+ logger.warning(
801
+ "No response or agent data found for base dataset (index 0) in case %s. "
802
+ "Adding placeholder.",
803
+ case_idx,
804
+ )
805
+ candidate_responses.append(
806
+ _create_placeholder_response_candidate(
807
+ "Missing response from base dataset (0) for case %s" % case_idx
808
+ )
809
+ )
810
+
811
+ eval_case_custom_columns = base_eval_case.model_dump(
812
+ exclude={
813
+ "eval_case_id",
814
+ "prompt",
815
+ "responses",
816
+ "reference",
817
+ "system_instruction",
818
+ "conversation_history",
819
+ "intermediate_events",
820
+ "agent_data",
821
+ "agent_info",
822
+ },
823
+ exclude_none=True,
824
+ )
825
+ for dataset_idx_offset, current_parsed_ds in enumerate(datasets[1:], start=1):
826
+ current_ds_eval_case: types.EvalCase = (
827
+ current_parsed_ds.eval_cases[case_idx]
828
+ if current_parsed_ds.eval_cases
829
+ else types.EvalCase()
830
+ )
831
+
832
+ _validate_case_consistency(
833
+ base_eval_case, current_ds_eval_case, case_idx, dataset_idx_offset
834
+ )
835
+
836
+ current_ds_extra_attrs = current_ds_eval_case.model_dump(
837
+ exclude={
838
+ "eval_case_id",
839
+ "prompt",
840
+ "responses",
841
+ "reference",
842
+ "system_instruction",
843
+ "conversation_history",
844
+ "intermediate_events",
845
+ "agent_data",
846
+ "agent_info",
847
+ },
848
+ exclude_none=True,
849
+ )
850
+ eval_case_custom_columns.update(current_ds_extra_attrs)
851
+
852
+ if current_ds_eval_case.responses:
853
+ candidate_responses.append(current_ds_eval_case.responses[0])
854
+ elif current_ds_eval_case.agent_data:
855
+ candidate_responses.append(_create_placeholder_response_candidate(""))
856
+ else:
857
+ logger.warning(
858
+ "No response or agent data found for dataset %s in case %s. Adding"
859
+ " placeholder.",
860
+ dataset_idx_offset,
861
+ case_idx,
862
+ )
863
+ candidate_responses.append(
864
+ _create_placeholder_response_candidate(
865
+ "Missing response from dataset %s for case %s"
866
+ % (dataset_idx_offset, case_idx)
867
+ )
868
+ )
869
+
870
+ merged_case = types.EvalCase(
871
+ eval_case_id=base_eval_case.eval_case_id
872
+ or "merged_eval_case_%s" % case_idx,
873
+ prompt=base_eval_case.prompt,
874
+ responses=candidate_responses if candidate_responses else None,
875
+ reference=base_eval_case.reference,
876
+ system_instruction=base_eval_case.system_instruction,
877
+ conversation_history=base_eval_case.conversation_history,
878
+ agent_info=agent_info or base_eval_case.agent_info,
879
+ agent_data=base_eval_case.agent_data,
880
+ intermediate_events=base_eval_case.intermediate_events,
881
+ **eval_case_custom_columns,
882
+ )
883
+ merged_eval_cases.append(merged_case)
884
+
885
+ return types.EvaluationDataset(eval_cases=merged_eval_cases)
886
+
887
+
888
+ def merge_response_datasets_into_canonical_format(
889
+ raw_datasets: list[list[dict[str, Any]]],
890
+ schemas: list[str],
891
+ agent_info: Optional[types.evals.AgentInfo] = None,
892
+ ) -> types.EvaluationDataset:
893
+ """Merges multiple raw response datasets into a single EvaluationDataset.
894
+
895
+ Assumes that each dataset in raw_datasets has responses corresponding
896
+ to the same set of prompts, in the same order. The prompt, reference,
897
+ system_instruction, and conversation_history are taken from the first dataset.
898
+ """
899
+ if not isinstance(raw_datasets, list):
900
+ raise TypeError(
901
+ "Input 'raw_datasets' must be a list, got %s." % type(raw_datasets)
902
+ )
903
+ if not raw_datasets or not all(isinstance(ds, list) for ds in raw_datasets):
904
+ raise ValueError(
905
+ "Input 'raw_datasets' cannot be empty and must be a list of lists."
906
+ )
907
+ if not schemas or len(schemas) != len(raw_datasets):
908
+ raise ValueError(
909
+ "A list of schemas must be provided, one for each raw dataset. "
910
+ "Got %s schemas for %s datasets." % (len(schemas), len(raw_datasets))
911
+ )
912
+
913
+ parsed_evaluation_datasets: list[types.EvaluationDataset] = []
914
+ for i, (raw_ds_entry, schema) in enumerate(zip(raw_datasets, schemas)):
915
+ converter = get_dataset_converter(schema)
916
+ parsed_evaluation_datasets.append(converter.convert(raw_ds_entry))
917
+
918
+ return merge_evaluation_datasets(parsed_evaluation_datasets, agent_info)
data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/_evals_metric_handlers.py ADDED
@@ -0,0 +1,1755 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2025 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
+ """Handlers for computing evaluation metrics."""
16
+
17
+ import abc
18
+ import collections
19
+ from concurrent import futures
20
+ import json
21
+ import logging
22
+ import random
23
+ import statistics
24
+ import time
25
+ from typing import Any, Callable, Generic, Optional, TypeVar, Union
26
+
27
+ from google.genai import errors as genai_errors
28
+ from google.genai import _common
29
+ from google.genai import types as genai_types
30
+ from tqdm import tqdm
31
+ from typing_extensions import override
32
+
33
+ from . import _evals_common
34
+ from . import _evals_constant
35
+ from . import _evals_utils
36
+ from . import evals
37
+ from . import types
38
+
39
+
40
+ logger = logging.getLogger(__name__)
41
+ _MAX_RETRIES = 5
42
+ # HTTP status codes that are safe to retry with backoff.
43
+ _RETRYABLE_STATUS_CODES = frozenset(
44
+ {
45
+ 408, # RequestTimeout (DEADLINE_EXCEEDED)
46
+ 409, # Conflict / Aborted (ABORTED)
47
+ 429, # TooManyRequests / ResourceExhausted (RESOURCE_EXHAUSTED)
48
+ 499, # Client Closed Request (CANCELLED)
49
+ 500, # InternalServerError (INTERNAL)
50
+ 502, # BadGateway
51
+ 503, # ServiceUnavailable (UNAVAILABLE)
52
+ 504, # GatewayTimeout (DEADLINE_EXCEEDED)
53
+ }
54
+ )
55
+
56
+ R = TypeVar("R")
57
+ T = TypeVar("T", types.Metric, types.MetricSource, types.LLMMetric)
58
+
59
+
60
+ def _call_with_retry(
61
+ fn: Callable[[], R],
62
+ metric_name: str,
63
+ ) -> R:
64
+ """Calls ``fn()`` with exponential backoff + jitter on retryable errors.
65
+
66
+ Retries up to ``_MAX_RETRIES`` times on errors whose HTTP status code is
67
+ in ``_RETRYABLE_STATUS_CODES`` (Aborted, DeadlineExceeded,
68
+ ResourceExhausted, ServiceUnavailable, Cancelled). Non-retryable errors
69
+ are re-raised immediately. If all retries are exhausted the last
70
+ exception is re-raised so the caller can decide how to handle it.
71
+
72
+ Args:
73
+ fn: A zero-argument callable that performs the API call.
74
+ metric_name: Name of the metric, used for log messages.
75
+
76
+ Returns:
77
+ The return value of ``fn()``.
78
+
79
+ Raises:
80
+ genai_errors.APIError: If all retries are exhausted or the error is
81
+ not retryable.
82
+ """
83
+ for attempt in range(_MAX_RETRIES):
84
+ try:
85
+ return fn()
86
+ except genai_errors.APIError as e:
87
+ if e.code in _RETRYABLE_STATUS_CODES:
88
+ backoff = 2**attempt + random.uniform(0, 1)
89
+ logger.warning(
90
+ "Retryable error (code=%s) on attempt %d/%d for metric"
91
+ " '%s': %s. Retrying in %.1f seconds...",
92
+ e.code,
93
+ attempt + 1,
94
+ _MAX_RETRIES,
95
+ metric_name,
96
+ e,
97
+ backoff,
98
+ )
99
+ if attempt == _MAX_RETRIES - 1:
100
+ raise
101
+ time.sleep(backoff)
102
+ else:
103
+ raise
104
+ raise genai_errors.APIError(
105
+ code=504, response_json={"message": "Retries exhausted"}
106
+ )
107
+
108
+
109
+ def _has_tool_call(events: Optional[list[Any]]) -> bool:
110
+ """Checks if any event in events has a function call."""
111
+ if not events:
112
+ return False
113
+ for event in events:
114
+ if getattr(event, "content", None) and getattr(event.content, "parts", None):
115
+ for part in event.content.parts:
116
+ if hasattr(part, "function_call") and part.function_call:
117
+ return True
118
+ return False
119
+
120
+
121
+ def _extract_text_from_content(
122
+ content: Optional[genai_types.Content], warn_property: str = "text"
123
+ ) -> Optional[str]:
124
+ """Extracts and concatenates all text parts from a Content object."""
125
+ if not content or not content.parts:
126
+ return None
127
+
128
+ text_accumulator = ""
129
+ any_text_part_found = False
130
+ non_text_part_names = []
131
+
132
+ for part_obj in content.parts:
133
+ part_dump = part_obj.model_dump(exclude={"text", "thought"})
134
+ for field_name, field_value in part_dump.items():
135
+ if field_value is not None:
136
+ if field_name not in non_text_part_names:
137
+ non_text_part_names.append(field_name)
138
+
139
+ if isinstance(part_obj.text, str):
140
+ if (
141
+ hasattr(part_obj, "thought")
142
+ and isinstance(part_obj.thought, bool)
143
+ and part_obj.thought
144
+ ):
145
+ continue
146
+ any_text_part_found = True
147
+ text_accumulator += part_obj.text
148
+
149
+ if non_text_part_names and any_text_part_found:
150
+ logger.warning(
151
+ "Warning: content contains non-text parts: %s. Returning"
152
+ " concatenated %s result from text parts. Inspect individual parts"
153
+ " for full content.",
154
+ non_text_part_names,
155
+ warn_property,
156
+ )
157
+ return text_accumulator if any_text_part_found else None
158
+
159
+
160
+ def _get_prompt_from_eval_case(
161
+ eval_case: types.EvalCase,
162
+ ) -> Optional[genai_types.Content]:
163
+ """Extracts prompt content from eval_case.prompt or starting_prompt."""
164
+ if eval_case.prompt:
165
+ return eval_case.prompt
166
+
167
+ user_scenario = getattr(eval_case, "user_scenario", None)
168
+ if user_scenario and user_scenario.starting_prompt:
169
+ return genai_types.Content(
170
+ parts=[genai_types.Part(text=user_scenario.starting_prompt)]
171
+ )
172
+
173
+ return None
174
+
175
+
176
+ def _get_response_from_eval_case(
177
+ eval_case: types.EvalCase, response_index: int, metric_name: str
178
+ ) -> Optional[genai_types.Content]:
179
+ """Extracts response content from eval_case.responses."""
180
+ response_content = None
181
+ if eval_case.responses and response_index < len(eval_case.responses):
182
+ response_content = eval_case.responses[response_index].response
183
+
184
+ return response_content
185
+
186
+
187
+ def _value_to_content_list(value: Any) -> list[genai_types.Content]:
188
+ """Converts a value to a list of Content objects."""
189
+ if isinstance(value, genai_types.Content):
190
+ return [value]
191
+ if isinstance(value, types.ResponseCandidate):
192
+ return [value.response] if value.response else []
193
+ if isinstance(value, list) and value:
194
+ if isinstance(value[0], genai_types.Content):
195
+ return value
196
+ if isinstance(value[0], types.evals.Message):
197
+ history_texts = []
198
+ for msg_obj in value:
199
+ msg_text = _extract_text_from_content(msg_obj.content)
200
+ if msg_text:
201
+ role = msg_obj.content.role or msg_obj.author or "user"
202
+ history_texts.append(f"{role}: {msg_text}")
203
+ return [
204
+ genai_types.Content(
205
+ parts=[genai_types.Part(text="\n".join(history_texts))]
206
+ )
207
+ ]
208
+ return [genai_types.Content(parts=[genai_types.Part(text=json.dumps(value))])]
209
+ if isinstance(value, dict):
210
+ return [genai_types.Content(parts=[genai_types.Part(text=json.dumps(value))])]
211
+ return [genai_types.Content(parts=[genai_types.Part(text=str(value))])]
212
+
213
+
214
+ def _get_autorater_config(metric: types.Metric) -> dict[str, Any]:
215
+ """Extracts autorater config settings from a metric."""
216
+ autorater_config: dict[str, Any] = {}
217
+ if metric.judge_model:
218
+ autorater_config["autorater_model"] = metric.judge_model
219
+ if metric.judge_model_generation_config:
220
+ autorater_config["generation_config"] = metric.judge_model_generation_config
221
+ if metric.judge_model_sampling_count:
222
+ autorater_config["sampling_count"] = metric.judge_model_sampling_count
223
+ return autorater_config
224
+
225
+
226
+ def _default_aggregate_scores(
227
+ metric_name: str,
228
+ eval_case_metric_results: list[types.EvalCaseMetricResult],
229
+ calculate_pass_rate: bool = False,
230
+ ) -> types.AggregatedMetricResult:
231
+ """Default aggregation logic using mean and standard deviation."""
232
+ scores = []
233
+ num_error = 0
234
+ num_valid = 0
235
+ num_passing = 0
236
+
237
+ for result in eval_case_metric_results:
238
+ if result.error_message is None and result.score is not None:
239
+ try:
240
+ score = float(result.score)
241
+ scores.append(score)
242
+ num_valid += 1
243
+ if calculate_pass_rate and score == 1.0:
244
+ num_passing += 1
245
+ except (ValueError, TypeError):
246
+ logger.warning(
247
+ "Could not convert score '%s' to float for metric '%s' during"
248
+ " default aggregation. Counting as error.",
249
+ result.score,
250
+ metric_name,
251
+ )
252
+ num_error += 1
253
+ else:
254
+ num_error += 1
255
+
256
+ mean_score = None
257
+ stdev_score = None
258
+ pass_rate = None
259
+
260
+ if num_valid > 0:
261
+ try:
262
+ mean_score = statistics.mean(scores)
263
+ except statistics.StatisticsError as e:
264
+ logger.warning("Could not calculate mean for %s: %s", metric_name, e)
265
+ if calculate_pass_rate:
266
+ pass_rate = num_passing / num_valid
267
+
268
+ if num_valid > 1:
269
+ try:
270
+ stdev_score = statistics.stdev(scores)
271
+ except statistics.StatisticsError as e:
272
+ logger.warning("Could not calculate stdev for %s: %s", metric_name, e)
273
+
274
+ return types.AggregatedMetricResult(
275
+ metric_name=metric_name,
276
+ num_cases_total=len(eval_case_metric_results),
277
+ num_cases_valid=num_valid,
278
+ num_cases_error=num_error,
279
+ mean_score=mean_score,
280
+ stdev_score=stdev_score,
281
+ pass_rate=pass_rate if calculate_pass_rate else None,
282
+ )
283
+
284
+
285
+ class MetricHandler(abc.ABC, Generic[T]):
286
+ """Abstract base class for metric handlers."""
287
+
288
+ def __init__(self, module: "evals.Evals", metric: T):
289
+ self.module = module
290
+ self.metric: T = metric
291
+
292
+ @property
293
+ @abc.abstractmethod
294
+ def metric_name(self) -> str:
295
+ """Returns the name of the metric polymorphically."""
296
+ raise NotImplementedError()
297
+
298
+ @abc.abstractmethod
299
+ def get_metric_result(
300
+ self, eval_case: types.EvalCase, response_index: int
301
+ ) -> types.EvalCaseMetricResult:
302
+ """Processes a single evaluation case for a specific metric."""
303
+ raise NotImplementedError()
304
+
305
+ @abc.abstractmethod
306
+ def aggregate(
307
+ self, eval_case_metric_results: list[types.EvalCaseMetricResult]
308
+ ) -> types.AggregatedMetricResult:
309
+ """Aggregates the metric results for a specific metric."""
310
+ raise NotImplementedError()
311
+
312
+
313
+ class ComputationMetricHandler(MetricHandler[types.Metric]):
314
+ """Metric handler for computation metrics."""
315
+
316
+ SUPPORTED_COMPUTATION_METRICS = frozenset(
317
+ {
318
+ "exact_match",
319
+ "bleu",
320
+ "rouge_1",
321
+ "rouge_l_sum",
322
+ "tool_call_valid",
323
+ "tool_name_match",
324
+ "tool_parameter_key_match",
325
+ "tool_parameter_kv_match",
326
+ # TODO b/423934249 - Add trajectory metrics once they are supported.
327
+ }
328
+ )
329
+
330
+ @property
331
+ def metric_name(self) -> str:
332
+ return self.metric.name or "unknown_metric"
333
+
334
+ def __init__(self, module: "evals.Evals", metric: types.Metric):
335
+ super().__init__(module=module, metric=metric)
336
+ if self.metric.name not in self.SUPPORTED_COMPUTATION_METRICS:
337
+ raise ValueError(
338
+ f"Metric '{self.metric.name}' is not supported for computation."
339
+ )
340
+
341
+ def _build_request_payload(
342
+ self, eval_case: types.EvalCase, response_index: int
343
+ ) -> dict[str, Any]:
344
+ """Builds the request parameters for evaluate instances."""
345
+ request_payload = {}
346
+
347
+ response_content = _get_response_from_eval_case(
348
+ eval_case, response_index, self.metric.name
349
+ )
350
+ prediction_text = _extract_text_from_content(response_content)
351
+
352
+ if prediction_text is None:
353
+ raise ValueError(
354
+ f"Response text missing for candidate {response_index} in eval_case"
355
+ f" {eval_case.eval_case_id or 'Unknown ID'}."
356
+ )
357
+
358
+ if (
359
+ eval_case.reference is None
360
+ or _extract_text_from_content(eval_case.reference.response) is None
361
+ ):
362
+ raise ValueError(
363
+ "Reference text missing for eval_case"
364
+ f" {eval_case.eval_case_id or 'Unknown ID'}."
365
+ )
366
+ logger.debug("eval_case: %s", eval_case)
367
+
368
+ if self.metric.name and self.metric.name.startswith("rouge"):
369
+ request_payload["rouge_input"] = {
370
+ "metric_spec": {
371
+ "rouge_type": (
372
+ "rougeLsum" if self.metric.name == "rouge_l_sum" else "rouge1"
373
+ ),
374
+ },
375
+ "instances": [
376
+ {
377
+ "prediction": prediction_text,
378
+ "reference": _extract_text_from_content(
379
+ eval_case.reference.response
380
+ ),
381
+ }
382
+ ],
383
+ }
384
+ else:
385
+ request_payload[f"{self.metric.name}_input"] = {
386
+ "metric_spec": {},
387
+ "instances": [
388
+ {
389
+ "prediction": prediction_text,
390
+ "reference": _extract_text_from_content(
391
+ eval_case.reference.response
392
+ ),
393
+ }
394
+ ],
395
+ }
396
+ logger.debug("request_payload: %s", request_payload)
397
+ return request_payload
398
+
399
+ @override
400
+ def get_metric_result(
401
+ self, eval_case: types.EvalCase, response_index: int
402
+ ) -> types.EvalCaseMetricResult:
403
+ """Processes a single evaluation case for a specific computation metric."""
404
+
405
+ metric_name = self.metric.name
406
+ logger.debug(
407
+ "ComputationMetricHandler: Processing '%s' for case: %s",
408
+ metric_name,
409
+ eval_case.model_dump(exclude_none=True),
410
+ )
411
+ response = _call_with_retry(
412
+ lambda: self.module.evaluate_instances(
413
+ metric_config=self._build_request_payload(eval_case, response_index)
414
+ ).model_dump(exclude_none=True),
415
+ metric_name,
416
+ )
417
+ logger.debug("response: %s", response)
418
+ score = None
419
+ for _, result_value in response.items():
420
+ if isinstance(result_value, dict) and result_value:
421
+ for _, metric_value in result_value.items():
422
+ if isinstance(metric_value, list) and metric_value:
423
+ score = metric_value[0]["score"]
424
+ break
425
+ logger.debug("Metric result: %s", score)
426
+ return types.EvalCaseMetricResult(
427
+ metric_name=metric_name,
428
+ score=score,
429
+ )
430
+
431
+ @override
432
+ def aggregate(
433
+ self, eval_case_metric_results: list[types.EvalCaseMetricResult]
434
+ ) -> types.AggregatedMetricResult:
435
+ """Aggregates the metric results for a computation metric."""
436
+ logger.debug("Aggregating results for computation metric: %s", self.metric.name)
437
+ return _default_aggregate_scores(self.metric.name, eval_case_metric_results)
438
+
439
+
440
+ class TranslationMetricHandler(MetricHandler[types.Metric]):
441
+ """Metric handler for translation metrics."""
442
+
443
+ SUPPORTED_TRANSLATION_METRICS = frozenset({"comet", "metricx"})
444
+
445
+ @property
446
+ def metric_name(self) -> str:
447
+ return self.metric.name or "unknown_metric"
448
+
449
+ def __init__(self, module: "evals.Evals", metric: types.Metric):
450
+ super().__init__(module=module, metric=metric)
451
+
452
+ if self.metric.name not in self.SUPPORTED_TRANSLATION_METRICS:
453
+ raise ValueError(
454
+ f"Metric '{self.metric.name}' is not supported for translation."
455
+ )
456
+
457
+ def _build_request_payload(
458
+ self, eval_case: types.EvalCase, response_index: int
459
+ ) -> dict[str, Any]:
460
+ """Builds the request parameters for evaluate instances."""
461
+ request_payload = {}
462
+ metric_input_name = f"{self.metric.name}_input"
463
+ version = None
464
+ if hasattr(self.metric, "version"):
465
+ version = self.metric.version
466
+ elif self.metric.name == "comet":
467
+ version = "COMET_22_SRC_REF"
468
+ elif self.metric.name == "metricx":
469
+ version = "METRICX_24_SRC_REF"
470
+
471
+ source_language = None
472
+ target_language = None
473
+ if hasattr(self.metric, "source_language"):
474
+ source_language = self.metric.source_language
475
+ if hasattr(self.metric, "target_language"):
476
+ target_language = self.metric.target_language
477
+
478
+ response_content = _get_response_from_eval_case(
479
+ eval_case, response_index, self.metric.name
480
+ )
481
+ prediction_text = _extract_text_from_content(response_content)
482
+ prompt_text = _extract_text_from_content(_get_prompt_from_eval_case(eval_case))
483
+
484
+ if prediction_text is None:
485
+ raise ValueError(
486
+ f"Response text missing for candidate {response_index} in eval_case"
487
+ f" {eval_case.eval_case_id or 'Unknown ID'}."
488
+ )
489
+
490
+ if (
491
+ eval_case.reference is None
492
+ or _extract_text_from_content(eval_case.reference.response) is None
493
+ ):
494
+ raise ValueError(
495
+ "Reference text missing for eval_case"
496
+ f" {eval_case.eval_case_id or 'Unknown ID'}."
497
+ )
498
+ if prompt_text is None:
499
+ raise ValueError(
500
+ "Prompt text (source for translation) missing for eval_case"
501
+ f" {eval_case.eval_case_id or 'Unknown ID'}."
502
+ )
503
+
504
+ request_payload[metric_input_name] = {
505
+ "metric_spec": {
506
+ "version": version,
507
+ "source_language": source_language,
508
+ "target_language": target_language,
509
+ },
510
+ "instance": {
511
+ "prediction": prediction_text,
512
+ "reference": _extract_text_from_content(eval_case.reference.response),
513
+ "source": prompt_text,
514
+ },
515
+ }
516
+ return request_payload
517
+
518
+ @override
519
+ def get_metric_result(
520
+ self, eval_case: types.EvalCase, response_index: int
521
+ ) -> types.EvalCaseMetricResult:
522
+ """Processes a single evaluation case for a specific translation metric."""
523
+ metric_name = self.metric.name
524
+ logger.debug(
525
+ "TranslationMetricHandler: Processing '%s' for case: %s",
526
+ metric_name,
527
+ eval_case,
528
+ )
529
+ api_response = _call_with_retry(
530
+ lambda: self.module.evaluate_instances(
531
+ metric_config=self._build_request_payload(eval_case, response_index)
532
+ ),
533
+ metric_name,
534
+ )
535
+ logger.debug("API Response: %s", api_response)
536
+
537
+ score = None
538
+ error_message = None
539
+
540
+ try:
541
+ if metric_name == "comet":
542
+ if api_response and api_response.comet_result:
543
+ score = api_response.comet_result.score
544
+ else:
545
+ logger.warning(
546
+ "Comet result missing in API response for metric '%s'."
547
+ " API response: %s",
548
+ metric_name,
549
+ (
550
+ api_response.model_dump_json(exclude_none=True)
551
+ if api_response
552
+ else "None"
553
+ ),
554
+ )
555
+ elif metric_name == "metricx":
556
+ if api_response and api_response.metricx_result:
557
+ score = api_response.metricx_result.score
558
+ else:
559
+ logger.warning(
560
+ "MetricX result missing in API response for metric '%s'."
561
+ " API response: %s",
562
+ metric_name,
563
+ (
564
+ api_response.model_dump_json(exclude_none=True)
565
+ if api_response
566
+ else "None"
567
+ ),
568
+ )
569
+ if score is None and not error_message:
570
+ logger.warning(
571
+ "Score could not be extracted for translation metric '%s'."
572
+ " API response: %s",
573
+ metric_name,
574
+ (
575
+ api_response.model_dump_json(exclude_none=True)
576
+ if api_response
577
+ else "None"
578
+ ),
579
+ )
580
+ except Exception as e: # pylint: disable=broad-exception-caught
581
+ logger.error(
582
+ "Error processing/extracting score for translation metric '%s': %s."
583
+ " API response: %s",
584
+ metric_name,
585
+ e,
586
+ (
587
+ api_response.model_dump_json(exclude_none=True)
588
+ if api_response
589
+ else "None"
590
+ ),
591
+ exc_info=True,
592
+ )
593
+ error_message = f"Error extracting score: {e}"
594
+
595
+ return types.EvalCaseMetricResult(
596
+ metric_name=metric_name,
597
+ score=score,
598
+ error_message=error_message,
599
+ )
600
+
601
+ @override
602
+ def aggregate(
603
+ self, eval_case_metric_results: list[types.EvalCaseMetricResult]
604
+ ) -> types.AggregatedMetricResult:
605
+ """Aggregates the metric results for a translation metric."""
606
+ logger.debug("Aggregating results for translation metric: %s", self.metric.name)
607
+ return _default_aggregate_scores(self.metric.name, eval_case_metric_results)
608
+
609
+
610
+ def _content_to_instance_data(
611
+ content: Optional[genai_types.Content],
612
+ ) -> Optional[types.evals.InstanceData]:
613
+ """Converts a genai_types.Content object to a types.InstanceData object."""
614
+ if not content:
615
+ return None
616
+ return types.evals.InstanceData(
617
+ contents=types.evals.InstanceDataContents(contents=[content])
618
+ )
619
+
620
+
621
+ def _eval_case_to_agent_data(
622
+ eval_case: types.EvalCase,
623
+ prompt_content: Optional[genai_types.Content] = None,
624
+ response_content: Optional[genai_types.Content] = None,
625
+ ) -> Optional[types.evals.AgentData]:
626
+ """Converts an EvalCase object to a single turn AgentData object.
627
+
628
+ If `eval_case.agent_data` is provided, it is returned directly, and
629
+ `prompt_content` and `response_content` are ignored.
630
+ """
631
+ if getattr(eval_case, "agent_data", None):
632
+ return eval_case.agent_data
633
+
634
+ if (
635
+ not eval_case.agent_info
636
+ and not eval_case.intermediate_events
637
+ and not prompt_content
638
+ and not response_content
639
+ ):
640
+ return None
641
+
642
+ agents_map = eval_case.agent_info.agents if eval_case.agent_info else None
643
+ events = []
644
+ if prompt_content:
645
+ events.append(types.evals.AgentEvent(author="user", content=prompt_content))
646
+
647
+ if eval_case.intermediate_events:
648
+ for event in eval_case.intermediate_events:
649
+ events.append(
650
+ types.evals.AgentEvent(
651
+ author=event.author,
652
+ content=event.content,
653
+ event_time=event.creation_timestamp,
654
+ )
655
+ )
656
+
657
+ if response_content:
658
+ events.append(types.evals.AgentEvent(author="model", content=response_content))
659
+
660
+ turns = (
661
+ [types.evals.ConversationTurn(turn_index=0, turn_id="turn_0", events=events)]
662
+ if events
663
+ else None
664
+ )
665
+ return types.evals.AgentData(agents=agents_map, turns=turns)
666
+
667
+
668
+ def _build_evaluation_instance(
669
+ eval_case: types.EvalCase,
670
+ response_content: Optional[genai_types.Content],
671
+ prompt_instance_data: Optional[types.evals.InstanceData] = None,
672
+ prompt_template: Optional[str] = None,
673
+ ) -> types.EvaluationInstance:
674
+ """Builds a unified EvaluationInstance. Multi-turn logic is handled by the caller."""
675
+ extracted_prompt = _get_prompt_from_eval_case(eval_case)
676
+
677
+ # 1. Use caller-provided prompt data (multi-turn) or default to simple content
678
+ if prompt_instance_data is None:
679
+ prompt_instance_data = _content_to_instance_data(extracted_prompt)
680
+
681
+ # 2. Collect placeholders for other_data
682
+ other_data_map: dict[str, Any] = {}
683
+ if hasattr(eval_case, "context") and eval_case.context:
684
+ if isinstance(eval_case.context, str):
685
+ other_data_map["context"] = types.evals.InstanceData(text=eval_case.context)
686
+ elif isinstance(eval_case.context, genai_types.Content):
687
+ other_data_map["context"] = _content_to_instance_data(eval_case.context)
688
+
689
+ # 3. Extract custom variables from LLMMetric templates
690
+ if prompt_template:
691
+ template_vars = types.PromptTemplate(text=prompt_template).variables
692
+ standard_fields = {"prompt", "response", "reference", "context", "agent_data"}
693
+ for full_path in template_vars:
694
+ # Extract the root variable (e.g. 'metadata' from 'metadata.user_id')
695
+ root_var = full_path.split(".")[0].split("[")[0]
696
+
697
+ if root_var not in standard_fields and hasattr(eval_case, root_var):
698
+ val = getattr(eval_case, root_var)
699
+ # Add the root object to other_data so the backend can traverse it
700
+ other_data_map[root_var] = types.evals.InstanceData(
701
+ contents=types.evals.InstanceDataContents(
702
+ contents=_value_to_content_list(val)
703
+ )
704
+ )
705
+
706
+ return types.EvaluationInstance(
707
+ prompt=prompt_instance_data,
708
+ response=_content_to_instance_data(response_content),
709
+ reference=(
710
+ _content_to_instance_data(eval_case.reference.response)
711
+ if eval_case.reference
712
+ else None
713
+ ),
714
+ rubric_groups=eval_case.rubric_groups,
715
+ other_data=(
716
+ types.MapInstance(map_instance=other_data_map) if other_data_map else None
717
+ ),
718
+ agent_data=_eval_case_to_agent_data(
719
+ eval_case, extracted_prompt, response_content
720
+ ),
721
+ )
722
+
723
+
724
+ class LLMMetricHandler(MetricHandler[types.LLMMetric]):
725
+ """Metric handler for LLM metrics."""
726
+
727
+ @property
728
+ def metric_name(self) -> str:
729
+ return self.metric.name or "unknown_metric"
730
+
731
+ def __init__(self, module: "evals.Evals", metric: types.LLMMetric):
732
+ super().__init__(module=module, metric=metric)
733
+
734
+ @override
735
+ def get_metric_result(
736
+ self, eval_case: types.EvalCase, response_index: int
737
+ ) -> types.EvalCaseMetricResult:
738
+ """Processes a single evaluation case using the unified backend interface."""
739
+ try:
740
+ response_content = _get_response_from_eval_case(
741
+ eval_case, response_index, self.metric_name
742
+ )
743
+ if not response_content:
744
+ raise ValueError(
745
+ f"Response content missing for candidate {response_index}."
746
+ )
747
+
748
+ instance = _build_evaluation_instance(
749
+ eval_case, response_content, prompt_template=self.metric.prompt_template
750
+ )
751
+ api_response = _call_with_retry(
752
+ lambda: self.module._evaluate_instances(
753
+ metrics=[self.metric],
754
+ instance=instance,
755
+ ),
756
+ self.metric_name,
757
+ )
758
+
759
+ if api_response and api_response.metric_results:
760
+ result = api_response.metric_results[0]
761
+ error_msg = None
762
+ if result.error and getattr(result.error, "code"):
763
+ error_msg = f"Error in metric result: {result.error}"
764
+
765
+ return types.EvalCaseMetricResult(
766
+ metric_name=self.metric_name,
767
+ score=result.score,
768
+ explanation=result.explanation,
769
+ rubric_verdicts=result.rubric_verdicts,
770
+ error_message=error_msg,
771
+ )
772
+ else:
773
+ return types.EvalCaseMetricResult(
774
+ metric_name=self.metric_name,
775
+ error_message="Metric results missing in API response.",
776
+ )
777
+
778
+ except Exception as e:
779
+ logger.error(
780
+ "Error processing metric %s for case %s.",
781
+ self.metric_name,
782
+ eval_case.eval_case_id,
783
+ exc_info=True,
784
+ )
785
+ return types.EvalCaseMetricResult(
786
+ metric_name=self.metric_name, error_message=str(e)
787
+ )
788
+
789
+ @override
790
+ def aggregate(
791
+ self, eval_case_metric_results: list[types.EvalCaseMetricResult]
792
+ ) -> types.AggregatedMetricResult:
793
+ """Aggregates the metric results for a LLM metric."""
794
+ if self.metric.aggregate_summary_fn and callable(
795
+ self.metric.aggregate_summary_fn
796
+ ):
797
+ logger.info(
798
+ "Using custom aggregate_summary_fn for metric '%s'", self.metric.name
799
+ )
800
+ try:
801
+ custom_summary_dict = self.metric.aggregate_summary_fn(
802
+ eval_case_metric_results
803
+ )
804
+ if not isinstance(custom_summary_dict, dict):
805
+ raise TypeError("aggregate_summary_fn must return a dictionary.")
806
+
807
+ num_cases_total = len(eval_case_metric_results)
808
+ num_cases_error = len(
809
+ [
810
+ result
811
+ for result in eval_case_metric_results
812
+ if result.error_message is not None
813
+ ]
814
+ )
815
+ num_cases_valid = num_cases_total - num_cases_error
816
+ required_fields = {
817
+ "num_cases_total": num_cases_total,
818
+ "num_cases_error": num_cases_error,
819
+ "num_cases_valid": num_cases_valid,
820
+ }
821
+ final_summary_dict = {**required_fields, **custom_summary_dict}
822
+
823
+ return types.AggregatedMetricResult(
824
+ metric_name=self.metric.name,
825
+ **final_summary_dict,
826
+ )
827
+ except Exception as e: # pylint: disable=broad-exception-caught
828
+ logger.error(
829
+ "Error executing custom aggregate_summary_fn for metric '%s': %s."
830
+ " Falling back to default aggregation.",
831
+ self.metric.name,
832
+ e,
833
+ exc_info=True,
834
+ )
835
+ return _default_aggregate_scores(
836
+ self.metric.name, eval_case_metric_results
837
+ )
838
+ else:
839
+ logger.debug(
840
+ "Using default aggregation for LLM metric '%s'", self.metric.name
841
+ )
842
+ return _default_aggregate_scores(self.metric.name, eval_case_metric_results)
843
+
844
+
845
+ class CustomMetricHandler(MetricHandler[types.Metric]):
846
+ """Metric handler for custom metrics."""
847
+
848
+ @property
849
+ def metric_name(self) -> str:
850
+ return self.metric.name or "unknown_metric"
851
+
852
+ def __init__(self, module: "evals.Evals", metric: types.Metric):
853
+ super().__init__(module=module, metric=metric)
854
+
855
+ if not self.metric.custom_function:
856
+ raise ValueError(
857
+ f"CustomMetricHandler for '{self.metric.name}' needs "
858
+ " Metric.custom_function to be set."
859
+ )
860
+ if not isinstance(self.metric.custom_function, Callable):
861
+ raise ValueError(
862
+ f"CustomMetricHandler for '{self.metric.name}' needs "
863
+ " Metric.custom_function to be a callable function."
864
+ )
865
+
866
+ @override
867
+ def get_metric_result(
868
+ self, eval_case: types.EvalCase, response_index: int
869
+ ) -> types.EvalCaseMetricResult:
870
+ """Processes a single evaluation case for a custom metric."""
871
+ metric_name = self.metric.name
872
+ logger.debug(
873
+ "CustomMetricHandler: Processing '%s' for case: %s",
874
+ metric_name,
875
+ eval_case.model_dump(exclude_none=True),
876
+ )
877
+
878
+ try:
879
+ response_content = _get_response_from_eval_case(
880
+ eval_case, response_index, metric_name
881
+ )
882
+ except ValueError as e:
883
+ return types.EvalCaseMetricResult(
884
+ metric_name=metric_name,
885
+ error_message=str(e),
886
+ )
887
+
888
+ if not response_content:
889
+ return types.EvalCaseMetricResult(
890
+ metric_name=metric_name,
891
+ error_message=(
892
+ f"No response found for candidate {response_index} in EvalCase"
893
+ f" {eval_case.eval_case_id}."
894
+ ),
895
+ )
896
+
897
+ instance_for_custom_fn = eval_case.model_dump(
898
+ exclude={"responses"}, mode="json", exclude_none=True
899
+ )
900
+ instance_for_custom_fn["response"] = response_content.model_dump(
901
+ mode="json", exclude_none=True
902
+ )
903
+ extracted_prompt = _get_prompt_from_eval_case(eval_case)
904
+ if extracted_prompt:
905
+ instance_for_custom_fn["prompt"] = extracted_prompt.model_dump(
906
+ mode="json", exclude_none=True
907
+ )
908
+
909
+ error_msg = None
910
+ score = None
911
+ explanation = None
912
+ try:
913
+ if self.metric.custom_function and callable(self.metric.custom_function):
914
+ custom_function_result = self.metric.custom_function(
915
+ instance_for_custom_fn
916
+ )
917
+
918
+ if isinstance(custom_function_result, types.EvalCaseMetricResult):
919
+ return custom_function_result
920
+ elif (
921
+ isinstance(custom_function_result, dict)
922
+ and "score" in custom_function_result
923
+ ):
924
+ score = custom_function_result["score"]
925
+ explanation = custom_function_result.get("explanation", None)
926
+ elif isinstance(custom_function_result, (float, int)):
927
+ score = custom_function_result
928
+ explanation = None
929
+ else:
930
+ error_msg = (
931
+ f"CustomFunctionError({self.metric.custom_function}): Returned"
932
+ f" unexpected type {type(custom_function_result)}"
933
+ )
934
+
935
+ except Exception as e: # pylint: disable=broad-exception-caught
936
+ if self.metric.custom_function and hasattr(
937
+ self.metric.custom_function, "__name__"
938
+ ):
939
+ custom_function_name = self.metric.custom_function.__name__
940
+ else:
941
+ custom_function_name = "unknown_custom_function"
942
+ error_msg = f"CustomFunctionError({custom_function_name}): {e}"
943
+ score = None
944
+ explanation = None
945
+
946
+ return types.EvalCaseMetricResult(
947
+ metric_name=self.metric.name,
948
+ score=score,
949
+ explanation=explanation,
950
+ error_message=error_msg,
951
+ )
952
+
953
+ @override
954
+ def aggregate(
955
+ self, eval_case_metric_results: list[types.EvalCaseMetricResult]
956
+ ) -> types.AggregatedMetricResult:
957
+ """Aggregates the metric results for a custom metric."""
958
+ logger.debug("Aggregating results for custom metric: %s", self.metric.name)
959
+ return _default_aggregate_scores(self.metric.name, eval_case_metric_results)
960
+
961
+
962
+ class PredefinedMetricHandler(MetricHandler[types.Metric]):
963
+ """Metric handler for predefined metrics."""
964
+
965
+ @property
966
+ def metric_name(self) -> str:
967
+ return self.metric.name or "unknown_metric"
968
+
969
+ def __init__(self, module: "evals.Evals", metric: types.Metric):
970
+ super().__init__(module=module, metric=metric)
971
+ if self.metric.name not in _evals_constant.SUPPORTED_PREDEFINED_METRICS:
972
+ raise ValueError(
973
+ f"Metric '{self.metric.name}' is not a supported predefined metric."
974
+ )
975
+
976
+ def _build_request_payload(
977
+ self, eval_case: types.EvalCase, response_index: int
978
+ ) -> dict[str, Any]:
979
+ """Builds the request parameters for evaluate instances request."""
980
+ response_content = _get_response_from_eval_case(
981
+ eval_case, response_index, self.metric.name
982
+ )
983
+
984
+ if not response_content and not getattr(eval_case, "agent_data", None):
985
+ raise ValueError(
986
+ f"Response content missing for candidate {response_index}."
987
+ )
988
+
989
+ if self.metric.name == "tool_use_quality_v1":
990
+ has_tool_call = _has_tool_call(eval_case.intermediate_events)
991
+
992
+ # Check agent_data for tool calls if intermediate_events is empty
993
+ agent_data = getattr(eval_case, "agent_data", None)
994
+ if not has_tool_call and agent_data:
995
+ for turn in agent_data.turns or []:
996
+ if _has_tool_call(turn.events):
997
+ has_tool_call = True
998
+ break
999
+
1000
+ if not has_tool_call:
1001
+ logger.warning(
1002
+ "Metric 'tool_use_quality_v1' requires tool usage in "
1003
+ "'intermediate_events' or 'agent_data', but no tool usage was found for case %s.",
1004
+ eval_case.eval_case_id,
1005
+ )
1006
+
1007
+ extracted_prompt = _get_prompt_from_eval_case(eval_case)
1008
+ prompt_instance_data = None
1009
+ if self.metric.name and self.metric.name.startswith("multi_turn"):
1010
+ prompt_contents = [
1011
+ msg.content for msg in (eval_case.conversation_history or [])
1012
+ ]
1013
+ if extracted_prompt:
1014
+ prompt_contents.append(extracted_prompt)
1015
+ prompt_instance_data = types.evals.InstanceData(
1016
+ contents=types.evals.InstanceDataContents(contents=prompt_contents)
1017
+ )
1018
+
1019
+ instance_payload = _build_evaluation_instance(
1020
+ eval_case=eval_case,
1021
+ response_content=response_content,
1022
+ prompt_instance_data=prompt_instance_data,
1023
+ )
1024
+
1025
+ request_payload: dict[str, Any] = {
1026
+ "instance": instance_payload,
1027
+ }
1028
+
1029
+ autorater_config = _get_autorater_config(self.metric)
1030
+ if autorater_config:
1031
+ request_payload["autorater_config"] = genai_types.AutoraterConfig(
1032
+ **autorater_config
1033
+ )
1034
+ return request_payload
1035
+
1036
+ @override
1037
+ def get_metric_result(
1038
+ self, eval_case: types.EvalCase, response_index: int
1039
+ ) -> types.EvalCaseMetricResult:
1040
+ """Processes a single evaluation case for a specific predefined metric."""
1041
+ metric_name = self.metric.name
1042
+ try:
1043
+ payload = self._build_request_payload(eval_case, response_index)
1044
+ api_response = _call_with_retry(
1045
+ lambda: self.module._evaluate_instances(
1046
+ metrics=[self.metric],
1047
+ instance=payload.get("instance"),
1048
+ autorater_config=payload.get("autorater_config"),
1049
+ ),
1050
+ metric_name,
1051
+ )
1052
+
1053
+ if (
1054
+ api_response
1055
+ and hasattr(api_response, "metric_results")
1056
+ and api_response.metric_results
1057
+ ):
1058
+ result_data = api_response.metric_results[0]
1059
+
1060
+ error_message = None
1061
+ if result_data.error and getattr(result_data.error, "code"):
1062
+ error_message = f"Error in metric result: {result_data.error}"
1063
+ return types.EvalCaseMetricResult(
1064
+ metric_name=metric_name,
1065
+ score=result_data.score,
1066
+ explanation=result_data.explanation,
1067
+ rubric_verdicts=result_data.rubric_verdicts,
1068
+ error_message=error_message,
1069
+ )
1070
+ else:
1071
+ logger.error(
1072
+ "Metric results missing in API response for predefined metric '%s'."
1073
+ " API response: %s",
1074
+ metric_name,
1075
+ (
1076
+ api_response.model_dump_json(exclude_none=True)
1077
+ if api_response
1078
+ else "None"
1079
+ ),
1080
+ )
1081
+ return types.EvalCaseMetricResult(
1082
+ metric_name=metric_name,
1083
+ error_message="Metric results missing in API response.",
1084
+ )
1085
+ except Exception as e: # pylint: disable=broad-exception-caught
1086
+ logger.error(
1087
+ "Error processing metric %s for case %s: %s",
1088
+ metric_name,
1089
+ eval_case.eval_case_id,
1090
+ e,
1091
+ exc_info=True,
1092
+ )
1093
+ return types.EvalCaseMetricResult(
1094
+ metric_name=metric_name, error_message=str(e)
1095
+ )
1096
+
1097
+ @override
1098
+ def aggregate(
1099
+ self, eval_case_metric_results: list[types.EvalCaseMetricResult]
1100
+ ) -> types.AggregatedMetricResult:
1101
+ """Aggregates the metric results for a predefined metric."""
1102
+ logger.debug("Aggregating results for predefined metric: %s", self.metric.name)
1103
+ return _default_aggregate_scores(
1104
+ self.metric.name, eval_case_metric_results, calculate_pass_rate=True
1105
+ )
1106
+
1107
+
1108
+ class CustomCodeExecutionMetricHandler(MetricHandler[types.Metric]):
1109
+ """Metric handler for custom code execution metrics."""
1110
+
1111
+ @property
1112
+ def metric_name(self) -> str:
1113
+ return self.metric.name or "unknown_metric"
1114
+
1115
+ def __init__(self, module: "evals.Evals", metric: types.Metric):
1116
+ super().__init__(module=module, metric=metric)
1117
+
1118
+ if not self.metric.remote_custom_function and not self.metric.custom_function:
1119
+ raise ValueError(
1120
+ f"CustomCodeExecutionMetricHandler for '{self.metric.name}' needs "
1121
+ " custom function to be set."
1122
+ )
1123
+
1124
+ def _build_request_payload(
1125
+ self, eval_case: types.EvalCase, response_index: int
1126
+ ) -> dict[str, Any]:
1127
+ """Builds the request parameters for evaluate instances request."""
1128
+ response_content = _get_response_from_eval_case(
1129
+ eval_case, response_index, self.metric.name
1130
+ )
1131
+
1132
+ if not response_content and not getattr(eval_case, "agent_data", None):
1133
+ raise ValueError(
1134
+ f"Response content missing for candidate {response_index}."
1135
+ )
1136
+
1137
+ reference_instance_data = None
1138
+ if eval_case.reference:
1139
+ reference_instance_data = _content_to_instance_data(
1140
+ eval_case.reference.response
1141
+ )
1142
+
1143
+ extracted_prompt = _get_prompt_from_eval_case(eval_case)
1144
+ prompt_instance_data = _content_to_instance_data(extracted_prompt)
1145
+
1146
+ instance_payload = types.EvaluationInstance(
1147
+ prompt=prompt_instance_data,
1148
+ response=_content_to_instance_data(response_content),
1149
+ reference=reference_instance_data,
1150
+ agent_data=_eval_case_to_agent_data(eval_case),
1151
+ )
1152
+
1153
+ return {
1154
+ "instance": instance_payload,
1155
+ }
1156
+
1157
+ @override
1158
+ def get_metric_result(
1159
+ self, eval_case: types.EvalCase, response_index: int
1160
+ ) -> types.EvalCaseMetricResult:
1161
+ """Processes a single evaluation case for a specific custom code execution metric."""
1162
+ metric_name = self.metric.name
1163
+ try:
1164
+ payload = self._build_request_payload(eval_case, response_index)
1165
+ api_response = _call_with_retry(
1166
+ lambda: self.module._evaluate_instances(
1167
+ metrics=[self.metric],
1168
+ instance=payload.get("instance"),
1169
+ ),
1170
+ metric_name,
1171
+ )
1172
+
1173
+ if (
1174
+ api_response
1175
+ and hasattr(api_response, "metric_results")
1176
+ and api_response.metric_results
1177
+ ):
1178
+ result_data = api_response.metric_results[0]
1179
+
1180
+ error_message = None
1181
+ if result_data.error and getattr(result_data.error, "code"):
1182
+ error_message = f"Error in metric result: {result_data.error}"
1183
+ return types.EvalCaseMetricResult(
1184
+ metric_name=metric_name,
1185
+ score=result_data.score,
1186
+ explanation=result_data.explanation,
1187
+ error_message=error_message,
1188
+ )
1189
+ else:
1190
+ logger.error(
1191
+ "Metric results missing in API response for metric '%s'."
1192
+ " API response: %s",
1193
+ metric_name,
1194
+ (
1195
+ api_response.model_dump_json(exclude_none=True)
1196
+ if api_response
1197
+ else "None"
1198
+ ),
1199
+ )
1200
+ return types.EvalCaseMetricResult(
1201
+ metric_name=metric_name,
1202
+ error_message="Metric results missing in API response.",
1203
+ )
1204
+ except Exception as e: # pylint: disable=broad-exception-caught
1205
+ logger.error(
1206
+ "Error processing metric %s for case %s",
1207
+ metric_name,
1208
+ eval_case.eval_case_id,
1209
+ exc_info=True,
1210
+ )
1211
+ return types.EvalCaseMetricResult(
1212
+ metric_name=metric_name, error_message=str(e)
1213
+ )
1214
+
1215
+ @override
1216
+ def aggregate(
1217
+ self, eval_case_metric_results: list[types.EvalCaseMetricResult]
1218
+ ) -> types.AggregatedMetricResult:
1219
+ """Aggregates the metric results for a custom code execution metric."""
1220
+ logger.debug(
1221
+ "Aggregating results for custom code execution metric: %s", self.metric.name
1222
+ )
1223
+ return _default_aggregate_scores(
1224
+ self.metric.name, eval_case_metric_results, calculate_pass_rate=True
1225
+ )
1226
+
1227
+
1228
+ class RegisteredMetricHandler(MetricHandler[types.Metric]):
1229
+ """Metric handler for registered metrics."""
1230
+
1231
+ def __init__(
1232
+ self,
1233
+ module: "evals.Evals",
1234
+ metric: types.Metric,
1235
+ ):
1236
+ if isinstance(metric, dict):
1237
+ metric = types.MetricSource(**metric)
1238
+ super().__init__(module=module, metric=metric)
1239
+
1240
+ def _build_request_payload(
1241
+ self, eval_case: types.EvalCase, response_index: int
1242
+ ) -> dict[str, Any]:
1243
+ """Builds request payload for registered metric by assembling EvaluationInstance."""
1244
+ response_content = _get_response_from_eval_case(
1245
+ eval_case, response_index, self.metric_name
1246
+ )
1247
+
1248
+ if not response_content and not getattr(eval_case, "agent_data", None):
1249
+ raise ValueError(
1250
+ f"Response content missing for candidate {response_index}."
1251
+ )
1252
+
1253
+ reference_instance_data = None
1254
+ if eval_case.reference:
1255
+ reference_instance_data = _content_to_instance_data(
1256
+ eval_case.reference.response
1257
+ )
1258
+
1259
+ extracted_prompt = _get_prompt_from_eval_case(eval_case)
1260
+ prompt_instance_data = _content_to_instance_data(extracted_prompt)
1261
+
1262
+ instance_payload = types.EvaluationInstance(
1263
+ prompt=prompt_instance_data,
1264
+ response=_content_to_instance_data(response_content),
1265
+ reference=reference_instance_data,
1266
+ rubric_groups=eval_case.rubric_groups,
1267
+ agent_data=_eval_case_to_agent_data(eval_case),
1268
+ )
1269
+
1270
+ request_payload = {
1271
+ "instance": instance_payload,
1272
+ }
1273
+ return request_payload
1274
+
1275
+ @property
1276
+ def metric_name(self) -> str:
1277
+ return self.metric.name or "unknown_metric"
1278
+
1279
+ @override
1280
+ def get_metric_result(
1281
+ self, eval_case: types.EvalCase, response_index: int
1282
+ ) -> types.EvalCaseMetricResult:
1283
+ """Processes a single evaluation case using a MetricSource reference."""
1284
+ metric_name = self.metric_name
1285
+ metric_source = types.MetricSource(
1286
+ metric_resource_name=self.metric.metric_resource_name
1287
+ )
1288
+
1289
+ try:
1290
+ payload = self._build_request_payload(eval_case, response_index)
1291
+ api_response = _call_with_retry(
1292
+ lambda: self.module._evaluate_instances(
1293
+ metric_sources=[metric_source],
1294
+ instance=payload.get("instance"),
1295
+ autorater_config=payload.get("autorater_config"),
1296
+ ),
1297
+ metric_name,
1298
+ )
1299
+
1300
+ if api_response and api_response.metric_results:
1301
+ result_data = api_response.metric_results[0]
1302
+ error_message = None
1303
+ if result_data.error and getattr(result_data.error, "code"):
1304
+ error_message = f"Error in metric result: {result_data.error}"
1305
+ return types.EvalCaseMetricResult(
1306
+ metric_name=metric_name,
1307
+ score=result_data.score,
1308
+ explanation=result_data.explanation,
1309
+ rubric_verdicts=result_data.rubric_verdicts,
1310
+ error_message=error_message,
1311
+ )
1312
+ else:
1313
+ return types.EvalCaseMetricResult(
1314
+ metric_name=metric_name,
1315
+ error_message="Metric results missing in API response.",
1316
+ )
1317
+ except Exception as e:
1318
+ return types.EvalCaseMetricResult(
1319
+ metric_name=metric_name, error_message=str(e)
1320
+ )
1321
+
1322
+ @override
1323
+ def aggregate(
1324
+ self, eval_case_metric_results: list[types.EvalCaseMetricResult]
1325
+ ) -> types.AggregatedMetricResult:
1326
+ """Aggregates the metric results for a registered metric."""
1327
+ return _default_aggregate_scores(
1328
+ self.metric_name, eval_case_metric_results, calculate_pass_rate=True
1329
+ )
1330
+
1331
+
1332
+ _METRIC_HANDLER_MAPPING = [
1333
+ (
1334
+ lambda m: (
1335
+ # Recognize the user-facing class
1336
+ isinstance(m, types.CodeExecutionMetric)
1337
+ and (hasattr(m, "custom_function") and m.custom_function)
1338
+ )
1339
+ or (hasattr(m, "remote_custom_function") and m.remote_custom_function)
1340
+ # Recognize base Metric objects that have been coerced by Pydantic
1341
+ or (
1342
+ isinstance(m, types.Metric)
1343
+ and isinstance(getattr(m, "custom_function", None), str)
1344
+ ),
1345
+ CustomCodeExecutionMetricHandler,
1346
+ ),
1347
+ (
1348
+ lambda m: m.custom_function and isinstance(m.custom_function, Callable),
1349
+ CustomMetricHandler,
1350
+ ),
1351
+ (
1352
+ lambda m: getattr(m, "metric_resource_name", None) is not None,
1353
+ RegisteredMetricHandler,
1354
+ ),
1355
+ (
1356
+ lambda m: m.name in ComputationMetricHandler.SUPPORTED_COMPUTATION_METRICS,
1357
+ ComputationMetricHandler,
1358
+ ),
1359
+ (
1360
+ lambda m: m.name in TranslationMetricHandler.SUPPORTED_TRANSLATION_METRICS,
1361
+ TranslationMetricHandler,
1362
+ ),
1363
+ (
1364
+ lambda m: m.name in _evals_constant.SUPPORTED_PREDEFINED_METRICS,
1365
+ PredefinedMetricHandler,
1366
+ ),
1367
+ (lambda m: isinstance(m, types.LLMMetric), LLMMetricHandler),
1368
+ ]
1369
+
1370
+ MetricHandlerType = TypeVar(
1371
+ "MetricHandlerType",
1372
+ ComputationMetricHandler,
1373
+ TranslationMetricHandler,
1374
+ LLMMetricHandler,
1375
+ CustomMetricHandler,
1376
+ CustomCodeExecutionMetricHandler,
1377
+ PredefinedMetricHandler,
1378
+ )
1379
+
1380
+
1381
+ def get_handler_for_metric(
1382
+ module: "evals.Evals", metric: types.Metric
1383
+ ) -> Union[MetricHandlerType, Any]:
1384
+ """Returns a metric handler for the given metric."""
1385
+ for condition, handler_class in _METRIC_HANDLER_MAPPING:
1386
+ if condition(metric): # type: ignore[no-untyped-call]
1387
+ return handler_class(module=module, metric=metric)
1388
+ raise ValueError(f"Unsupported metric: {metric.name}")
1389
+
1390
+
1391
+ def calculate_win_rates(eval_result: types.EvaluationResult) -> dict[str, Any]:
1392
+ """Calculates win/tie rates for comparison results."""
1393
+ if not eval_result.eval_case_results:
1394
+ return {}
1395
+ max_models = max(
1396
+ (
1397
+ len(case.response_candidate_results)
1398
+ for case in eval_result.eval_case_results
1399
+ if case.response_candidate_results
1400
+ ),
1401
+ default=0,
1402
+ )
1403
+ if max_models == 0:
1404
+ return {}
1405
+ stats: collections.defaultdict[str, dict[str, Any]] = collections.defaultdict(
1406
+ lambda: {"wins": [0] * max_models, "ties": 0, "valid_comparisons": 0}
1407
+ )
1408
+ for case in eval_result.eval_case_results:
1409
+ if not case.response_candidate_results:
1410
+ continue
1411
+ scores_by_metric = collections.defaultdict(list)
1412
+ for idx, candidate in enumerate(case.response_candidate_results):
1413
+ for name, res in (
1414
+ candidate.metric_results.items() if candidate.metric_results else {}
1415
+ ):
1416
+ if res.score is not None:
1417
+ scores_by_metric[name].append({"score": res.score, "cand_idx": idx})
1418
+ for name, scores in scores_by_metric.items():
1419
+ if not scores:
1420
+ continue
1421
+ stats[name]["valid_comparisons"] += 1
1422
+ max_score = max(s["score"] for s in scores)
1423
+ winners = [s["cand_idx"] for s in scores if s["score"] == max_score]
1424
+ if len(winners) == 1:
1425
+ stats[name]["wins"][winners[0]] += 1
1426
+ else:
1427
+ stats[name]["ties"] += 1
1428
+ win_rates = {}
1429
+ for name, metric_stats in stats.items():
1430
+ if metric_stats["valid_comparisons"] > 0:
1431
+ win_rates[name] = {
1432
+ "win_rates": [
1433
+ w / metric_stats["valid_comparisons"] for w in metric_stats["wins"]
1434
+ ],
1435
+ "tie_rate": metric_stats["ties"] / metric_stats["valid_comparisons"],
1436
+ }
1437
+ return win_rates
1438
+
1439
+
1440
+ def _aggregate_metric_results(
1441
+ metric_handlers: list[MetricHandler[Any]],
1442
+ eval_case_results: list[types.EvalCaseResult],
1443
+ ) -> list[types.AggregatedMetricResult]:
1444
+ """Aggregates results by calling the aggregate method of each handler."""
1445
+ aggregated_metric_results = []
1446
+ logger.info("Aggregating results per metric...")
1447
+ for handler in metric_handlers:
1448
+ metric_name = handler.metric_name
1449
+ results_for_this_metric: list[types.EvalCaseMetricResult] = []
1450
+ for case_result in eval_case_results:
1451
+ if case_result.response_candidate_results:
1452
+ for response_candidate_res in case_result.response_candidate_results:
1453
+ if (
1454
+ response_candidate_res.metric_results
1455
+ and metric_name in response_candidate_res.metric_results
1456
+ and isinstance(metric_name, str)
1457
+ ):
1458
+ results_for_this_metric.append(
1459
+ response_candidate_res.metric_results[metric_name]
1460
+ )
1461
+ if not results_for_this_metric:
1462
+ logger.warning(
1463
+ "No results found for metric '%s' to aggregate.", metric_name
1464
+ )
1465
+ continue
1466
+
1467
+ try:
1468
+ summary = handler.aggregate(results_for_this_metric)
1469
+ aggregated_metric_results.append(summary)
1470
+ except NotImplementedError:
1471
+ logger.warning(
1472
+ "Aggregation not implemented for metric handler: %s (metric: '%s')."
1473
+ " Skipping summary.",
1474
+ type(handler).__name__,
1475
+ metric_name,
1476
+ )
1477
+ except Exception as e: # pylint: disable=broad-exception-caught
1478
+ logger.error(
1479
+ "Error during aggregation for metric '%s' using handler %s: %s",
1480
+ metric_name,
1481
+ type(handler).__name__,
1482
+ e,
1483
+ exc_info=True,
1484
+ )
1485
+ aggregated_metric_results.append(
1486
+ types.AggregatedMetricResult(
1487
+ metric_name=metric_name,
1488
+ num_cases_total=len(results_for_this_metric),
1489
+ num_cases_valid=0,
1490
+ num_cases_error=len(results_for_this_metric),
1491
+ mean_score=None,
1492
+ stdev_score=None,
1493
+ )
1494
+ )
1495
+ logger.debug("Finished aggregation, returning: %s", aggregated_metric_results)
1496
+ return aggregated_metric_results
1497
+
1498
+
1499
+ class EvaluationRunConfig(_common.BaseModel):
1500
+ """Configuration for an evaluation run."""
1501
+
1502
+ evals_module: Any
1503
+ """The module to be used for the evaluation run."""
1504
+ dataset: types.EvaluationDataset
1505
+ """The dataset to be used for the evaluation run."""
1506
+ metrics: list[types.Metric]
1507
+ """The list of metrics to be used for the evaluation run."""
1508
+ num_response_candidates: int
1509
+ """The number of response candidates for the evaluation run."""
1510
+
1511
+
1512
+ def _rate_limited_get_metric_result(
1513
+ rate_limiter: _evals_utils.RateLimiter,
1514
+ handler: MetricHandler[Any],
1515
+ eval_case: types.EvalCase,
1516
+ response_index: int,
1517
+ ) -> types.EvalCaseMetricResult:
1518
+ """Wraps a handler's get_metric_result with rate limiting."""
1519
+ rate_limiter.sleep_and_advance()
1520
+ return handler.get_metric_result(eval_case, response_index)
1521
+
1522
+
1523
+ def compute_metrics_and_aggregate(
1524
+ evaluation_run_config: EvaluationRunConfig,
1525
+ evaluation_service_qps: Optional[float] = None,
1526
+ ) -> types.EvaluationResult:
1527
+ """Computes metrics and aggregates them for a given evaluation run config.
1528
+
1529
+ Args:
1530
+ evaluation_run_config: The configuration for the evaluation run.
1531
+ evaluation_service_qps: Optional QPS limit for the evaluation service.
1532
+ Defaults to _DEFAULT_EVAL_SERVICE_QPS (10). Users with higher
1533
+ quotas can increase this value.
1534
+ """
1535
+ metric_handlers = []
1536
+ all_futures = []
1537
+ results_by_case_response_metric: collections.defaultdict[
1538
+ Any, collections.defaultdict[Any, dict[Any, Any]]
1539
+ ] = collections.defaultdict(lambda: collections.defaultdict(dict))
1540
+ submission_errors = []
1541
+ execution_errors = []
1542
+ case_indices_with_errors = set()
1543
+
1544
+ if evaluation_service_qps is not None and evaluation_service_qps <= 0:
1545
+ raise ValueError("evaluation_service_qps must be a positive number.")
1546
+ qps = evaluation_service_qps or _evals_utils._DEFAULT_EVAL_SERVICE_QPS
1547
+ rate_limiter = _evals_utils.RateLimiter(rate=qps)
1548
+ logger.info("Rate limiting evaluation service requests to %.1f QPS.", qps)
1549
+
1550
+ for eval_metric in evaluation_run_config.metrics:
1551
+ metric_handlers.append(
1552
+ get_handler_for_metric(evaluation_run_config.evals_module, eval_metric)
1553
+ )
1554
+
1555
+ eval_case_count = len(evaluation_run_config.dataset.eval_cases)
1556
+ logger.info("Total number of evaluation cases: %d", eval_case_count)
1557
+ logger.info(
1558
+ "Number of response candidates: %d",
1559
+ evaluation_run_config.num_response_candidates,
1560
+ )
1561
+ total_metric_computations = (
1562
+ eval_case_count
1563
+ * len(metric_handlers)
1564
+ * evaluation_run_config.num_response_candidates
1565
+ )
1566
+ logger.info("Total number of metric computations: %d", total_metric_computations)
1567
+
1568
+ with tqdm(
1569
+ total=total_metric_computations,
1570
+ desc="Computing Metrics for Evaluation Dataset",
1571
+ ) as pbar:
1572
+ with futures.ThreadPoolExecutor(
1573
+ max_workers=_evals_common.MAX_WORKERS
1574
+ ) as executor:
1575
+ for metric_handler_instance in metric_handlers:
1576
+ for eval_case_index, eval_case in enumerate(
1577
+ evaluation_run_config.dataset.eval_cases
1578
+ ):
1579
+ num_responses = (
1580
+ len(eval_case.responses) if eval_case.responses else 0
1581
+ )
1582
+ if num_responses == 0 and getattr(eval_case, "agent_data", None):
1583
+ num_responses = 1
1584
+
1585
+ actual_num_candidates_for_case = min(
1586
+ evaluation_run_config.num_response_candidates,
1587
+ num_responses,
1588
+ )
1589
+ for response_index in range(actual_num_candidates_for_case):
1590
+ try:
1591
+ future = executor.submit(
1592
+ _rate_limited_get_metric_result,
1593
+ rate_limiter,
1594
+ metric_handler_instance,
1595
+ eval_case,
1596
+ response_index,
1597
+ )
1598
+ future.add_done_callback(lambda _: pbar.update(1))
1599
+ logger.debug(
1600
+ "Submitting metric computation for case %d, "
1601
+ "response %d for metric %s.",
1602
+ eval_case_index,
1603
+ response_index,
1604
+ metric_handler_instance.metric_name,
1605
+ )
1606
+ all_futures.append(
1607
+ (
1608
+ future,
1609
+ metric_handler_instance.metric_name,
1610
+ eval_case_index,
1611
+ response_index,
1612
+ )
1613
+ )
1614
+ except Exception as e: # pylint: disable=broad-exception-caught
1615
+ logger.error(
1616
+ "Error submitting metric computation for case %d, "
1617
+ "response %d for metric %s: %s",
1618
+ eval_case_index,
1619
+ response_index,
1620
+ metric_handler_instance.metric_name,
1621
+ e,
1622
+ exc_info=True,
1623
+ )
1624
+ submission_errors.append(
1625
+ (
1626
+ metric_handler_instance.metric_name,
1627
+ eval_case_index,
1628
+ response_index,
1629
+ f"Error: {e}",
1630
+ )
1631
+ )
1632
+ error_result = types.EvalCaseMetricResult(
1633
+ metric_name=metric_handler_instance.metric_name,
1634
+ error_message=f"Submission Error: {e}",
1635
+ )
1636
+ results_by_case_response_metric[eval_case_index][
1637
+ response_index
1638
+ ][metric_handler_instance.metric_name] = error_result
1639
+ case_indices_with_errors.add(eval_case_index)
1640
+ pbar.update(1)
1641
+
1642
+ for future, metric_name, eval_case_index, response_index in all_futures:
1643
+ try:
1644
+ eval_case_metric_result = future.result()
1645
+ logger.debug(
1646
+ "Successfully obtained result for metric '%s', case %d, response"
1647
+ " %d: %s.",
1648
+ metric_name,
1649
+ eval_case_index,
1650
+ response_index,
1651
+ eval_case_metric_result,
1652
+ )
1653
+ results_by_case_response_metric[eval_case_index][response_index][
1654
+ metric_name
1655
+ ] = eval_case_metric_result
1656
+ logger.debug(
1657
+ "Stored result for metric '%s', case %d, response %d.",
1658
+ metric_name,
1659
+ eval_case_index,
1660
+ response_index,
1661
+ )
1662
+ except Exception as e: # pylint: disable=broad-exception-caught
1663
+ logger.error(
1664
+ "Error executing metric '%s' for case %s, response %s: %s",
1665
+ metric_name,
1666
+ eval_case_index,
1667
+ response_index,
1668
+ e,
1669
+ exc_info=True,
1670
+ )
1671
+ error_msg = (
1672
+ f"Error executing metric '{metric_name}' for case"
1673
+ f" {eval_case_index}, response {response_index}: {e}"
1674
+ )
1675
+ execution_errors.append(
1676
+ (
1677
+ metric_name,
1678
+ eval_case_index,
1679
+ response_index,
1680
+ error_msg,
1681
+ )
1682
+ )
1683
+ case_indices_with_errors.add(eval_case_index)
1684
+ error_result = types.EvalCaseMetricResult(
1685
+ metric_name=metric_name,
1686
+ error_message=error_msg,
1687
+ )
1688
+ results_by_case_response_metric[eval_case_index][response_index][
1689
+ metric_name
1690
+ ] = error_result
1691
+
1692
+ final_eval_case_results = []
1693
+ sorted_eval_case_indices = sorted(results_by_case_response_metric.keys())
1694
+ for eval_case_index in sorted_eval_case_indices:
1695
+ per_response_results_for_this_case = results_by_case_response_metric[
1696
+ eval_case_index
1697
+ ]
1698
+
1699
+ current_response_candidate_results_list = []
1700
+ sorted_response_indices = sorted(per_response_results_for_this_case.keys())
1701
+
1702
+ for response_index in sorted_response_indices:
1703
+ metric_results_for_this_response = per_response_results_for_this_case[
1704
+ response_index
1705
+ ]
1706
+
1707
+ response_candidate_result_obj = types.ResponseCandidateResult(
1708
+ response_index=response_index,
1709
+ metric_results=metric_results_for_this_response,
1710
+ )
1711
+ current_response_candidate_results_list.append(
1712
+ response_candidate_result_obj
1713
+ )
1714
+
1715
+ if current_response_candidate_results_list:
1716
+ eval_case_result = types.EvalCaseResult(
1717
+ eval_case_index=eval_case_index,
1718
+ response_candidate_results=current_response_candidate_results_list,
1719
+ )
1720
+ final_eval_case_results.append(eval_case_result)
1721
+ elif eval_case_index in case_indices_with_errors or any(
1722
+ err_case_idx == eval_case_index
1723
+ for _, err_case_idx, _, _ in submission_errors
1724
+ ):
1725
+ logger.warning(
1726
+ "EvalCase %d had errors but no metric results were"
1727
+ " processed into the structure.",
1728
+ eval_case_index,
1729
+ )
1730
+ eval_case_result = types.EvalCaseResult(
1731
+ eval_case_index=eval_case_index,
1732
+ response_candidate_results=[],
1733
+ )
1734
+ final_eval_case_results.append(eval_case_result)
1735
+
1736
+ if submission_errors:
1737
+ logger.warning("Encountered %d submission errors.", len(submission_errors))
1738
+ logger.warning("Submission errors: %s", submission_errors)
1739
+ if execution_errors:
1740
+ logger.warning("Encountered %d execution errors.", len(execution_errors))
1741
+ logger.warning("Execution errors: %s", execution_errors)
1742
+
1743
+ aggregated_metric_results = _aggregate_metric_results(
1744
+ metric_handlers, final_eval_case_results
1745
+ )
1746
+ eval_result = types.EvaluationResult(
1747
+ eval_case_results=final_eval_case_results,
1748
+ summary_metrics=aggregated_metric_results,
1749
+ )
1750
+ if evaluation_run_config.num_response_candidates > 1:
1751
+ try:
1752
+ eval_result.win_rates = calculate_win_rates(eval_result)
1753
+ except Exception as e: # pylint: disable=broad-exception-caught
1754
+ logger.error("Error calculating win rates: %s", e, exc_info=True)
1755
+ return eval_result
data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/_evals_metric_loaders.py ADDED
@@ -0,0 +1,381 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2025 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
+ """Utility functions for evals."""
16
+
17
+ import json
18
+ import logging
19
+ import os
20
+ import re
21
+ from typing import Any, Optional, Union, TYPE_CHECKING
22
+
23
+ import yaml
24
+
25
+ from . import _evals_constant
26
+ from . import _gcs_utils
27
+
28
+ if TYPE_CHECKING:
29
+ from . import types
30
+
31
+
32
+ logger = logging.getLogger(__name__)
33
+
34
+
35
+ class LazyLoadedPrebuiltMetric:
36
+ """A proxy object representing a prebuilt metric to be loaded on demand.
37
+
38
+ This can resolve to either an API Predefined Metric or an LLM Metric
39
+ loaded from GCS.
40
+ """
41
+
42
+ _cache: dict[str, "types.Metric"] = {}
43
+ _base_gcs_path = (
44
+ "gs://vertex-ai-generative-ai-eval-sdk-resources/metrics/{metric_name}/"
45
+ )
46
+
47
+ def __init__(self, name: str, version: Optional[str] = None, **kwargs: Any):
48
+ self.name = name.upper()
49
+ self.version = version
50
+ self.metric_kwargs = kwargs
51
+ self._resolved_metric: Optional["types.Metric"] = None
52
+
53
+ def _get_api_metric_spec_name(self) -> Optional[str]:
54
+ """Constructs the metric_spec_name for API Predefined Metrics."""
55
+ base_name = self.name.lower()
56
+ if self.version:
57
+ # Explicit version provided
58
+ version = self.version.lower()
59
+ potential_name = f"{base_name}_{version}"
60
+ return (
61
+ potential_name
62
+ if potential_name in _evals_constant.SUPPORTED_PREDEFINED_METRICS
63
+ else None
64
+ )
65
+ else:
66
+ # Default versioning: Try _v1, then base name
67
+ v1_name = f"{base_name}_v1"
68
+ if v1_name in _evals_constant.SUPPORTED_PREDEFINED_METRICS:
69
+ return v1_name
70
+ if base_name in _evals_constant.SUPPORTED_PREDEFINED_METRICS:
71
+ return base_name
72
+ return None
73
+
74
+ def _resolve_api_predefined(self) -> Optional["types.Metric"]:
75
+ """Attempts to resolve as an API Predefined Metric."""
76
+ from . import types
77
+
78
+ metric_spec_name = self._get_api_metric_spec_name()
79
+ if metric_spec_name:
80
+ logger.info(
81
+ "Resolving '%s' as API Predefined Metric with spec name: %s",
82
+ self.name,
83
+ metric_spec_name,
84
+ )
85
+ return types.Metric(name=metric_spec_name, **self.metric_kwargs)
86
+ return None
87
+
88
+ def _get_latest_version_uri(self, api_client: Any, metric_gcs_dir: str) -> str:
89
+ """Lists files in GCS directory and determines the latest version URI."""
90
+ gcs_utils = _gcs_utils.GcsUtils(api_client)
91
+ bucket_name, prefix = gcs_utils.parse_gcs_path(metric_gcs_dir)
92
+
93
+ blobs = gcs_utils.storage_client.list_blobs(bucket_name, prefix=prefix)
94
+
95
+ version_files: list[dict[str, Union[list[int], str]]] = (
96
+ []
97
+ ) # {'version_parts': [1,0,0], 'filename': 'v1.0.0.yaml'}
98
+
99
+ version_pattern = re.compile(
100
+ r"v(\d+)(?:\.(\d+))?(?:\.(\d+))?\.(yaml|yml|json)$", re.IGNORECASE
101
+ )
102
+
103
+ for blob in blobs:
104
+ match = version_pattern.match(os.path.basename(blob.name))
105
+ if match:
106
+ major = int(match.group(1))
107
+ minor = int(match.group(2)) if match.group(2) else 0
108
+ patch = int(match.group(3)) if match.group(3) else 0
109
+ version_files.append(
110
+ {
111
+ "version_parts": [major, minor, patch],
112
+ "filename": os.path.basename(blob.name),
113
+ }
114
+ )
115
+
116
+ if not version_files:
117
+ raise IOError(f"No versioned metric files found in {metric_gcs_dir}")
118
+
119
+ version_files.sort(key=lambda x: x["version_parts"], reverse=True)
120
+
121
+ latest_filename = version_files[0]["filename"]
122
+ return os.path.join(metric_gcs_dir, latest_filename)
123
+
124
+ def _fetch_and_parse(self, api_client: Any) -> "types.LLMMetric":
125
+ """Fetches and parses the metric definition from GCS."""
126
+
127
+ from . import types
128
+
129
+ metric_gcs_dir = self._base_gcs_path.format(metric_name=self.name.lower())
130
+ uri: str
131
+ if self.version == "latest" or self.version is None:
132
+ uri = self._get_latest_version_uri(api_client, metric_gcs_dir)
133
+ resolved_version_match = re.match(
134
+ r"(v\d+(?:\.\d+)*)\.(?:yaml|yml|json)",
135
+ os.path.basename(uri),
136
+ re.IGNORECASE,
137
+ )
138
+ if resolved_version_match:
139
+ self.version = resolved_version_match.group(1)
140
+ else:
141
+ # Fallback if regex fails
142
+ self.version = os.path.splitext(os.path.basename(uri))[0]
143
+ else:
144
+ yaml_uri = os.path.join(metric_gcs_dir, f"{self.version}.yaml")
145
+ json_uri = os.path.join(metric_gcs_dir, f"{self.version}.json")
146
+
147
+ gcs_utils = _gcs_utils.GcsUtils(api_client)
148
+ try:
149
+ bucket_name, blob_path = gcs_utils.parse_gcs_path(yaml_uri)
150
+ if (
151
+ gcs_utils.storage_client.bucket(bucket_name)
152
+ .blob(blob_path)
153
+ .exists()
154
+ ):
155
+ uri = yaml_uri
156
+ else:
157
+ bucket_name_json, blob_path_json = gcs_utils.parse_gcs_path(
158
+ json_uri
159
+ )
160
+ if (
161
+ gcs_utils.storage_client.bucket(bucket_name_json)
162
+ .blob(blob_path_json)
163
+ .exists()
164
+ ):
165
+ uri = json_uri
166
+ else:
167
+ raise IOError(
168
+ f"Metric file for version '{self.version}' "
169
+ f"not found as .yaml or .json in {metric_gcs_dir}"
170
+ )
171
+ except Exception as e:
172
+ raise IOError(
173
+ f"Error checking for metric file version '{self.version}' in"
174
+ f" {metric_gcs_dir}: {e}"
175
+ ) from e
176
+
177
+ logger.info(
178
+ "Fetching predefined metric '%s@%s' from %s...",
179
+ self.name,
180
+ self.version,
181
+ uri,
182
+ )
183
+
184
+ gcs_utils = _gcs_utils.GcsUtils(api_client)
185
+ content_str = gcs_utils.read_file_contents(uri)
186
+
187
+ file_extension = os.path.splitext(uri)[1].lower()
188
+ data: dict[str, Any]
189
+ if file_extension == ".yaml" or file_extension == ".yml":
190
+ if yaml is None:
191
+ raise ImportError(
192
+ "YAML parsing requires the pyyaml library. Please install it"
193
+ " with `pip install google-cloud-aiplatform[evaluation]`."
194
+ )
195
+ data = yaml.safe_load(content_str)
196
+ elif file_extension == ".json":
197
+ data = json.loads(content_str)
198
+ else:
199
+ raise ValueError(f"Unsupported file extension: {file_extension}")
200
+
201
+ if not isinstance(data, dict):
202
+ raise ValueError("Metric config content did not parse into a dictionary.")
203
+
204
+ metric_obj = types.LLMMetric.model_validate({**data, **self.metric_kwargs})
205
+ metric_obj._is_predefined = True
206
+ metric_obj._config_source = uri
207
+ metric_obj._version = self.version
208
+ return metric_obj
209
+
210
+ def resolve(self, api_client: Any) -> "types.Metric":
211
+ """Resolves the metric by checking API Predefined, then GCS, caching results."""
212
+ if self._resolved_metric:
213
+ return self._resolved_metric
214
+
215
+ cache_key = f"{self.name}@{self.version or 'default'}"
216
+ if cache_key in LazyLoadedPrebuiltMetric._cache:
217
+ self._resolved_metric = LazyLoadedPrebuiltMetric._cache[cache_key]
218
+ logger.debug("Metric '%s' found in cache.", cache_key)
219
+ return self._resolved_metric
220
+
221
+ # Try resolving as API Predefined Metric first
222
+ api_metric = self._resolve_api_predefined()
223
+ if api_metric:
224
+ self._resolved_metric = api_metric
225
+ LazyLoadedPrebuiltMetric._cache[cache_key] = self._resolved_metric
226
+ return self._resolved_metric
227
+
228
+ # Fallback to GCS loading for custom LLM-based Prebuilt Metrics
229
+ logger.debug(
230
+ "Metric '%s' not an API Predefined Metric, trying GCS...", self.name
231
+ )
232
+ try:
233
+ gcs_metric = self._fetch_and_parse(api_client)
234
+ final_cache_key = f"{self.name}@{self.version}"
235
+ LazyLoadedPrebuiltMetric._cache[final_cache_key] = gcs_metric
236
+ self._resolved_metric = gcs_metric
237
+ return self._resolved_metric
238
+ except Exception as e:
239
+ logger.error(
240
+ "Error loading metric %s (requested version: %s) from GCS: %s",
241
+ self.name,
242
+ self.version,
243
+ e,
244
+ )
245
+ raise ValueError(
246
+ f"Metric '{self.name}' could not be resolved as an API "
247
+ "Predefined Metric or loaded from GCS."
248
+ ) from e
249
+
250
+ def __call__(
251
+ self, version: Optional[str] = None, **kwargs: Any
252
+ ) -> "LazyLoadedPrebuiltMetric":
253
+ """Allows setting a specific version and other metric attributes."""
254
+ updated_kwargs = self.metric_kwargs.copy()
255
+ updated_kwargs.update(kwargs)
256
+ return LazyLoadedPrebuiltMetric(
257
+ name=self.name, version=version or self.version, **updated_kwargs
258
+ )
259
+
260
+
261
+ class PrebuiltMetricLoader:
262
+ """Provides access to predefined evaluation metrics via attributes.
263
+
264
+ This class provides a set of predefined LLM-based metrics (Autorater recipes)
265
+ for evaluation. These metrics are lazily loaded from a GCS repository
266
+ when they are first accessed.
267
+
268
+ Example:
269
+ from agentplatform import types
270
+ text_quality_metric = types.RubricMetric.TEXT_QUALITY
271
+ """
272
+
273
+ def __getattr__(
274
+ self, name: str, version: Optional[str] = None, **kwargs: Any
275
+ ) -> LazyLoadedPrebuiltMetric:
276
+ return LazyLoadedPrebuiltMetric(name=name, version=version, **kwargs)
277
+
278
+ @property
279
+ def GENERAL_QUALITY(self) -> LazyLoadedPrebuiltMetric:
280
+ return self.__getattr__("GENERAL_QUALITY")
281
+
282
+ @property
283
+ def TEXT_QUALITY(self) -> LazyLoadedPrebuiltMetric:
284
+ return self.__getattr__("TEXT_QUALITY")
285
+
286
+ @property
287
+ def INSTRUCTION_FOLLOWING(self) -> LazyLoadedPrebuiltMetric:
288
+ return self.__getattr__("INSTRUCTION_FOLLOWING")
289
+
290
+ @property
291
+ def SAFETY(self) -> LazyLoadedPrebuiltMetric:
292
+ return self.__getattr__("SAFETY")
293
+
294
+ @property
295
+ def MULTI_TURN_GENERAL_QUALITY(self) -> LazyLoadedPrebuiltMetric:
296
+ return self.__getattr__("MULTI_TURN_GENERAL_QUALITY")
297
+
298
+ @property
299
+ def MULTI_TURN_TEXT_QUALITY(self) -> LazyLoadedPrebuiltMetric:
300
+ return self.__getattr__("MULTI_TURN_TEXT_QUALITY")
301
+
302
+ @property
303
+ def MULTI_TURN_TOOL_USE_QUALITY(self) -> LazyLoadedPrebuiltMetric:
304
+ return self.__getattr__("MULTI_TURN_TOOL_USE_QUALITY", version="v1")
305
+
306
+ @property
307
+ def MULTI_TURN_TRAJECTORY_QUALITY(self) -> LazyLoadedPrebuiltMetric:
308
+ return self.__getattr__("MULTI_TURN_TRAJECTORY_QUALITY", version="v1")
309
+
310
+ @property
311
+ def MULTI_TURN_TASK_SUCCESS(self) -> LazyLoadedPrebuiltMetric:
312
+ return self.__getattr__("MULTI_TURN_TASK_SUCCESS", version="v1")
313
+
314
+ @property
315
+ def FINAL_RESPONSE_MATCH(self) -> LazyLoadedPrebuiltMetric:
316
+ return self.__getattr__("FINAL_RESPONSE_MATCH", version="v2")
317
+
318
+ @property
319
+ def FINAL_RESPONSE_REFERENCE_FREE(self) -> LazyLoadedPrebuiltMetric:
320
+ return self.__getattr__("FINAL_RESPONSE_REFERENCE_FREE")
321
+
322
+ @property
323
+ def COHERENCE(self) -> LazyLoadedPrebuiltMetric:
324
+ return self.__getattr__("COHERENCE")
325
+
326
+ @property
327
+ def FLUENCY(self) -> LazyLoadedPrebuiltMetric:
328
+ return self.__getattr__("FLUENCY")
329
+
330
+ @property
331
+ def VERBOSITY(self) -> LazyLoadedPrebuiltMetric:
332
+ return self.__getattr__("VERBOSITY")
333
+
334
+ @property
335
+ def SUMMARIZATION_QUALITY(self) -> LazyLoadedPrebuiltMetric:
336
+ return self.__getattr__("SUMMARIZATION_QUALITY")
337
+
338
+ @property
339
+ def QUESTION_ANSWERING_QUALITY(self) -> LazyLoadedPrebuiltMetric:
340
+ return self.__getattr__("QUESTION_ANSWERING_QUALITY")
341
+
342
+ @property
343
+ def MULTI_TURN_CHAT_QUALITY(self) -> LazyLoadedPrebuiltMetric:
344
+ return self.__getattr__("MULTI_TURN_CHAT_QUALITY")
345
+
346
+ @property
347
+ def MULTI_TURN_SAFETY(self) -> LazyLoadedPrebuiltMetric:
348
+ return self.__getattr__("MULTI_TURN_SAFETY")
349
+
350
+ @property
351
+ def FINAL_RESPONSE_QUALITY(self) -> LazyLoadedPrebuiltMetric:
352
+ return self.__getattr__("FINAL_RESPONSE_QUALITY")
353
+
354
+ @property
355
+ def HALLUCINATION(self) -> LazyLoadedPrebuiltMetric:
356
+ return self.__getattr__("HALLUCINATION")
357
+
358
+ @property
359
+ def TOOL_USE_QUALITY(self) -> LazyLoadedPrebuiltMetric:
360
+ return self.__getattr__("TOOL_USE_QUALITY")
361
+
362
+ @property
363
+ def GECKO_TEXT2IMAGE(self) -> LazyLoadedPrebuiltMetric:
364
+ return self.__getattr__("GECKO_TEXT2IMAGE")
365
+
366
+ @property
367
+ def GECKO_TEXT2VIDEO(self) -> LazyLoadedPrebuiltMetric:
368
+ return self.__getattr__("GECKO_TEXT2VIDEO")
369
+
370
+
371
+ PrebuiltMetric = PrebuiltMetricLoader()
372
+ RubricMetric = PrebuiltMetric
373
+
374
+
375
+ def CodeExecutionMetric(
376
+ name: str, custom_function: str, **kwargs: Any
377
+ ) -> "types.Metric":
378
+ """Instantiates a code execution metric."""
379
+ from . import types
380
+
381
+ return types.Metric(name=name, remote_custom_function=custom_function, **kwargs)
data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/_evals_utils.py ADDED
@@ -0,0 +1,1043 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2025 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
+ """Utility functions for evals."""
16
+
17
+ import abc
18
+ import asyncio
19
+ import json
20
+ import logging
21
+ import os
22
+ import threading
23
+ import time
24
+ from typing import Any, Optional, Union
25
+
26
+ from google.genai._api_client import BaseApiClient
27
+ from google.genai._common import get_value_by_path as getv
28
+ from google.genai._common import set_value_by_path as setv
29
+ import pandas as pd
30
+
31
+ from . import _bigquery_utils
32
+ from . import _gcs_utils
33
+ from . import _transformers
34
+ from . import types
35
+
36
+
37
+ logger = logging.getLogger(__name__)
38
+
39
+
40
+ GCS_PREFIX = "gs://"
41
+ BQ_PREFIX = "bq://"
42
+ _DEFAULT_EVAL_SERVICE_QPS = 10
43
+
44
+
45
+ class RateLimiter:
46
+ """Helper class for rate-limiting requests to Vertex AI to improve QoS.
47
+
48
+ Implements a token bucket algorithm to limit the rate at which API calls
49
+ can occur. Designed for cases where the batch size is always 1 for traffic
50
+ shaping and rate limiting.
51
+
52
+ Attributes:
53
+ seconds_per_event: The time interval (in seconds) between events to
54
+ maintain the desired rate.
55
+ last: The timestamp of the last event.
56
+ _lock: A lock to ensure thread safety.
57
+ """
58
+
59
+ def __init__(self, rate: float) -> None:
60
+ """Initializes the rate limiter.
61
+
62
+ Args:
63
+ rate: The number of queries allowed per second.
64
+
65
+ Raises:
66
+ ValueError: If the rate is not positive.
67
+ """
68
+ if not rate or rate <= 0:
69
+ raise ValueError("Rate must be a positive number")
70
+ self.seconds_per_event = 1.0 / rate
71
+ self._next_allowed = time.monotonic()
72
+ self._lock = threading.Lock()
73
+
74
+ def sleep_and_advance(self) -> None:
75
+ """Blocks the current thread until the next event can be admitted.
76
+
77
+ The lock is held only long enough to reserve a time slot. The
78
+ actual sleep happens outside the lock so that multiple threads
79
+ can be sleeping concurrently with staggered wake-up times.
80
+ """
81
+ with self._lock:
82
+ now = time.monotonic()
83
+ wait_until = max(now, self._next_allowed)
84
+ delay = wait_until - now
85
+ self._next_allowed = wait_until + self.seconds_per_event
86
+
87
+ if delay > 0:
88
+ time.sleep(delay)
89
+
90
+
91
+ class EvalDatasetLoader:
92
+ """A loader for datasets from various sources, using a shared client."""
93
+
94
+ def __init__(self, api_client: BaseApiClient) -> None:
95
+ self.api_client = api_client
96
+ self.gcs_utils = _gcs_utils.GcsUtils(self.api_client)
97
+ self.bigquery_utils = _bigquery_utils.BigQueryUtils(self.api_client)
98
+
99
+ def _load_file(
100
+ self, filepath: str, file_type: str
101
+ ) -> Union[list[dict[str, Any]], Any]:
102
+ """Loads data from a file into a list of dictionaries."""
103
+ if filepath.startswith(GCS_PREFIX):
104
+ df = self.gcs_utils.read_gcs_file_to_dataframe(filepath, file_type)
105
+ return df.to_dict(orient="records")
106
+ else:
107
+ if file_type == "jsonl":
108
+ df = pd.read_json(filepath, lines=True)
109
+ return df.to_dict(orient="records")
110
+ elif file_type == "csv":
111
+ df = pd.read_csv(filepath, encoding="utf-8")
112
+ return df.to_dict(orient="records")
113
+ else:
114
+ raise ValueError(
115
+ f"Unsupported file type: '{file_type}'. Please provide 'jsonl' or"
116
+ " 'csv'."
117
+ )
118
+
119
+ def load(
120
+ self, source: Union[str, "pd.DataFrame"]
121
+ ) -> Union[list[dict[str, Any]], Any]:
122
+ """Loads dataset from various sources into a list of dictionaries."""
123
+ if isinstance(source, pd.DataFrame):
124
+ return source.to_dict(orient="records")
125
+ elif isinstance(source, str):
126
+ if source.startswith(BQ_PREFIX):
127
+ df = self.bigquery_utils.load_bigquery_to_dataframe(
128
+ source[len(BQ_PREFIX) :]
129
+ )
130
+ return df.to_dict(orient="records")
131
+
132
+ _, extension = os.path.splitext(source)
133
+ file_type = extension.lower()[1:]
134
+
135
+ if file_type == "jsonl":
136
+ return self._load_file(source, "jsonl")
137
+ elif file_type == "csv":
138
+ return self._load_file(source, "csv")
139
+ else:
140
+ raise TypeError(
141
+ f"Unsupported file type: {file_type} from {source}. Please"
142
+ " provide a valid GCS path with `jsonl` or `csv` suffix, "
143
+ "a local file path, or a valid BigQuery table URI."
144
+ )
145
+ else:
146
+ raise TypeError(
147
+ "Unsupported dataset type. Must be a `pd.DataFrame`, Python"
148
+ " a valid GCS path with `jsonl` or `csv` suffix, a local"
149
+ " file path, or a valid BigQuery table URI."
150
+ )
151
+
152
+
153
+ class BatchEvaluateRequestPreparer:
154
+ """Prepares data for requests."""
155
+
156
+ @staticmethod
157
+ def _EvaluationDataset_to_vertex(
158
+ from_object: Union[dict[str, Any], object],
159
+ parent_object: Optional[dict[str, Any]] = None,
160
+ ) -> dict[str, Any]:
161
+ to_object: dict[str, Any] = {}
162
+
163
+ if getv(from_object, ["gcs_source"]) is not None:
164
+ setv(
165
+ to_object,
166
+ ["gcs_source"],
167
+ getv(from_object, ["gcs_source"]),
168
+ )
169
+
170
+ if getv(from_object, ["bigquery_source"]) is not None:
171
+ setv(
172
+ to_object,
173
+ ["bigquery_source"],
174
+ getv(from_object, ["bigquery_source"]),
175
+ )
176
+
177
+ return to_object
178
+
179
+ @staticmethod
180
+ def _Metric_to_vertex(
181
+ from_object: Union[dict[str, Any], object],
182
+ parent_object: Optional[dict[str, Any]] = None,
183
+ ) -> dict[str, Any]:
184
+ to_object: dict[str, Any] = {}
185
+
186
+ if getv(from_object, ["prompt_template"]) is not None:
187
+ setv(
188
+ to_object,
189
+ ["pointwise_metric_spec", "prompt_template"],
190
+ getv(from_object, ["prompt_template"]),
191
+ )
192
+
193
+ if getv(from_object, ["judge_model"]) is not None:
194
+ setv(
195
+ parent_object,
196
+ ["autorater_config", "autorater_model"],
197
+ getv(from_object, ["judge_model"]),
198
+ )
199
+
200
+ if getv(from_object, ["judge_model_sampling_count"]) is not None:
201
+ setv(
202
+ parent_object,
203
+ ["autorater_config", "sampling_count"],
204
+ getv(from_object, ["judge_model_sampling_count"]),
205
+ )
206
+
207
+ if getv(from_object, ["judge_model_system_instruction"]) is not None:
208
+ setv(
209
+ to_object,
210
+ ["pointwise_metric_spec", "system_instruction"],
211
+ getv(from_object, ["judge_model_system_instruction"]),
212
+ )
213
+
214
+ if getv(from_object, ["return_raw_output"]) is not None:
215
+ setv(
216
+ to_object,
217
+ [
218
+ "pointwise_metric_spec",
219
+ "custom_output_format_config",
220
+ "return_raw_output",
221
+ ],
222
+ getv(from_object, ["return_raw_output"]),
223
+ )
224
+
225
+ return to_object
226
+
227
+ @staticmethod
228
+ def _OutputConfig_to_vertex(
229
+ from_object: Union[dict[str, Any], object],
230
+ parent_object: Optional[dict[str, Any]] = None,
231
+ ) -> dict[str, Any]:
232
+ to_object: dict[str, Any] = {}
233
+ if getv(from_object, ["gcs_destination"]) is not None:
234
+ setv(
235
+ to_object,
236
+ ["gcsDestination"],
237
+ getv(from_object, ["gcs_destination"]),
238
+ )
239
+
240
+ return to_object
241
+
242
+ @staticmethod
243
+ def _EvaluationDataset_from_vertex(
244
+ from_object: Union[dict[str, Any], object],
245
+ parent_object: Optional[dict[str, Any]] = None,
246
+ ) -> dict[str, Any]:
247
+ to_object: dict[str, Any] = {}
248
+
249
+ if getv(from_object, ["dataset", "gcs_source"]) is not None:
250
+ setv(
251
+ to_object,
252
+ ["gcs_source"],
253
+ getv(from_object, ["dataset", "gcs_source"]),
254
+ )
255
+
256
+ if getv(from_object, ["dataset", "bigquery_source"]) is not None:
257
+ setv(
258
+ to_object,
259
+ ["bigquery_source"],
260
+ getv(from_object, ["dataset", "bigquery_source"]),
261
+ )
262
+
263
+ return to_object
264
+
265
+ @staticmethod
266
+ def _AutoraterConfig_to_vertex(
267
+ from_object: Union[dict[str, Any], object],
268
+ parent_object: Optional[dict[str, Any]] = None,
269
+ ) -> dict[str, Any]:
270
+ to_object: dict[str, Any] = {}
271
+ if getv(from_object, ["sampling_count"]) is not None:
272
+ setv(to_object, ["samplingCount"], getv(from_object, ["sampling_count"]))
273
+
274
+ if getv(from_object, ["flip_enabled"]) is not None:
275
+ setv(to_object, ["flipEnabled"], getv(from_object, ["flip_enabled"]))
276
+
277
+ if getv(from_object, ["autorater_model"]) is not None:
278
+ setv(
279
+ to_object,
280
+ ["autoraterModel"],
281
+ getv(from_object, ["autorater_model"]),
282
+ )
283
+
284
+ return to_object
285
+
286
+ @staticmethod
287
+ def EvaluateDatasetOperation_from_vertex(
288
+ from_object: Union[dict[str, Any], object],
289
+ parent_object: Optional[dict[str, Any]] = None,
290
+ ) -> dict[str, Any]:
291
+ to_object: dict[str, Any] = {}
292
+ if getv(from_object, ["name"]) is not None:
293
+ setv(to_object, ["name"], getv(from_object, ["name"]))
294
+
295
+ if getv(from_object, ["metadata"]) is not None:
296
+ setv(to_object, ["metadata"], getv(from_object, ["metadata"]))
297
+
298
+ if getv(from_object, ["done"]) is not None:
299
+ setv(to_object, ["done"], getv(from_object, ["done"]))
300
+
301
+ if getv(from_object, ["error"]) is not None:
302
+ setv(to_object, ["error"], getv(from_object, ["error"]))
303
+
304
+ if getv(from_object, ["response"]) is not None:
305
+ setv(
306
+ to_object,
307
+ ["response"],
308
+ BatchEvaluateRequestPreparer._EvaluationDataset_from_vertex(
309
+ getv(from_object, ["response"]), to_object
310
+ ),
311
+ )
312
+
313
+ return to_object
314
+
315
+ @staticmethod
316
+ def EvaluateDatasetRequestParameters_to_vertex(
317
+ from_object: Union[dict[str, Any], object],
318
+ parent_object: Optional[dict[str, Any]] = None,
319
+ ) -> dict[str, Any]:
320
+ to_object: dict[str, Any] = {}
321
+ if getv(from_object, ["dataset"]) is not None:
322
+ setv(
323
+ to_object,
324
+ ["dataset"],
325
+ BatchEvaluateRequestPreparer._EvaluationDataset_to_vertex(
326
+ getv(from_object, ["dataset"]), to_object
327
+ ),
328
+ )
329
+
330
+ if getv(from_object, ["metrics"]) is not None:
331
+ setv(
332
+ to_object,
333
+ ["metrics"],
334
+ [
335
+ BatchEvaluateRequestPreparer._Metric_to_vertex(item, to_object)
336
+ for item in getv(from_object, ["metrics"])
337
+ ],
338
+ )
339
+
340
+ if getv(from_object, ["output_config"]) is not None:
341
+ setv(
342
+ to_object,
343
+ ["outputConfig"],
344
+ BatchEvaluateRequestPreparer._OutputConfig_to_vertex(
345
+ getv(from_object, ["output_config"]), to_object
346
+ ),
347
+ )
348
+
349
+ if getv(from_object, ["autorater_config"]) is not None:
350
+ setv(
351
+ to_object,
352
+ ["autoraterConfig"],
353
+ BatchEvaluateRequestPreparer._AutoraterConfig_to_vertex(
354
+ getv(from_object, ["autorater_config"]), to_object
355
+ ),
356
+ )
357
+
358
+ if getv(from_object, ["config"]) is not None:
359
+ setv(to_object, ["config"], getv(from_object, ["config"]))
360
+
361
+ return to_object
362
+
363
+ @staticmethod
364
+ def prepare_metric_payload(
365
+ request_dict: dict[str, Any], resolved_metrics: list["types.MetricSubclass"]
366
+ ) -> dict[str, Any]:
367
+ """Prepares the metric payload for the evaluation request.
368
+
369
+ Args:
370
+ request_dict: The dictionary containing the request details.
371
+ resolved_metrics: A list of resolved metric objects.
372
+
373
+ Returns:
374
+ The updated request dictionary with the prepared metric payload.
375
+ """
376
+ request_dict["metrics"] = _transformers.t_metrics(
377
+ resolved_metrics, set_default_aggregation_metrics=True
378
+ )
379
+ return request_dict
380
+
381
+
382
+ class EvalDataConverter(abc.ABC):
383
+ """Abstract base class for dataset converters."""
384
+
385
+ @abc.abstractmethod
386
+ def convert(self, raw_data: Any) -> "types.EvaluationDataset":
387
+ """Converts a loaded raw dataset into an EvaluationDataset."""
388
+ raise NotImplementedError()
389
+
390
+
391
+ def _postprocess_user_scenarios_response(
392
+ response: types.GenerateUserScenariosResponse,
393
+ ) -> types.EvaluationDataset:
394
+ """Postprocesses the response from generating user scenarios."""
395
+ eval_cases = []
396
+ data_for_df = []
397
+ if hasattr(response, "user_scenarios") and response.user_scenarios:
398
+ for scenario in response.user_scenarios:
399
+ eval_case = types.EvalCase(
400
+ user_scenario=scenario,
401
+ )
402
+ eval_cases.append(eval_case)
403
+ data_for_df.append(
404
+ {
405
+ "starting_prompt": scenario.starting_prompt,
406
+ "conversation_plan": scenario.conversation_plan,
407
+ }
408
+ )
409
+ eval_dataset_df = None
410
+ if pd is not None:
411
+ eval_dataset_df = pd.DataFrame(data_for_df)
412
+ else:
413
+ logger.warning("Pandas is not installed. eval_dataset_df will be None.")
414
+ return types.EvaluationDataset(
415
+ eval_cases=eval_cases, eval_dataset_df=eval_dataset_df
416
+ )
417
+
418
+
419
+ def _display_loss_analysis_result(
420
+ result: types.LossAnalysisResult,
421
+ ) -> None:
422
+ """Displays a LossAnalysisResult as a formatted pandas DataFrame."""
423
+ metric = result.config.metric if result.config else None
424
+ candidate = result.config.candidate if result.config else None
425
+ rows: list[dict[str, Any]] = []
426
+ for cluster in result.clusters or []:
427
+ entry = cluster.taxonomy_entry
428
+ row = {
429
+ "metric": metric,
430
+ "candidate": candidate,
431
+ "cluster_id": cluster.cluster_id,
432
+ "l1_category": entry.l1_category if entry else None,
433
+ "l2_category": entry.l2_category if entry else None,
434
+ "description": entry.description if entry else None,
435
+ "item_count": cluster.item_count,
436
+ }
437
+ rows.append(row)
438
+
439
+ if not rows:
440
+ logger.info("No loss clusters found.")
441
+ return
442
+
443
+ df = pd.DataFrame(rows)
444
+ try:
445
+ from IPython.display import display # pylint: disable=g-import-not-at-top
446
+
447
+ display(df)
448
+ except ImportError:
449
+ print(df.to_string()) # pylint: disable=print-function
450
+
451
+
452
+ def _resolve_metric_name(
453
+ metric: Optional[Any],
454
+ ) -> Optional[str]:
455
+ """Extracts a metric name string from a metric argument.
456
+
457
+ Accepts a string, a Metric object, or a LazyLoadedPrebuiltMetric
458
+ (RubricMetric) and returns the metric name as a string.
459
+
460
+ For LazyLoadedPrebuiltMetric (e.g., RubricMetric.MULTI_TURN_TASK_SUCCESS),
461
+ this resolves to the API metric spec name (e.g.,
462
+ "multi_turn_task_success_v1") so it matches the keys in eval results.
463
+
464
+ Args:
465
+ metric: A metric name string, Metric object, RubricMetric enum value, or
466
+ None.
467
+
468
+ Returns:
469
+ The metric name as a string, or None if metric is None.
470
+ """
471
+ if metric is None:
472
+ return None
473
+ if isinstance(metric, str):
474
+ return metric
475
+ # LazyLoadedPrebuiltMetric: resolve to versioned API spec name.
476
+ if hasattr(metric, "_get_api_metric_spec_name"):
477
+ spec_name: Optional[str] = metric._get_api_metric_spec_name()
478
+ if spec_name:
479
+ return spec_name
480
+ # Metric objects and other types with a .name attribute.
481
+ if hasattr(metric, "name"):
482
+ return str(metric.name)
483
+ return str(metric)
484
+
485
+
486
+ def _resolve_eval_run_loss_configs(
487
+ loss_analysis_metrics: Optional[list[Any]] = None,
488
+ loss_analysis_configs: Optional[list[Any]] = None,
489
+ inference_configs: Optional[dict[str, Any]] = None,
490
+ ) -> Optional[list[types.LossAnalysisConfig]]:
491
+ """Resolves loss analysis configs for create_evaluation_run.
492
+
493
+ Supports two modes:
494
+ 1. ``loss_analysis_metrics``: A simplified list of metrics. The candidate
495
+ is auto-inferred from ``inference_configs`` when there is exactly one
496
+ candidate. Each metric is resolved via ``_resolve_metric_name()``.
497
+ 2. ``loss_analysis_configs``: Explicit ``LossAnalysisConfig`` objects or
498
+ dicts for full control.
499
+
500
+ Args:
501
+ loss_analysis_metrics: Optional list of metric references (strings,
502
+ Metric objects, or RubricMetric enums).
503
+ loss_analysis_configs: Optional list of LossAnalysisConfig or dicts.
504
+ inference_configs: The resolved inference_configs dict (candidate name
505
+ -> config). Used to auto-infer candidate for the metrics path.
506
+
507
+ Returns:
508
+ A list of resolved LossAnalysisConfig objects, or None if neither
509
+ loss_analysis_metrics nor loss_analysis_configs is provided.
510
+
511
+ Raises:
512
+ ValueError: If candidate cannot be inferred for loss_analysis_metrics.
513
+ """
514
+ if not loss_analysis_metrics and not loss_analysis_configs:
515
+ return None
516
+
517
+ if loss_analysis_configs:
518
+ return [
519
+ types.LossAnalysisConfig.model_validate(c) if isinstance(c, dict) else c
520
+ for c in loss_analysis_configs
521
+ ]
522
+
523
+ # loss_analysis_metrics path: auto-infer candidate from inference_configs
524
+ candidate = None
525
+ if inference_configs and len(inference_configs) == 1:
526
+ candidate = next(iter(inference_configs))
527
+ elif inference_configs and len(inference_configs) > 1:
528
+ raise ValueError(
529
+ "Cannot infer candidate for loss analysis: multiple candidates"
530
+ f" found in inference_configs: {list(inference_configs.keys())}."
531
+ " Please use loss_analysis_configs with explicit candidate values"
532
+ " instead."
533
+ )
534
+
535
+ configs = []
536
+ for m in loss_analysis_metrics or []:
537
+ metric_name = _resolve_metric_name(m)
538
+ configs.append(
539
+ types.LossAnalysisConfig(metric=metric_name, candidate=candidate)
540
+ )
541
+ return configs
542
+
543
+
544
+ def _resolve_red_teaming_config(
545
+ red_teaming_config: Optional[types.RedTeamingAnalysisConfigOrDict] = None,
546
+ ) -> Optional[list[types.AnalysisConfig]]:
547
+ """Wraps a RedTeamingAnalysisConfig into analysis_configs for the API."""
548
+ if not red_teaming_config:
549
+ return None
550
+ config = (
551
+ types.RedTeamingAnalysisConfig.model_validate(red_teaming_config)
552
+ if isinstance(red_teaming_config, dict)
553
+ else red_teaming_config
554
+ )
555
+ return [types.AnalysisConfig(red_teaming_analysis_config=config)]
556
+
557
+
558
+ def _resolve_loss_analysis_config(
559
+ eval_result: types.EvaluationResult,
560
+ config: Optional[types.LossAnalysisConfig] = None,
561
+ metric: Optional[str] = None,
562
+ candidate: Optional[str] = None,
563
+ ) -> types.LossAnalysisConfig:
564
+ """Resolves and validates the LossAnalysisConfig for generate_loss_clusters.
565
+
566
+ Auto-infers `metric` and `candidate` from the EvaluationResult when not
567
+ explicitly provided. Validates that provided values exist in the eval result.
568
+
569
+ Args:
570
+ eval_result: The EvaluationResult from client.evals.evaluate().
571
+ config: Optional explicit LossAnalysisConfig. If provided, metric and
572
+ candidate from config take precedence over the separate arguments.
573
+ metric: Optional metric name override.
574
+ candidate: Optional candidate name override.
575
+
576
+ Returns:
577
+ A resolved LossAnalysisConfig with metric and candidate populated.
578
+
579
+ Raises:
580
+ ValueError: If metric/candidate cannot be inferred or are invalid.
581
+ """
582
+ # Start from config if provided, otherwise create a new one.
583
+ if config is not None:
584
+ resolved_metric = metric or config.metric
585
+ resolved_candidate = candidate or config.candidate
586
+ resolved_config = config.model_copy(
587
+ update={"metric": resolved_metric, "candidate": resolved_candidate}
588
+ )
589
+ else:
590
+ resolved_config = types.LossAnalysisConfig(metric=metric, candidate=candidate)
591
+
592
+ # Collect available metric names from the eval result.
593
+ available_metrics: set[str] = set()
594
+ if eval_result.eval_case_results:
595
+ for case_result in eval_result.eval_case_results:
596
+ for resp_cand in case_result.response_candidate_results or []:
597
+ for m_name in (resp_cand.metric_results or {}).keys():
598
+ available_metrics.add(m_name)
599
+
600
+ # Collect available candidate names from metadata.
601
+ available_candidates: list[str] = []
602
+ if eval_result.metadata and eval_result.metadata.candidate_names:
603
+ available_candidates = list(eval_result.metadata.candidate_names)
604
+
605
+ # Auto-infer metric if not provided.
606
+ if not resolved_config.metric:
607
+ if len(available_metrics) == 1:
608
+ resolved_config = resolved_config.model_copy(
609
+ update={"metric": next(iter(available_metrics))}
610
+ )
611
+ elif len(available_metrics) == 0:
612
+ raise ValueError(
613
+ "Cannot infer metric: no metric results found in eval_result."
614
+ " Please provide metric explicitly via"
615
+ " config=types.LossAnalysisConfig(metric='...')."
616
+ )
617
+ else:
618
+ raise ValueError(
619
+ "Cannot infer metric: multiple metrics found in eval_result:"
620
+ f" {sorted(available_metrics)}. Please provide metric"
621
+ " explicitly via config=types.LossAnalysisConfig(metric='...')."
622
+ )
623
+
624
+ # Validate metric if provided explicitly.
625
+ if available_metrics and resolved_config.metric not in available_metrics:
626
+ raise ValueError(
627
+ f"Metric '{resolved_config.metric}' not found in eval_result."
628
+ f" Available metrics: {sorted(available_metrics)}."
629
+ )
630
+
631
+ # Auto-infer candidate if not provided.
632
+ if not resolved_config.candidate:
633
+ if len(available_candidates) == 1:
634
+ resolved_config = resolved_config.model_copy(
635
+ update={"candidate": available_candidates[0]}
636
+ )
637
+ elif len(available_candidates) == 0:
638
+ # Fallback: use default candidate naming convention from SDK.
639
+ resolved_config = resolved_config.model_copy(
640
+ update={"candidate": "candidate_1"}
641
+ )
642
+ logger.warning(
643
+ "No candidate names found in eval_result.metadata."
644
+ " Defaulting to 'candidate_1'. If this is incorrect, provide"
645
+ " candidate explicitly via"
646
+ " config=types.LossAnalysisConfig(candidate='...')."
647
+ )
648
+ else:
649
+ raise ValueError(
650
+ "Cannot infer candidate: multiple candidates found in"
651
+ f" eval_result: {available_candidates}. Please provide"
652
+ " candidate explicitly via"
653
+ " config=types.LossAnalysisConfig(candidate='...')."
654
+ )
655
+
656
+ # Validate candidate if provided explicitly and candidates are known.
657
+ if available_candidates and resolved_config.candidate not in available_candidates:
658
+ raise ValueError(
659
+ f"Candidate '{resolved_config.candidate}' not found in"
660
+ f" eval_result. Available candidates: {available_candidates}."
661
+ )
662
+
663
+ return resolved_config
664
+
665
+
666
+ def _build_rubric_description_map(
667
+ eval_result: types.EvaluationResult,
668
+ ) -> dict[str, str]:
669
+ """Builds a rubric_id -> description map from the EvaluationResult."""
670
+ rubric_map: dict[str, str] = {}
671
+ for case_result in eval_result.eval_case_results or []:
672
+ for resp_cand in case_result.response_candidate_results or []:
673
+ for metric_res in (resp_cand.metric_results or {}).values():
674
+ for verdict in metric_res.rubric_verdicts or []:
675
+ rubric = verdict.evaluated_rubric
676
+ if rubric and rubric.rubric_id and rubric.content:
677
+ if (
678
+ rubric.content.property
679
+ and rubric.content.property.description
680
+ ):
681
+ rubric_map[rubric.rubric_id] = (
682
+ rubric.content.property.description
683
+ )
684
+ return rubric_map
685
+
686
+
687
+ def _extract_scenario_preview_from_dict(
688
+ eval_result_dict: dict[str, Any],
689
+ ) -> Optional[str]:
690
+ """Extracts the first user message from an evaluation_result dict.
691
+
692
+ Handles both snake_case (SDK-side) and camelCase (API echo-back) keys.
693
+ """
694
+ request = eval_result_dict.get("request")
695
+ if not request:
696
+ return None
697
+ prompt = request.get("prompt")
698
+ if not prompt:
699
+ return None
700
+ # Try agent_data (snake_case or camelCase)
701
+ agent_data = prompt.get("agent_data") or prompt.get("agentData")
702
+ if agent_data and isinstance(agent_data, dict):
703
+ turns = agent_data.get("turns", [])
704
+ for turn in turns:
705
+ events = turn.get("events", [])
706
+ for event in events:
707
+ author = event.get("author", "")
708
+ content = event.get("content")
709
+ if author.lower() == "user" and content and isinstance(content, dict):
710
+ parts = content.get("parts", [])
711
+ for part in parts:
712
+ text = str(part.get("text", "")).strip()
713
+ if text:
714
+ if len(text) > 150:
715
+ return text[:150] + "..."
716
+ return text
717
+ # Try simple prompt path
718
+ parts = prompt.get("parts", [])
719
+ for part in parts:
720
+ text = str(part.get("text", "")).strip()
721
+ if text:
722
+ if len(text) > 150:
723
+ return text[:150] + "..."
724
+ return text
725
+ return None
726
+
727
+
728
+ def _extract_scenario_from_agent_data(agent_data: Any) -> Optional[str]:
729
+ """Extracts the first user message from an AgentData object or dict."""
730
+ if agent_data is None:
731
+ return None
732
+ if hasattr(agent_data, "model_dump"):
733
+ agent_data = agent_data.model_dump()
734
+ if isinstance(agent_data, str):
735
+ try:
736
+ agent_data = json.loads(agent_data)
737
+ except (json.JSONDecodeError, ValueError):
738
+ return None
739
+ if not isinstance(agent_data, dict):
740
+ return None
741
+ turns = agent_data.get("turns", [])
742
+ if not isinstance(turns, list):
743
+ return None
744
+ for turn in turns:
745
+ if not isinstance(turn, dict):
746
+ continue
747
+ events = turn.get("events", [])
748
+ if not isinstance(events, list):
749
+ continue
750
+ for event in events:
751
+ if not isinstance(event, dict):
752
+ continue
753
+ author = event.get("author", "")
754
+ if not isinstance(author, str) or author.lower() != "user":
755
+ continue
756
+ content = event.get("content")
757
+ if not content or not isinstance(content, dict):
758
+ continue
759
+ parts = content.get("parts", [])
760
+ if not isinstance(parts, list):
761
+ continue
762
+ for part in parts:
763
+ if not isinstance(part, dict):
764
+ continue
765
+ text = str(part.get("text", "")).strip()
766
+ if text:
767
+ if len(text) > 150:
768
+ return text[:150] + "..."
769
+ return text
770
+ return None
771
+
772
+
773
+ def _truncate_scenario(text: str, max_len: int = 150) -> str:
774
+ """Truncates a scenario preview to max_len characters."""
775
+ text = text.strip()
776
+ if len(text) > max_len:
777
+ return text[:max_len] + "..."
778
+ return text
779
+
780
+
781
+ def _build_scenario_preview_list(
782
+ eval_result: types.EvaluationResult,
783
+ ) -> list[Optional[str]]:
784
+ """Builds an ordered list of scenario previews from the EvaluationResult.
785
+
786
+ Returns one scenario preview per eval_case_result, in the same order as
787
+ eval_case_results. This extracts the first user message from the original
788
+ SDK EvaluationResult (via eval_cases or DataFrame), rather than relying
789
+ on the API echo-back which may not preserve the request data.
790
+
791
+ Extraction priority per eval case:
792
+ 1. eval_case.agent_data → first user message in turns
793
+ 2. eval_case.user_scenario.starting_prompt
794
+ 3. eval_case.prompt → text content
795
+ 4. DataFrame agent_data column → first user message
796
+ 5. DataFrame starting_prompt column
797
+ """
798
+ eval_dataset = eval_result.evaluation_dataset
799
+ eval_cases: list[Any] = []
800
+ if isinstance(eval_dataset, list) and eval_dataset:
801
+ eval_cases = getv(eval_dataset[0], ["eval_cases"]) or []
802
+
803
+ eval_case_results = eval_result.eval_case_results or []
804
+ scenarios: list[Optional[str]] = []
805
+
806
+ for case_result in eval_case_results:
807
+ case_idx = case_result.eval_case_index or 0
808
+ scenario: Optional[str] = None
809
+
810
+ eval_case = None
811
+ if 0 <= case_idx < len(eval_cases):
812
+ eval_case = eval_cases[case_idx]
813
+
814
+ if eval_case:
815
+ # 1. Try agent_data (populated after run_inference)
816
+ agent_data = getv(eval_case, ["agent_data"])
817
+ if agent_data:
818
+ scenario = _extract_scenario_from_agent_data(agent_data)
819
+
820
+ # 2. Try user_scenario.starting_prompt (from
821
+ # generate_conversation_scenarios)
822
+ if scenario is None:
823
+ user_scenario = getv(eval_case, ["user_scenario"])
824
+ if user_scenario:
825
+ starting_prompt = getv(user_scenario, ["starting_prompt"])
826
+ if starting_prompt and isinstance(starting_prompt, str):
827
+ scenario = _truncate_scenario(starting_prompt)
828
+
829
+ # 3. Try prompt text
830
+ if scenario is None:
831
+ prompt = getv(eval_case, ["prompt"])
832
+ if prompt:
833
+ from . import _evals_data_converters
834
+
835
+ text = _evals_data_converters._get_content_text(prompt)
836
+ if text:
837
+ scenario = _truncate_scenario(str(text))
838
+
839
+ # 4. Fallback: extract agent_data from DataFrame
840
+ if scenario is None and eval_dataset:
841
+ df_agent_data = _transformers._extract_agent_data_from_df(
842
+ eval_dataset, case_idx
843
+ )
844
+ if df_agent_data is not None:
845
+ scenario = _extract_scenario_from_agent_data(df_agent_data)
846
+
847
+ # 5. Fallback: extract starting_prompt from DataFrame
848
+ if scenario is None and eval_dataset:
849
+ ds = eval_dataset[0] if isinstance(eval_dataset, list) else eval_dataset
850
+ df = getv(ds, ["eval_dataset_df"])
851
+ if df is not None and hasattr(df, "iloc"):
852
+ if 0 <= case_idx < len(df):
853
+ row = df.iloc[case_idx]
854
+ sp = row.get("starting_prompt")
855
+ if sp and isinstance(sp, str) and sp.strip():
856
+ scenario = _truncate_scenario(sp)
857
+
858
+ scenarios.append(scenario)
859
+
860
+ return scenarios
861
+
862
+
863
+ def _enrich_loss_response_with_rubric_descriptions(
864
+ response: types.GenerateLossClustersResponse,
865
+ eval_result: types.EvaluationResult,
866
+ ) -> None:
867
+ """Enriches loss response with rubric descriptions and scenario previews.
868
+
869
+ Rubric descriptions and scenario previews are extracted from the original
870
+ SDK EvaluationResult object, because the API echo-back in
871
+ LossExample.evaluation_result may not preserve all request data (e.g.,
872
+ agent_data turns with user messages).
873
+ """
874
+ rubric_map = _build_rubric_description_map(eval_result)
875
+ scenario_list = _build_scenario_preview_list(eval_result)
876
+ logger.debug(
877
+ "Enriching loss response: %d scenarios extracted, %d rubric" " descriptions",
878
+ sum(1 for s in scenario_list if s),
879
+ len(rubric_map),
880
+ )
881
+ for result in response.results or []:
882
+ for cluster in result.clusters or []:
883
+ for example in cluster.examples or []:
884
+ if example.evaluation_result is None:
885
+ example.evaluation_result = {}
886
+ if rubric_map:
887
+ example.evaluation_result["rubric_descriptions"] = rubric_map
888
+ # Try extracting scenario from the API echo-back first
889
+ if "scenario_preview" not in example.evaluation_result:
890
+ scenario = _extract_scenario_preview_from_dict(
891
+ example.evaluation_result
892
+ )
893
+ if scenario:
894
+ example.evaluation_result["scenario_preview"] = scenario
895
+ # Fallback: match against scenarios from original eval_result
896
+ if "scenario_preview" not in example.evaluation_result:
897
+ if scenario_list:
898
+ for s in scenario_list:
899
+ if s:
900
+ example.evaluation_result["scenario_preview"] = s
901
+ break
902
+
903
+
904
+ def _poll_operation(
905
+ api_client: BaseApiClient,
906
+ operation: types.GenerateLossClustersOperation,
907
+ poll_interval_seconds: float = 5.0,
908
+ ) -> types.GenerateLossClustersOperation:
909
+ """Polls a long-running operation until completion.
910
+
911
+ Args:
912
+ api_client: The API client to use for polling.
913
+ operation: The initial operation returned from the API call.
914
+ poll_interval_seconds: Time between polls.
915
+
916
+ Returns:
917
+ The completed operation.
918
+ """
919
+ if operation.done:
920
+ return operation
921
+ start_time = time.time()
922
+ while True:
923
+ response = api_client.request("get", operation.name, {}, None)
924
+ response_dict = {} if not response.body else json.loads(response.body)
925
+ polled = types.GenerateLossClustersOperation._from_response(
926
+ response=response_dict, kwargs={}
927
+ )
928
+ if polled.done:
929
+ return polled
930
+ elapsed = int(time.time() - start_time)
931
+ logger.info(
932
+ "Loss analysis operation still running... Elapsed time: %d seconds",
933
+ elapsed,
934
+ )
935
+ time.sleep(poll_interval_seconds)
936
+
937
+
938
+ async def _poll_operation_async(
939
+ api_client: BaseApiClient,
940
+ operation: types.GenerateLossClustersOperation,
941
+ poll_interval_seconds: float = 5.0,
942
+ ) -> types.GenerateLossClustersOperation:
943
+ """Polls a long-running operation until completion (async).
944
+
945
+ Args:
946
+ api_client: The API client to use for polling.
947
+ operation: The initial operation returned from the API call.
948
+ poll_interval_seconds: Time between polls.
949
+
950
+ Returns:
951
+ The completed operation.
952
+ """
953
+ if operation.done:
954
+ return operation
955
+ start_time = time.time()
956
+ while True:
957
+ response = await api_client.async_request("get", operation.name, {}, None)
958
+ response_dict = {} if not response.body else json.loads(response.body)
959
+ polled = types.GenerateLossClustersOperation._from_response(
960
+ response=response_dict, kwargs={}
961
+ )
962
+ if polled.done:
963
+ return polled
964
+ elapsed = int(time.time() - start_time)
965
+ logger.info(
966
+ "Loss analysis operation still running... Elapsed time: %d seconds",
967
+ elapsed,
968
+ )
969
+ await asyncio.sleep(poll_interval_seconds)
970
+
971
+
972
+ def _validate_dataset_agent_data(
973
+ dataset: types.EvaluationDataset,
974
+ inference_configs: Optional[dict[str, Any]] = None,
975
+ ) -> None:
976
+ """Validates agent_data in the EvaluationDataset.
977
+
978
+ Checks that agent_data matches the expected AgentData type and that
979
+ 'agents' are not defined in both the dataset's agent_data and inference_configs.
980
+ """
981
+ has_inference_agent_configs = False
982
+ if inference_configs:
983
+ for cand_config in inference_configs.values():
984
+ if isinstance(cand_config, dict) and cand_config.get("agent_configs"):
985
+ has_inference_agent_configs = True
986
+ elif hasattr(cand_config, "agent_configs") and cand_config.agent_configs:
987
+ has_inference_agent_configs = True
988
+
989
+ def _validate_single_agent_data(agent_data_val: Any, identifier: str) -> None:
990
+
991
+ if not agent_data_val:
992
+ return
993
+
994
+ agent_data_obj = None
995
+ if isinstance(agent_data_val, str):
996
+ try:
997
+ agent_data_val = json.loads(agent_data_val)
998
+ if "error" in agent_data_val:
999
+ return
1000
+ agent_data_obj = types.evals.AgentData.model_validate(agent_data_val)
1001
+ except json.JSONDecodeError as e:
1002
+ raise ValueError(
1003
+ f"{identifier}: 'agent_data' is not valid JSON: {e}"
1004
+ ) from e
1005
+ elif isinstance(agent_data_val, dict) and "error" in agent_data_val:
1006
+ return
1007
+ elif isinstance(agent_data_val, dict):
1008
+ try:
1009
+ agent_data_obj = types.evals.AgentData.model_validate(agent_data_val)
1010
+ except Exception as e:
1011
+ raise ValueError(
1012
+ f"{identifier}: 'agent_data' "
1013
+ f"is inconsistent with AgentData type: {e}"
1014
+ ) from e
1015
+ elif isinstance(agent_data_val, types.evals.AgentData):
1016
+ agent_data_obj = agent_data_val
1017
+ else:
1018
+ raise ValueError(
1019
+ f"{identifier}: 'agent_data' is inconsistent with AgentData type. "
1020
+ f"Got {type(agent_data_val)}"
1021
+ )
1022
+
1023
+ if agent_data_obj and agent_data_obj.agents and has_inference_agent_configs:
1024
+ raise ValueError(
1025
+ f"{identifier}: Cannot provide 'agents' in the dataset's 'agent_data' "
1026
+ "and 'agent_configs' in inference_configs at the same time."
1027
+ )
1028
+
1029
+ if (
1030
+ dataset.eval_dataset_df is not None
1031
+ and "agent_data" in dataset.eval_dataset_df.columns
1032
+ ):
1033
+ for idx, row in dataset.eval_dataset_df.iterrows():
1034
+ _validate_single_agent_data(row.get("agent_data"), f"Row {idx}")
1035
+
1036
+ if dataset.eval_cases:
1037
+ for idx, eval_case in enumerate(dataset.eval_cases):
1038
+ agent_data = None
1039
+ if isinstance(eval_case, dict):
1040
+ agent_data = eval_case.get("agent_data", None)
1041
+ elif hasattr(eval_case, "agent_data"):
1042
+ agent_data = eval_case.agent_data
1043
+ _validate_single_agent_data(agent_data, f"EvalCase {idx}")
data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/_evals_visualization.py ADDED
The diff for this file is too large to render. See raw diff
 
data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/_gcs_utils.py ADDED
@@ -0,0 +1,192 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2025 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
+
16
+ import io
17
+ import json
18
+ import logging
19
+ from typing import Any, Union
20
+
21
+ from google.cloud import storage # type: ignore[attr-defined]
22
+ from google.cloud.aiplatform.utils.gcs_utils import blob_from_uri
23
+ from google.genai._api_client import BaseApiClient
24
+ import pandas as pd
25
+ import uuid
26
+
27
+
28
+ logger = logging.getLogger(__name__)
29
+
30
+
31
+ GCS_PREFIX = "gs://"
32
+
33
+
34
+ class GcsUtils:
35
+ """Handles File I/O operations with Google Cloud Storage (GCS)"""
36
+
37
+ def __init__(self, api_client: BaseApiClient):
38
+ self.api_client = api_client
39
+ self.storage_client = storage.Client(
40
+ project=self.api_client.project,
41
+ credentials=self.api_client._credentials,
42
+ )
43
+
44
+ def parse_gcs_path(self, gcs_path: str) -> tuple[str, str]:
45
+ """Helper to parse gs://bucket/path into (bucket_name, blob_path)."""
46
+ if not gcs_path.startswith(GCS_PREFIX):
47
+ raise ValueError(
48
+ f"Invalid GCS path: '{gcs_path}'. It must start with '{GCS_PREFIX}'."
49
+ )
50
+ path_without_prefix = gcs_path[len(GCS_PREFIX) :]
51
+ if "/" not in path_without_prefix:
52
+ return path_without_prefix, ""
53
+ bucket_name, blob_path = path_without_prefix.split("/", 1)
54
+ return bucket_name, blob_path
55
+
56
+ def upload_file_to_gcs(self, upload_gcs_path: str, filename: str) -> None:
57
+ """Uploads the provided file to a Google Cloud Storage location."""
58
+
59
+ blob_from_uri(
60
+ uri=upload_gcs_path, client=self.storage_client
61
+ ).upload_from_filename(filename)
62
+
63
+ def upload_dataframe(
64
+ self,
65
+ df: "pd.DataFrame",
66
+ gcs_destination_blob_path: str,
67
+ file_type: str = "jsonl",
68
+ ) -> None:
69
+ """Uploads a Pandas DataFrame to a Google Cloud Storage location.
70
+
71
+ Args:
72
+ df: The Pandas DataFrame to upload.
73
+ gcs_destination_blob_path: The full GCS path for the destination blob
74
+ (e.g., 'gs://bucket/data/my_dataframe.jsonl').
75
+ file_type: The format to save the DataFrame ('jsonl' or 'csv'). Defaults
76
+ to 'jsonl'.
77
+ """
78
+ bucket_name, blob_name = self.parse_gcs_path(gcs_destination_blob_path)
79
+ if not blob_name:
80
+ raise ValueError(
81
+ f"Invalid GCS path for blob: '{gcs_destination_blob_path}'. "
82
+ "It must include the object name (e.g., gs://bucket/file.csv)."
83
+ )
84
+ bucket = self.storage_client.bucket(bucket_name)
85
+ blob = bucket.blob(blob_name)
86
+
87
+ buffer = io.StringIO()
88
+ if file_type == "csv":
89
+ df.to_csv(buffer, index=False)
90
+ content_type = "text/csv"
91
+ elif file_type == "jsonl":
92
+ df.to_json(buffer, orient="records", lines=True)
93
+ content_type = "application/jsonl"
94
+ else:
95
+ raise ValueError(
96
+ f"Unsupported file type: '{file_type}'. "
97
+ "Please provide 'jsonl' or 'csv'."
98
+ )
99
+ blob.upload_from_string(buffer.getvalue(), content_type=content_type)
100
+
101
+ logger.info(
102
+ f"DataFrame successfully uploaded to: gs://{bucket.name}/{blob.name}"
103
+ )
104
+
105
+ def upload_json(self, data: dict[str, Any], gcs_destination_blob_path: str) -> None:
106
+ """Uploads a dictionary as a JSON file to Google Cloud Storage."""
107
+ bucket_name, blob_name = self.parse_gcs_path(gcs_destination_blob_path)
108
+ if not blob_name:
109
+ raise ValueError(
110
+ f"Invalid GCS path for blob: '{gcs_destination_blob_path}'. "
111
+ "It must include the object name (e.g., gs://bucket/file.json)."
112
+ )
113
+ bucket = self.storage_client.bucket(bucket_name)
114
+ blob = bucket.blob(blob_name)
115
+
116
+ json_data = json.dumps(data, indent=2)
117
+ blob.upload_from_string(json_data, content_type="application/json")
118
+
119
+ logger.info(
120
+ f"JSON data successfully uploaded to: gs://{bucket_name}/{blob_name}"
121
+ )
122
+
123
+ def upload_json_to_prefix(
124
+ self,
125
+ data: dict[str, Any],
126
+ gcs_dest_prefix: str,
127
+ filename_prefix: str = "data",
128
+ ) -> str:
129
+ """Uploads a dictionary to a GCS prefix with a UUID JSON filename.
130
+
131
+ Args:
132
+ data: The dictionary to upload.
133
+ gcs_dest_prefix: The GCS prefix (e.g., 'gs://bucket/path/prefix/').
134
+ filename_prefix: Prefix for the generated filename. Defaults to 'data'.
135
+
136
+ Returns:
137
+ The full GCS path where the file was uploaded.
138
+
139
+ Raises:
140
+ ValueError: If the gcs_dest_prefix is not a valid GCS path.
141
+ """
142
+ if not gcs_dest_prefix.startswith(GCS_PREFIX):
143
+ raise ValueError(
144
+ f"Invalid GCS destination prefix: '{gcs_dest_prefix}'. Must start"
145
+ f" with '{GCS_PREFIX}'."
146
+ )
147
+
148
+ gcs_path_without_scheme = gcs_dest_prefix[len(GCS_PREFIX) :]
149
+ bucket_name, *path_parts = gcs_path_without_scheme.split("/")
150
+
151
+ user_prefix_path = "/".join(path_parts)
152
+ if user_prefix_path and not user_prefix_path.endswith("/"):
153
+ user_prefix_path += "/"
154
+
155
+ filename = f"{filename_prefix}_{uuid.uuid4()}.json"
156
+
157
+ blob_name = f"{user_prefix_path}{filename}"
158
+
159
+ full_gcs_path = f"{GCS_PREFIX}{bucket_name}/{blob_name}"
160
+
161
+ self.upload_json(data, full_gcs_path)
162
+ return full_gcs_path
163
+
164
+ def read_file_contents(self, gcs_filepath: str) -> Union[str, Any]:
165
+ """Reads the contents of a file from Google Cloud Storage."""
166
+
167
+ bucket_name, blob_path = self.parse_gcs_path(gcs_filepath)
168
+ if not blob_path:
169
+ raise ValueError(
170
+ f"Invalid GCS file path: '{gcs_filepath}'. Path must point to a file,"
171
+ " not just a bucket."
172
+ )
173
+ bucket = self.storage_client.bucket(bucket_name)
174
+ blob = bucket.blob(blob_path)
175
+ content = blob.download_as_bytes().decode("utf-8")
176
+ logger.info(f"Successfully read content from '{gcs_filepath}'")
177
+ return content
178
+
179
+ def read_gcs_file_to_dataframe(
180
+ self, gcs_filepath: str, file_type: str
181
+ ) -> "pd.DataFrame":
182
+ """Reads a file from Google Cloud Storage into a Pandas DataFrame."""
183
+ file_contents = self.read_file_contents(gcs_filepath)
184
+ if file_type == "csv":
185
+ return pd.read_csv(io.StringIO(file_contents), encoding="utf-8")
186
+ elif file_type == "jsonl":
187
+ return pd.read_json(io.StringIO(file_contents), lines=True)
188
+ else:
189
+ raise ValueError(
190
+ f"Unsupported file type: '{file_type}'. Please provide 'jsonl' or"
191
+ " 'csv'."
192
+ )
data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/_logging_utils.py ADDED
@@ -0,0 +1,47 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2025 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
+
16
+ import functools
17
+ from typing import Any, Callable
18
+ from google.genai import _common
19
+ import warnings
20
+
21
+
22
+ def show_deprecation_warning_once(
23
+ message: str,
24
+ ) -> Callable[[Callable[..., Any]], Callable[..., Any]]:
25
+ """Decorator to show a deprecation warning once for a function."""
26
+
27
+ def decorator(func: Any) -> Any:
28
+ warning_done = False
29
+
30
+ @functools.wraps(func)
31
+ def wrapper(*args: Any, **kwargs: Any) -> Any:
32
+ nonlocal warning_done
33
+ if not warning_done:
34
+ warning_done = True
35
+ warnings.warn(message, DeprecationWarning, stacklevel=2)
36
+
37
+ # Suppress ExperimentalWarning while executing the deprecated wrapper
38
+ with warnings.catch_warnings():
39
+ # We ignore ExperimentalWarning because the user will see it
40
+ # when they migrate to the new prompts module
41
+ warnings.simplefilter("ignore", category=_common.ExperimentalWarning)
42
+ return func(*args, **kwargs)
43
+ return func(*args, **kwargs)
44
+
45
+ return wrapper
46
+
47
+ return decorator
data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/_observability_data_converter.py ADDED
@@ -0,0 +1,186 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2025 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
+ """Dataset converter for Google Observability GenAI data."""
16
+
17
+ import json
18
+ import logging
19
+ from typing import Any, Optional
20
+
21
+ from google.genai import types as genai_types
22
+ from typing_extensions import override
23
+
24
+ from . import _evals_utils
25
+ from . import types
26
+
27
+
28
+ logger = logging.getLogger("agentplatform_genai._observability_data_converters")
29
+
30
+
31
+ def _load_jsonl(data: Any, case_id: str) -> list[dict[Any, Any]]:
32
+ """Parses the raw JSONL data into a list of dict possible."""
33
+ if isinstance(data, str):
34
+ json_list = []
35
+ for line in data.splitlines():
36
+ loaded_json = json.loads(line)
37
+ if not isinstance(loaded_json, dict):
38
+ raise TypeError(
39
+ f"Decoded JSON payload is not a dict for case "
40
+ f"{case_id}. Type found: {type(loaded_json).__name__}"
41
+ )
42
+ json_list.append(loaded_json)
43
+ return json_list
44
+ else:
45
+ raise TypeError(
46
+ f"Payload is not a JSONL string for case {case_id}. Type "
47
+ f"found: {type(data).__name__}"
48
+ )
49
+
50
+
51
+ class ObservabilityDataConverter(_evals_utils.EvalDataConverter):
52
+ """Converter for dataset in GCP Observability GenAI format."""
53
+
54
+ def _message_to_content(self, message: dict[str, Any]) -> genai_types.Content:
55
+ """Converts Observability GenAI Message format to Content."""
56
+ parts = []
57
+ message_parts = message.get("parts", [])
58
+ if isinstance(message_parts, list):
59
+ for message_part in message_parts:
60
+ part = None
61
+ part_type = message_part.get("type", "")
62
+ if part_type == "text":
63
+ part = genai_types.Part(text=message_part.get("content", ""))
64
+ elif part_type == "blob":
65
+ part = genai_types.Part(
66
+ inline_data=genai_types.Blob(
67
+ data=message_part.get("data", ""),
68
+ mime_type=message_part.get("mime_type", ""),
69
+ )
70
+ )
71
+ elif part_type == "file_data":
72
+ part = genai_types.Part(
73
+ file_data=genai_types.FileData(
74
+ file_uri=message_part.get("file_uri", ""),
75
+ mime_type=message_part.get("mime_type", ""),
76
+ )
77
+ )
78
+ elif part_type == "tool_call":
79
+ # O11y format requires use of id in place of name
80
+ part = genai_types.Part(
81
+ function_call=genai_types.FunctionCall(
82
+ id=message_part.get("id", ""),
83
+ name=message_part.get("id", ""),
84
+ args=message_part.get("arguments", {}),
85
+ )
86
+ )
87
+ elif part_type == "tool_call_response":
88
+ # O11y format requires use of id in place of name
89
+ part = genai_types.Part(
90
+ function_response=genai_types.FunctionResponse(
91
+ id=message_part.get("id", ""),
92
+ name=message_part.get("id", ""),
93
+ response=message_part.get("result", {}),
94
+ )
95
+ )
96
+ else:
97
+ logger.warning(
98
+ "Skipping message part due to unrecognized message "
99
+ "part type of '%s'",
100
+ part_type,
101
+ )
102
+
103
+ if part is not None:
104
+ parts.append(part)
105
+
106
+ return genai_types.Content(parts=parts, role=message.get("role", ""))
107
+
108
+ def _parse_messages(
109
+ self,
110
+ eval_case_id: str,
111
+ request_msgs: list[Any],
112
+ response_msgs: list[Any],
113
+ system_instruction_msg: Optional[dict[str, Any]] = None,
114
+ ) -> types.EvalCase:
115
+ """Parses a set of Observability messages into an EvalCase."""
116
+ # System instruction message
117
+ system_instruction = None
118
+ if system_instruction_msg is not None:
119
+ system_instruction = self._message_to_content(system_instruction_msg)
120
+
121
+ # Request messages
122
+ prompt = None
123
+ conversation_history = []
124
+ if request_msgs:
125
+ # Extract latest message as prompt
126
+ prompt = self._message_to_content(request_msgs[-1])
127
+
128
+ # All previous messages are conversation history
129
+ if len(request_msgs) > 1:
130
+ for i, msg in enumerate(request_msgs[:-1]):
131
+ conversation_history.append(
132
+ types.evals.Message(
133
+ turn_id=str(i),
134
+ content=self._message_to_content(msg),
135
+ author=msg.get("role", ""),
136
+ )
137
+ )
138
+
139
+ # Output messages
140
+ responses = []
141
+ for msg in response_msgs:
142
+ response = types.ResponseCandidate(response=self._message_to_content(msg))
143
+ responses.append(response)
144
+
145
+ return types.EvalCase(
146
+ eval_case_id=eval_case_id,
147
+ prompt=prompt,
148
+ responses=responses,
149
+ system_instruction=system_instruction,
150
+ conversation_history=conversation_history,
151
+ reference=None,
152
+ )
153
+
154
+ @override
155
+ def convert(self, raw_data: list[dict[str, Any]]) -> types.EvaluationDataset:
156
+ """Converts a list of GCP Observability GenAI cases into an EvaluationDataset."""
157
+ eval_cases = []
158
+
159
+ for i, case in enumerate(raw_data):
160
+ eval_case_id = f"observability_eval_case_{i}"
161
+
162
+ if "request" not in case or "response" not in case:
163
+ logger.warning(
164
+ "Skipping case %s due to missing 'request' or 'response' key.",
165
+ eval_case_id,
166
+ )
167
+ continue
168
+
169
+ request_data = case.get("request", [])
170
+ request_list = _load_jsonl(request_data, eval_case_id)
171
+
172
+ response_data = case.get("response", [])
173
+ response_list = _load_jsonl(response_data, eval_case_id)
174
+
175
+ system_dict = None
176
+ if "system_instruction" in case:
177
+ system_data = case.get("system_instruction", {})
178
+ system_list = _load_jsonl(system_data, eval_case_id)
179
+ system_dict = system_list[0] if system_list else {}
180
+
181
+ eval_case = self._parse_messages(
182
+ eval_case_id, request_list, response_list, system_dict
183
+ )
184
+ eval_cases.append(eval_case)
185
+
186
+ return types.EvaluationDataset(eval_cases=eval_cases)
data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/_prompt_management_utils.py ADDED
@@ -0,0 +1,147 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2025 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
+ """Utility functions for prompt management."""
16
+
17
+ from typing import Optional
18
+
19
+ from google.genai import types as genai_types
20
+
21
+ from . import types
22
+
23
+
24
+ DEFAULT_API_SCHEMA_VERSION = "1.0.0"
25
+ PROMPT_SCHEMA_URI = (
26
+ "gs://google-cloud-aiplatform/schema/dataset/metadata/text_prompt_1.0.0.yaml"
27
+ )
28
+ PROMPT_TYPE = "multimodal_freeform"
29
+
30
+
31
+ def _create_dataset_metadata_from_prompt(
32
+ prompt: types.Prompt,
33
+ variables: Optional[list[dict[str, genai_types.Part]]] = None,
34
+ ) -> types.SchemaTextPromptDatasetMetadata:
35
+ """Convert a types.Prompt into types.SchemaTextPromptDatasetMetadata."""
36
+
37
+ prompt_metadata = types.SchemaTextPromptDatasetMetadata()
38
+
39
+ prompt_api_schema = types.SchemaPromptApiSchema()
40
+ prompt_api_schema.multimodal_prompt = types.SchemaPromptSpecMultimodalPrompt(
41
+ prompt_message=prompt.prompt_data
42
+ )
43
+
44
+ prompt_api_schema.api_schema_version = DEFAULT_API_SCHEMA_VERSION
45
+
46
+ prompt_metadata.has_prompt_variable = bool(variables)
47
+
48
+ if variables:
49
+ prompt_execution_list = []
50
+ for prompt_var in variables:
51
+ prompt_instance_execution = types.SchemaPromptInstancePromptExecution()
52
+ prompt_instance_execution.arguments = {}
53
+ for key, val in prompt_var.items():
54
+ prompt_instance_execution.arguments[key] = (
55
+ types.SchemaPromptInstanceVariableValue(
56
+ part_list=types.SchemaPromptSpecPartList(parts=[val])
57
+ )
58
+ )
59
+ prompt_execution_list.append(prompt_instance_execution)
60
+ prompt_api_schema.executions = prompt_execution_list
61
+
62
+ # Need to exclude variables from the prompt message as it is a client side
63
+ # only field
64
+ if prompt_api_schema.multimodal_prompt.prompt_message:
65
+ prompt_message_dict = (
66
+ prompt_api_schema.multimodal_prompt.prompt_message.model_dump(
67
+ exclude=["variables"], exclude_none=True
68
+ )
69
+ )
70
+ prompt_api_schema.multimodal_prompt.prompt_message = (
71
+ types.SchemaPromptSpecPromptMessage(**prompt_message_dict)
72
+ )
73
+ prompt_metadata.prompt_api_schema = prompt_api_schema
74
+
75
+ prompt_metadata.prompt_type = PROMPT_TYPE
76
+
77
+ return prompt_metadata
78
+
79
+
80
+ def _create_prompt_from_dataset_metadata(
81
+ dataset: types.Dataset,
82
+ ) -> types.Prompt:
83
+ """Constructs a types.Prompt from a types.Dataset resource returned from the API.
84
+
85
+ Args:
86
+ dataset: The types.Dataset object containing the prompt metadata.
87
+
88
+ Returns:
89
+ A types.Prompt object reconstructed from the dataset metadata.
90
+ """
91
+ if (
92
+ not hasattr(dataset, "metadata")
93
+ or dataset.metadata is None
94
+ or not isinstance(dataset.metadata, types.SchemaTextPromptDatasetMetadata)
95
+ ):
96
+ raise ValueError(
97
+ "Error retrieving prompt: prompt dataset resource is missing 'metadata'."
98
+ )
99
+ api_schema = dataset.metadata.prompt_api_schema
100
+ prompt = types.Prompt()
101
+
102
+ if api_schema is None:
103
+ return prompt
104
+
105
+ if api_schema.multimodal_prompt:
106
+
107
+ prompt_message = api_schema.multimodal_prompt.prompt_message
108
+ prompt.prompt_data = prompt_message
109
+
110
+ if api_schema.executions:
111
+ executions = api_schema.executions
112
+ if executions and prompt.prompt_data is not None:
113
+ prompt.prompt_data.variables = []
114
+ for execution in executions:
115
+ if execution.arguments:
116
+ args = execution.arguments
117
+ var_map = {}
118
+ for key, val in args.items():
119
+ if (
120
+ val.part_list is not None
121
+ and val.part_list.parts is not None
122
+ ):
123
+ part_list = val.part_list.parts
124
+ if part_list and part_list[0].text:
125
+ var_map[key] = part_list[0]
126
+ if var_map and prompt.prompt_data.variables is not None:
127
+ prompt.prompt_data.variables.append(var_map)
128
+
129
+ return prompt
130
+
131
+
132
+ def _raise_for_invalid_prompt(
133
+ prompt: types.Prompt,
134
+ ) -> None:
135
+
136
+ if not prompt.prompt_data:
137
+ raise ValueError("Prompt data must be provided.")
138
+ if not prompt.prompt_data.contents:
139
+ raise ValueError("Prompt contents must be provided.")
140
+ if not prompt.prompt_data.model:
141
+ raise ValueError("Model name must be provided.")
142
+ if (
143
+ prompt.prompt_data
144
+ and prompt.prompt_data.contents
145
+ and len(prompt.prompt_data.contents) > 1
146
+ ):
147
+ raise ValueError("Multi-turn prompts are not currently supported.")
data/conda_envs/evalclaw/lib/python3.11/site-packages/agentplatform/_genai/_prompt_optimizer_utils.py ADDED
@@ -0,0 +1,215 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2025 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
+ """Utility functions for prompt optimizer."""
16
+
17
+ import json
18
+ from typing import Any, Optional, Union
19
+ from typing_extensions import TypeAlias
20
+
21
+ from pydantic import ValidationError
22
+
23
+ from . import types
24
+
25
+ try:
26
+ import pandas as pd # pylint: disable=g-import-not-at-top
27
+
28
+ PandasDataFrame: TypeAlias = pd.DataFrame
29
+ except ImportError:
30
+ pd = None
31
+ PandasDataFrame = Any # type: ignore[misc]
32
+
33
+
34
+ def _construct_input_prompt(
35
+ example_df: PandasDataFrame,
36
+ *,
37
+ prompt_col_name: str,
38
+ model_response_col_name: str,
39
+ rubrics_col_name: str,
40
+ rubrics_evaluations_col_name: str,
41
+ target_response_col_name: str,
42
+ system_instruction: Optional[str] = None,
43
+ ) -> str:
44
+ """Construct the input prompt for the few shot prompt optimizer."""
45
+
46
+ all_prompts = []
47
+ for row in example_df.to_dict(orient="records"):
48
+ example_data = {
49
+ "prompt": row[prompt_col_name],
50
+ "model_response": row[model_response_col_name],
51
+ }
52
+ if rubrics_col_name:
53
+ example_data["rubrics"] = row[rubrics_col_name]
54
+ if rubrics_evaluations_col_name:
55
+ example_data["rubrics_evaluations"] = row[rubrics_evaluations_col_name]
56
+ if target_response_col_name:
57
+ example_data["target_response"] = row[target_response_col_name]
58
+
59
+ json_str = json.dumps(example_data, indent=2)
60
+ all_prompts.append(f"```JSON\n{json_str}\n```")
61
+
62
+ all_prompts_str = "\n\n".join(all_prompts)
63
+
64
+ if system_instruction is None:
65
+ system_instruction = ""
66
+
67
+ return "\n".join(
68
+ [
69
+ "Original System Instructions:\n",
70
+ system_instruction,
71
+ "Examples:\n",
72
+ all_prompts_str,
73
+ "\nNew Output:\n",
74
+ ]
75
+ )
76
+
77
+
78
+ def _get_few_shot_prompt(
79
+ system_instruction: str,
80
+ config: types.OptimizeConfig,
81
+ ) -> str:
82
+ """Builds the few shot prompt."""
83
+
84
+ if config.examples_dataframe is None:
85
+ raise ValueError("The 'examples_dataframe' is required in the config.")
86
+
87
+ if "prompt" not in config.examples_dataframe.columns:
88
+ raise ValueError("'prompt' is required in the examples_dataframe.")
89
+
90
+ if "prompt" not in config.examples_dataframe.columns:
91
+ raise ValueError("'prompt' is required in the examples_dataframe.")
92
+ prompt_col_name = "prompt"
93
+
94
+ if "model_response" not in config.examples_dataframe.columns:
95
+ raise ValueError("'model_response' is required in the example_df.")
96
+ model_response_col_name = "model_response"
97
+
98
+ target_response_col_name = ""
99
+ rubrics_col_name = ""
100
+ rubrics_evaluations_col_name = ""
101
+
102
+ if (
103
+ config.optimization_target
104
+ == types.OptimizeTarget.OPTIMIZATION_TARGET_FEW_SHOT_TARGET_RESPONSE
105
+ ):
106
+ if "target_response" not in config.examples_dataframe.columns:
107
+ raise ValueError("'target_response' is required in the examples_dataframe.")
108
+ target_response_col_name = "target_response"
109
+ if "rubrics" in config.examples_dataframe.columns:
110
+ raise ValueError(
111
+ "Only 'target_response' should be provided "
112
+ "for OPTIMIZATION_TARGET_FEW_SHOT_TARGET_RESPONSE "
113
+ "but 'rubrics' was provided."
114
+ )
115
+
116
+ elif (
117
+ config.optimization_target
118
+ == types.OptimizeTarget.OPTIMIZATION_TARGET_FEW_SHOT_RUBRICS
119
+ ):
120
+ if not {"rubrics", "rubrics_evaluations"}.issubset(
121
+ config.examples_dataframe.columns
122
+ ):
123
+ raise ValueError(
124
+ "rubrics and rubrics_evaluations is required in the"
125
+ "examples_dataframe when rubrics is set."
126
+ )
127
+
128
+ rubrics_col_name = "rubrics"
129
+ rubrics_evaluations_col_name = "rubrics_evaluations"
130
+ if "target_response" in config.examples_dataframe.columns:
131
+ raise ValueError(
132
+ "Only 'rubrics' and 'rubrics_evaluations' should be provided "
133
+ "for OPTIMIZATION_TARGET_FEW_SHOT_RUBRICS "
134
+ "but target_response was provided."
135
+ )
136
+ else:
137
+ raise ValueError("One of 'target_response' or 'rubrics' must be provided.")
138
+
139
+ return _construct_input_prompt(
140
+ config.examples_dataframe,
141
+ prompt_col_name=prompt_col_name,
142
+ model_response_col_name=model_response_col_name,
143
+ rubrics_col_name=rubrics_col_name,
144
+ rubrics_evaluations_col_name=rubrics_evaluations_col_name,
145
+ target_response_col_name=target_response_col_name,
146
+ system_instruction=system_instruction,
147
+ )
148
+
149
+
150
+ def _get_service_account(
151
+ config: types.PromptOptimizerConfigOrDict,
152
+ ) -> str:
153
+ """Get the service account from the config for the custom job."""
154
+ if isinstance(config, dict):
155
+ config = types.PromptOptimizerConfig.model_validate(config)
156
+
157
+ if (
158
+ config.service_account and config.service_account_project_number
159
+ ): # pytype: disable=attribute-error
160
+ raise ValueError(
161
+ "Only one of service_account or "
162
+ "service_account_project_number can be provided."
163
+ )
164
+ elif config.service_account: # pytype: disable=attribute-error
165
+ return config.service_account # pytype: disable=attribute-error
166
+ elif config.service_account_project_number: # pytype: disable=attribute-error
167
+ return f"{config.service_account_project_number}-compute@developer.gserviceaccount.com" # pytype: disable=attribute-error
168
+ else:
169
+ raise ValueError(
170
+ "Either service_account or service_account_project_number " "is required."
171
+ )
172
+
173
+
174
+ def _clean_and_parse_optimized_prompt(output_str: str) -> Optional[Any]:
175
+ """Cleans a string response returned from the prompt optimizer endpoint.
176
+
177
+ Args:
178
+ output_str: The optimized prompt string containing the JSON data,
179
+ potentially with markdown formatting like ```json ... ```.
180
+
181
+ Returns:
182
+ The parsed JSON data, or None if parsing fails.
183
+ """
184
+ lines = output_str.strip().split("\n")
185
+ # Remove markdown delimiters
186
+ if lines and lines[0].strip().startswith("```"):
187
+ cleaned_string = "\n".join(lines[1:-1])
188
+ else:
189
+ cleaned_string = output_str
190
+
191
+ # remove any 'json' labels if they exist on the first line.
192
+ if cleaned_string.strip().startswith("json"):
193
+ cleaned_string = cleaned_string.strip()[4:].strip()
194
+
195
+ try:
196
+ return json.loads(cleaned_string)
197
+ except json.JSONDecodeError as e:
198
+ # TODO(b/437144880): raise errors.ClientError here instead
199
+ raise ValueError(
200
+ f"Failed to parse the response from prompt optimizer endpoint. {e}"
201
+ ) from e
202
+
203
+
204
+ def _parse(
205
+ output_str: str,
206
+ ) -> Union[
207
+ types.prompts.ParsedResponse,
208
+ types.prompts.ParsedResponseFewShot,
209
+ ]:
210
+ """Parses the output string from the prompt optimizer endpoint."""
211
+ parsed_out = _clean_and_parse_optimized_prompt(output_str)
212
+ try:
213
+ return types.prompts.ParsedResponse(**parsed_out)
214
+ except ValidationError:
215
+ return types.prompts.ParsedResponseFewShot(**parsed_out)